Imported Upstream version 3.5.3 01/155901/1
authorDongHun Kwak <dh0128.kwak@samsung.com>
Mon, 16 Oct 2017 11:00:54 +0000 (20:00 +0900)
committerDongHun Kwak <dh0128.kwak@samsung.com>
Mon, 16 Oct 2017 11:01:03 +0000 (20:01 +0900)
Change-Id: I685b7d4e281e9be9dc892ec65b6982aceb90282b
Signed-off-by: DongHun Kwak <dh0128.kwak@samsung.com>
812 files changed:
Doc/Makefile
Doc/c-api/arg.rst
Doc/c-api/buffer.rst
Doc/c-api/bytes.rst
Doc/c-api/capsule.rst
Doc/c-api/dict.rst
Doc/c-api/exceptions.rst
Doc/c-api/import.rst
Doc/c-api/init.rst
Doc/c-api/long.rst
Doc/c-api/mapping.rst
Doc/c-api/module.rst
Doc/c-api/none.rst
Doc/c-api/number.rst
Doc/c-api/set.rst
Doc/c-api/slice.rst
Doc/c-api/structures.rst
Doc/c-api/typeobj.rst
Doc/c-api/unicode.rst
Doc/c-api/veryhigh.rst
Doc/conf.py
Doc/distutils/apiref.rst
Doc/distutils/builtdist.rst
Doc/distutils/configfile.rst
Doc/distutils/examples.rst
Doc/distutils/extending.rst
Doc/distutils/packageindex.rst
Doc/distutils/setupscript.rst
Doc/distutils/sourcedist.rst
Doc/extending/building.rst
Doc/extending/embedding.rst
Doc/extending/extending.rst
Doc/extending/newtypes.rst
Doc/faq/design.rst
Doc/faq/extending.rst
Doc/faq/general.rst
Doc/faq/gui.rst
Doc/howto/argparse.rst
Doc/howto/clinic.rst
Doc/howto/cporting.rst
Doc/howto/descriptor.rst
Doc/howto/functional.rst
Doc/howto/ipaddress.rst
Doc/howto/logging-cookbook.rst
Doc/howto/logging.rst
Doc/howto/pyporting.rst
Doc/howto/regex.rst
Doc/howto/sockets.rst
Doc/howto/sorting.rst
Doc/howto/unicode.rst
Doc/howto/urllib2.rst
Doc/includes/email-alternative-new-api.py
Doc/install/index.rst
Doc/library/2to3.rst
Doc/library/argparse.rst
Doc/library/array.rst
Doc/library/ast.rst
Doc/library/asyncio-dev.rst
Doc/library/asyncio-eventloop.rst
Doc/library/asyncio-eventloops.rst
Doc/library/asyncio-protocol.rst
Doc/library/asyncio-stream.rst
Doc/library/asyncio-subprocess.rst
Doc/library/asyncio-task.rst
Doc/library/asyncio.rst
Doc/library/asyncore.rst
Doc/library/bdb.rst
Doc/library/binascii.rst
Doc/library/builtins.rst
Doc/library/calendar.rst
Doc/library/cgi.rst
Doc/library/cmath.rst
Doc/library/cmd.rst
Doc/library/codecs.rst
Doc/library/collections.abc.rst
Doc/library/collections.rst
Doc/library/configparser.rst
Doc/library/copy.rst
Doc/library/ctypes.rst
Doc/library/curses.ascii.rst
Doc/library/curses.rst
Doc/library/datetime.rst
Doc/library/dbm.rst
Doc/library/decimal.rst
Doc/library/difflib.rst
Doc/library/dis.rst
Doc/library/doctest.rst
Doc/library/email-examples.rst
Doc/library/email.contentmanager.rst
Doc/library/email.iterators.rst
Doc/library/email.message.rst
Doc/library/email.parser.rst
Doc/library/email.policy.rst
Doc/library/ensurepip.rst
Doc/library/enum.rst
Doc/library/fnmatch.rst
Doc/library/ftplib.rst
Doc/library/functions.rst
Doc/library/functools.rst
Doc/library/gc.rst
Doc/library/gettext.rst
Doc/library/hashlib.rst
Doc/library/hmac.rst
Doc/library/html.parser.rst
Doc/library/http.client.rst
Doc/library/http.server.rst
Doc/library/idle.rst
Doc/library/imaplib.rst
Doc/library/importlib.rst
Doc/library/inspect.rst
Doc/library/io.rst
Doc/library/ipaddress.rst
Doc/library/json.rst
Doc/library/linecache.rst
Doc/library/logging.config.rst
Doc/library/logging.handlers.rst
Doc/library/logging.rst
Doc/library/lzma.rst
Doc/library/mmap.rst
Doc/library/msvcrt.rst
Doc/library/multiprocessing.rst
Doc/library/netrc.rst
Doc/library/nntplib.rst
Doc/library/optparse.rst
Doc/library/os.rst
Doc/library/pathlib.rst
Doc/library/pdb.rst
Doc/library/pickletools.rst
Doc/library/pkgutil.rst
Doc/library/py_compile.rst
Doc/library/pyexpat.rst
Doc/library/queue.rst
Doc/library/quopri.rst
Doc/library/random.rst
Doc/library/re.rst
Doc/library/readline.rst
Doc/library/resource.rst
Doc/library/select.rst
Doc/library/selectors.rst
Doc/library/shelve.rst
Doc/library/shutil.rst
Doc/library/signal.rst
Doc/library/smtpd.rst
Doc/library/smtplib.rst
Doc/library/socket.rst
Doc/library/socketserver.rst
Doc/library/sqlite3.rst
Doc/library/ssl.rst
Doc/library/statistics.rst
Doc/library/stdtypes.rst
Doc/library/string.rst
Doc/library/subprocess.rst
Doc/library/sunau.rst
Doc/library/sys.rst
Doc/library/sysconfig.rst
Doc/library/tarfile.rst
Doc/library/test.rst
Doc/library/threading.rst
Doc/library/tkinter.rst
Doc/library/tkinter.ttk.rst
Doc/library/token.rst
Doc/library/traceback.rst
Doc/library/tracemalloc.rst
Doc/library/turtle.rst
Doc/library/typing.rst
Doc/library/unittest.mock.rst
Doc/library/unittest.rst
Doc/library/urllib.parse.rst
Doc/library/urllib.request.rst
Doc/library/uuid.rst
Doc/library/venv.rst
Doc/library/warnings.rst
Doc/library/wave.rst
Doc/library/weakref.rst
Doc/library/winreg.rst
Doc/library/xml.dom.minidom.rst
Doc/library/xml.dom.pulldom.rst
Doc/library/xml.dom.rst
Doc/library/xml.etree.elementtree.rst
Doc/library/xml.rst
Doc/library/xml.sax.reader.rst
Doc/library/xml.sax.utils.rst
Doc/library/xmlrpc.client.rst
Doc/library/xmlrpc.server.rst
Doc/library/zipapp.rst
Doc/library/zipfile.rst
Doc/library/zipimport.rst
Doc/license.rst
Doc/reference/compound_stmts.rst
Doc/reference/datamodel.rst
Doc/reference/expressions.rst
Doc/reference/import.rst
Doc/reference/lexical_analysis.rst
Doc/tools/extensions/suspicious.py
Doc/tools/pydoctheme/static/pydoctheme.css
Doc/tools/static/version_switch.js
Doc/tools/templates/customsourcelink.html [new file with mode: 0644]
Doc/tools/templates/indexsidebar.html
Doc/tools/templates/layout.html
Doc/tutorial/classes.rst
Doc/tutorial/controlflow.rst
Doc/tutorial/errors.rst
Doc/tutorial/floatingpoint.rst
Doc/tutorial/interpreter.rst
Doc/tutorial/modules.rst
Doc/tutorial/stdlib2.rst
Doc/using/cmdline.rst
Doc/using/venv-create.inc
Doc/using/windows.rst
Doc/whatsnew/2.0.rst
Doc/whatsnew/2.1.rst
Doc/whatsnew/2.2.rst
Doc/whatsnew/2.3.rst
Doc/whatsnew/2.4.rst
Doc/whatsnew/2.5.rst
Doc/whatsnew/2.6.rst
Doc/whatsnew/2.7.rst
Doc/whatsnew/3.0.rst
Doc/whatsnew/3.1.rst
Doc/whatsnew/3.2.rst
Doc/whatsnew/3.3.rst
Doc/whatsnew/3.5.rst
Doc/whatsnew/changelog.rst
Grammar/Grammar
Include/abstract.h
Include/dictobject.h
Include/genobject.h
Include/longobject.h
Include/moduleobject.h
Include/patchlevel.h
Include/pyfpe.h
Include/pymacconfig.h
Include/pymath.h
Include/pyport.h
Include/unicodeobject.h
LICENSE
Lib/_collections_abc.py
Lib/_pydecimal.py
Lib/_pyio.py
Lib/antigravity.py
Lib/asyncio/base_events.py
Lib/asyncio/base_subprocess.py
Lib/asyncio/coroutines.py
Lib/asyncio/events.py
Lib/asyncio/futures.py
Lib/asyncio/locks.py
Lib/asyncio/proactor_events.py
Lib/asyncio/queues.py
Lib/asyncio/selector_events.py
Lib/asyncio/sslproto.py
Lib/asyncio/streams.py
Lib/asyncio/tasks.py
Lib/asyncio/test_utils.py
Lib/asyncio/transports.py
Lib/asyncio/unix_events.py
Lib/calendar.py
Lib/collections/__init__.py
Lib/compileall.py
Lib/concurrent/futures/process.py
Lib/concurrent/futures/thread.py
Lib/configparser.py
Lib/contextlib.py
Lib/ctypes/macholib/dyld.py
Lib/ctypes/test/test_callbacks.py
Lib/ctypes/test/test_find.py
Lib/ctypes/test/test_frombuffer.py
Lib/ctypes/test/test_numbers.py
Lib/ctypes/test/test_structures.py
Lib/ctypes/util.py
Lib/curses/ascii.py
Lib/curses/textpad.py
Lib/datetime.py
Lib/dbm/dumb.py
Lib/distutils/_msvccompiler.py
Lib/distutils/command/build_ext.py
Lib/distutils/command/upload.py
Lib/distutils/command/wininst-14.0-amd64.exe
Lib/distutils/command/wininst-14.0.exe
Lib/distutils/config.py
Lib/distutils/filelist.py
Lib/distutils/tests/test_bdist_rpm.py
Lib/distutils/tests/test_build_ext.py
Lib/distutils/tests/test_check.py
Lib/distutils/tests/test_config.py
Lib/distutils/tests/test_filelist.py
Lib/distutils/tests/test_msvc9compiler.py
Lib/distutils/tests/test_msvccompiler.py
Lib/distutils/tests/test_register.py
Lib/distutils/tests/test_sdist.py
Lib/distutils/tests/test_upload.py
Lib/distutils/unixccompiler.py
Lib/email/_header_value_parser.py
Lib/email/base64mime.py
Lib/email/contentmanager.py
Lib/email/feedparser.py
Lib/email/generator.py
Lib/email/message.py
Lib/email/mime/text.py
Lib/email/policy.py
Lib/email/quoprimime.py
Lib/ensurepip/__init__.py
Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl [deleted file]
Lib/ensurepip/_bundled/pip-9.0.1-py2.py3-none-any.whl [new file with mode: 0644]
Lib/ensurepip/_bundled/setuptools-28.8.0-py2.py3-none-any.whl [moved from Lib/ensurepip/_bundled/setuptools-20.10.1-py2.py3-none-any.whl with 51% similarity]
Lib/fractions.py
Lib/functools.py
Lib/gettext.py
Lib/http/client.py
Lib/http/cookiejar.py
Lib/idlelib/Bindings.py
Lib/idlelib/CallTipWindow.py
Lib/idlelib/NEWS.txt
Lib/idlelib/NEWS2x.txt [new file with mode: 0644]
Lib/idlelib/ParenMatch.py
Lib/idlelib/README.txt
Lib/idlelib/aboutDialog.py
Lib/idlelib/configDialog.py
Lib/idlelib/configHandler.py
Lib/idlelib/help.html
Lib/idlelib/help.py
Lib/idlelib/idle.py
Lib/idlelib/idle_test/test_autocomplete.py
Lib/idlelib/idle_test/test_configdialog.py
Lib/idlelib/idle_test/test_editmenu.py
Lib/idlelib/idle_test/test_formatparagraph.py
Lib/idlelib/idle_test/test_help_about.py [new file with mode: 0644]
Lib/idlelib/idle_test/test_hyperparser.py
Lib/idlelib/idle_test/test_idlehistory.py
Lib/idlelib/idle_test/test_textview.py
Lib/idlelib/idle_test/test_widgetredir.py
Lib/idlelib/run.py
Lib/idlelib/textView.py
Lib/imaplib.py
Lib/imp.py
Lib/importlib/_bootstrap_external.py
Lib/importlib/util.py
Lib/inspect.py
Lib/json/__init__.py
Lib/lib2to3/Grammar.txt
Lib/lib2to3/fixer_base.py
Lib/lib2to3/fixes/fix_apply.py
Lib/lib2to3/fixes/fix_callable.py [deleted file]
Lib/lib2to3/fixes/fix_intern.py
Lib/lib2to3/fixes/fix_reload.py
Lib/lib2to3/pgen2/driver.py
Lib/lib2to3/pgen2/grammar.py
Lib/lib2to3/pgen2/pgen.py
Lib/lib2to3/tests/support.py
Lib/lib2to3/tests/test_fixers.py
Lib/lib2to3/tests/test_parser.py
Lib/lib2to3/tests/test_refactor.py
Lib/logging/__init__.py
Lib/logging/handlers.py
Lib/mailcap.py
Lib/multiprocessing/context.py
Lib/multiprocessing/managers.py
Lib/multiprocessing/spawn.py
Lib/os.py
Lib/pdb.py
Lib/pickle.py
Lib/pkgutil.py
Lib/platform.py
Lib/plistlib.py
Lib/posixpath.py
Lib/pstats.py
Lib/pydoc.py
Lib/pydoc_data/topics.py
Lib/random.py
Lib/runpy.py
Lib/selectors.py
Lib/shlex.py
Lib/shutil.py
Lib/smtplib.py
Lib/socket.py
Lib/sqlite3/test/dbapi.py
Lib/sqlite3/test/factory.py
Lib/sqlite3/test/hooks.py
Lib/sqlite3/test/regression.py
Lib/sqlite3/test/transactions.py
Lib/sqlite3/test/types.py
Lib/sqlite3/test/userfunctions.py
Lib/ssl.py
Lib/subprocess.py
Lib/tarfile.py
Lib/test/_test_multiprocessing.py
Lib/test/allsans.pem [new file with mode: 0644]
Lib/test/cfgparser.2
Lib/test/check_soundcard.vbs [deleted file]
Lib/test/datetimetester.py
Lib/test/eintrdata/eintr_tester.py
Lib/test/mailcap.txt
Lib/test/make_ssl_certs.py
Lib/test/mp_preload.py [new file with mode: 0644]
Lib/test/pickletester.py
Lib/test/regrtest.py
Lib/test/ssl_servers.py
Lib/test/ssltests.py
Lib/test/support/__init__.py
Lib/test/support/script_helper.py
Lib/test/test_argparse.py
Lib/test/test_array.py
Lib/test/test_asyncio/test_base_events.py
Lib/test/test_asyncio/test_events.py
Lib/test/test_asyncio/test_futures.py
Lib/test/test_asyncio/test_locks.py
Lib/test/test_asyncio/test_pep492.py
Lib/test/test_asyncio/test_proactor_events.py
Lib/test/test_asyncio/test_queues.py
Lib/test/test_asyncio/test_selector_events.py
Lib/test/test_asyncio/test_sslproto.py
Lib/test/test_asyncio/test_streams.py
Lib/test/test_asyncio/test_subprocess.py
Lib/test/test_asyncio/test_tasks.py
Lib/test/test_asyncio/test_unix_events.py
Lib/test/test_asyncio/test_windows_events.py
Lib/test/test_binascii.py
Lib/test/test_builtin.py
Lib/test/test_bytes.py
Lib/test/test_bz2.py
Lib/test/test_calendar.py
Lib/test/test_cmd_line.py
Lib/test/test_cmd_line_script.py
Lib/test/test_code.py
Lib/test/test_codecs.py
Lib/test/test_collections.py
Lib/test/test_compile.py
Lib/test/test_complex.py
Lib/test/test_concurrent_futures.py
Lib/test/test_configparser.py
Lib/test/test_contextlib.py
Lib/test/test_coroutines.py
Lib/test/test_curses.py
Lib/test/test_dbm_dumb.py
Lib/test/test_decimal.py
Lib/test/test_defaultdict.py
Lib/test/test_deque.py
Lib/test/test_descr.py
Lib/test/test_dict.py
Lib/test/test_dictviews.py
Lib/test/test_doctest.py
Lib/test/test_docxmlrpc.py
Lib/test/test_dummy_thread.py
Lib/test/test_email/__init__.py
Lib/test/test_email/test_email.py
Lib/test/test_email/test_inversion.py
Lib/test/test_email/test_message.py
Lib/test/test_email/test_parser.py
Lib/test/test_enum.py
Lib/test/test_exceptions.py
Lib/test/test_extcall.py
Lib/test/test_fileio.py
Lib/test/test_format.py
Lib/test/test_fractions.py
Lib/test/test_functools.py
Lib/test/test_future.py
Lib/test/test_gc.py
Lib/test/test_gdb.py
Lib/test/test_generators.py
Lib/test/test_genericpath.py
Lib/test/test_gettext.py
Lib/test/test_http_cookiejar.py
Lib/test/test_httplib.py
Lib/test/test_imaplib.py
Lib/test/test_importlib/extension/test_case_sensitivity.py
Lib/test/test_importlib/extension/test_loader.py
Lib/test/test_importlib/import_/test_meta_path.py
Lib/test/test_importlib/source/test_case_sensitivity.py
Lib/test/test_importlib/test_lazy.py
Lib/test/test_importlib/test_util.py
Lib/test/test_importlib/util.py
Lib/test/test_inspect.py
Lib/test/test_io.py
Lib/test/test_ipaddress.py
Lib/test/test_itertools.py
Lib/test/test_json/test_decode.py
Lib/test/test_logging.py
Lib/test/test_long.py
Lib/test/test_lzma.py
Lib/test/test_mailcap.py
Lib/test/test_math.py
Lib/test/test_mmap.py
Lib/test/test_module.py
Lib/test/test_nntplib.py
Lib/test/test_os.py
Lib/test/test_parser.py
Lib/test/test_pdb.py
Lib/test/test_pep247.py
Lib/test/test_pickle.py
Lib/test/test_pkgutil.py
Lib/test/test_platform.py
Lib/test/test_plistlib.py
Lib/test/test_poll.py
Lib/test/test_posixpath.py
Lib/test/test_pydoc.py
Lib/test/test_pyexpat.py
Lib/test/test_random.py
Lib/test/test_range.py
Lib/test/test_re.py
Lib/test/test_readline.py
Lib/test/test_regrtest.py
Lib/test/test_resource.py
Lib/test/test_runpy.py
Lib/test/test_selectors.py
Lib/test/test_set.py
Lib/test/test_shelve.py
Lib/test/test_shlex.py
Lib/test/test_shutil.py
Lib/test/test_socket.py
Lib/test/test_ssl.py
Lib/test/test_structseq.py
Lib/test/test_subprocess.py
Lib/test/test_support.py
Lib/test/test_symtable.py
Lib/test/test_syntax.py
Lib/test/test_sys.py
Lib/test/test_tarfile.py
Lib/test/test_textwrap.py
Lib/test/test_threading.py
Lib/test/test_tools/test_fixcid.py [new file with mode: 0644]
Lib/test/test_tools/test_i18n.py
Lib/test/test_trace.py
Lib/test/test_traceback.py
Lib/test/test_typing.py
Lib/test/test_unicode.py
Lib/test/test_unpack_ex.py
Lib/test/test_urllib.py
Lib/test/test_urllib2_localnet.py
Lib/test/test_urlparse.py
Lib/test/test_uuid.py
Lib/test/test_venv.py
Lib/test/test_warnings/__init__.py
Lib/test/test_weakref.py
Lib/test/test_webbrowser.py
Lib/test/test_winreg.py
Lib/test/test_winsound.py
Lib/test/test_xml_etree.py
Lib/test/test_xml_etree_c.py
Lib/test/test_zipfile.py
Lib/test/test_zipimport.py
Lib/test/test_zlib.py
Lib/textwrap.py
Lib/threading.py
Lib/tkinter/__init__.py
Lib/tkinter/test/test_tkinter/test_variables.py
Lib/tkinter/test/test_ttk/test_extensions.py
Lib/tkinter/test/test_ttk/test_widgets.py
Lib/tkinter/tix.py
Lib/tkinter/ttk.py
Lib/traceback.py
Lib/turtle.py
Lib/typing.py
Lib/unittest/__init__.py
Lib/unittest/case.py
Lib/unittest/mock.py
Lib/unittest/test/test_case.py
Lib/unittest/test/test_discovery.py
Lib/unittest/test/test_result.py
Lib/unittest/test/testmock/testcallable.py
Lib/unittest/test/testmock/testhelpers.py
Lib/urllib/parse.py
Lib/urllib/request.py
Lib/venv/scripts/posix/activate
Lib/venv/scripts/posix/activate.csh
Lib/venv/scripts/posix/activate.fish
Lib/weakref.py
Lib/webbrowser.py
Lib/xml/dom/expatbuilder.py
Lib/xml/etree/ElementTree.py
Lib/xmlrpc/server.py
Lib/zipfile.py
Mac/BuildScript/build-installer.py
Mac/BuildScript/openssl_sdk_makedepend.patch
Mac/IDLE/IDLE.app/Contents/Info.plist
Mac/IDLE/IDLE.app/Contents/Resources/idlemain.py
Mac/PythonLauncher/Info.plist.in
Mac/PythonLauncher/MyAppDelegate.m
Mac/Resources/app/Info.plist.in
Mac/Resources/framework/Info.plist.in
Makefile.pre.in
Misc/ACKS
Misc/HISTORY
Misc/NEWS
Misc/coverity_model.c
Misc/python.man
Modules/_bz2module.c
Modules/_codecsmodule.c
Modules/_cryptmodule.c
Modules/_csv.c
Modules/_ctypes/_ctypes.c
Modules/_ctypes/_ctypes_test.c
Modules/_ctypes/callbacks.c
Modules/_ctypes/callproc.c
Modules/_ctypes/cfield.c
Modules/_ctypes/ctypes.h
Modules/_ctypes/libffi_msvc/ffi.c
Modules/_ctypes/libffi_osx/ffi.c
Modules/_ctypes/stgdict.c
Modules/_cursesmodule.c
Modules/_dbmmodule.c
Modules/_decimal/_decimal.c
Modules/_elementtree.c
Modules/_functoolsmodule.c
Modules/_gdbmmodule.c
Modules/_hashopenssl.c
Modules/_io/_iomodule.c
Modules/_io/clinic/_iomodule.c.h
Modules/_io/iobase.c
Modules/_io/textio.c
Modules/_localemodule.c
Modules/_lsprof.c
Modules/_lzmamodule.c
Modules/_multiprocessing/semaphore.c
Modules/_opcode.c
Modules/_operator.c
Modules/_pickle.c
Modules/_posixsubprocess.c
Modules/_sqlite/connection.c
Modules/_sqlite/connection.h
Modules/_sqlite/cursor.c
Modules/_sqlite/module.h
Modules/_sre.c
Modules/_ssl.c
Modules/_testcapimodule.c
Modules/_testmultiphase.c
Modules/_threadmodule.c
Modules/_tkinter.c
Modules/_tracemalloc.c
Modules/_weakref.c
Modules/_winapi.c
Modules/arraymodule.c
Modules/audioop.c
Modules/binascii.c
Modules/cjkcodecs/multibytecodec.c
Modules/clinic/_codecsmodule.c.h
Modules/clinic/_cryptmodule.c.h
Modules/clinic/_dbmmodule.c.h
Modules/clinic/_gdbmmodule.c.h
Modules/clinic/_lzmamodule.c.h
Modules/clinic/_opcode.c.h
Modules/clinic/_pickle.c.h
Modules/clinic/_sre.c.h
Modules/clinic/_ssl.c.h
Modules/clinic/_tkinter.c.h
Modules/clinic/_weakref.c.h
Modules/clinic/_winapi.c.h
Modules/clinic/arraymodule.c.h
Modules/clinic/audioop.c.h
Modules/clinic/binascii.c.h
Modules/clinic/cmathmodule.c.h
Modules/clinic/fcntlmodule.c.h
Modules/clinic/grpmodule.c.h
Modules/clinic/md5module.c.h
Modules/clinic/posixmodule.c.h
Modules/clinic/pwdmodule.c.h
Modules/clinic/pyexpat.c.h
Modules/clinic/sha1module.c.h
Modules/clinic/sha256module.c.h
Modules/clinic/sha512module.c.h
Modules/clinic/signalmodule.c.h
Modules/clinic/spwdmodule.c.h
Modules/clinic/zlibmodule.c.h
Modules/cmathmodule.c
Modules/expat/xmlrole.c
Modules/expat/xmltok.c
Modules/fcntlmodule.c
Modules/getpath.c
Modules/grpmodule.c
Modules/hashtable.c
Modules/itertoolsmodule.c
Modules/ld_so_aix.in
Modules/makesetup
Modules/mathmodule.c
Modules/md5module.c
Modules/mmapmodule.c
Modules/ossaudiodev.c
Modules/posixmodule.c
Modules/pwdmodule.c
Modules/pyexpat.c
Modules/readline.c
Modules/resource.c
Modules/sha1module.c
Modules/sha256module.c
Modules/sha512module.c
Modules/signalmodule.c
Modules/socketmodule.c
Modules/spwdmodule.c
Modules/unicodedata.c
Modules/zipimport.c
Modules/zlibmodule.c
Objects/abstract.c
Objects/bytearrayobject.c
Objects/bytesobject.c
Objects/codeobject.c
Objects/complexobject.c
Objects/dictobject.c
Objects/exceptions.c
Objects/funcobject.c
Objects/genobject.c
Objects/listobject.c
Objects/listsort.txt
Objects/longobject.c
Objects/memoryobject.c
Objects/moduleobject.c
Objects/object.c
Objects/odictobject.c
Objects/rangeobject.c
Objects/typeobject.c
Objects/typeslots.py
Objects/unicodeobject.c
PC/_msi.c
PC/bdist_wininst/install.c
PC/clinic/msvcrtmodule.c.h
PC/clinic/winreg.c.h
PC/clinic/winsound.c.h
PC/icons.mak [deleted file]
PC/icons.rc [deleted file]
PC/launcher.c
PC/make_versioninfo.c [deleted file]
PC/msvcrtmodule.c
PC/pyshellext.cpp [new file with mode: 0644]
PC/pyshellext.def [new file with mode: 0644]
PC/pyshellext.idl [new file with mode: 0644]
PC/pyshellext.rc [new file with mode: 0644]
PC/pyshellext_d.def [new file with mode: 0644]
PC/python.manifest
PC/python3.def
PC/validate_ucrtbase.py
PC/winreg.c
PC/winsound.c
PCbuild/build.bat
PCbuild/get_externals.bat
PCbuild/pcbuild.proj
PCbuild/pcbuild.sln
PCbuild/prepare_ssl.py
PCbuild/pyproject.props
PCbuild/pyshellext.vcxproj [new file with mode: 0644]
PCbuild/pyshellext.vcxproj.filters [new file with mode: 0644]
PCbuild/python.props
PCbuild/python.vcxproj
PCbuild/python3dll.vcxproj
PCbuild/pythoncore.vcxproj
PCbuild/readme.txt
PCbuild/tcl.vcxproj
PCbuild/tix.vcxproj
PCbuild/tk.vcxproj
Parser/asdl_c.py
Parser/tokenizer.c
Programs/_freeze_importlib.c
Python/Python-ast.c
Python/_warnings.c
Python/ast.c
Python/bltinmodule.c
Python/ceval.c
Python/clinic/bltinmodule.c.h
Python/clinic/import.c.h
Python/compile.c
Python/condvar.h
Python/errors.c
Python/formatter_unicode.c
Python/future.c
Python/getargs.c
Python/getcopyright.c
Python/import.c
Python/importdl.c
Python/importlib.h
Python/importlib_external.h
Python/pystate.c
Python/pythonrun.c
Python/random.c
Python/symtable.c
Python/sysmodule.c
Python/traceback.c
README
Tools/clinic/clinic.py
Tools/clinic/clinic_test.py
Tools/demo/redemo.py
Tools/freeze/freeze.py
Tools/freeze/winmakemakefile.py
Tools/gdb/libpython.py
Tools/i18n/pygettext.py
Tools/importbench/importbench.py
Tools/msi/build.bat
Tools/msi/buildrelease.bat
Tools/msi/bundle/Default.wxl
Tools/msi/bundle/bootstrap/PythonBootstrapperApplication.cpp
Tools/msi/bundle/bootstrap/pythonba.vcxproj
Tools/msi/bundle/bundle.targets
Tools/msi/bundle/bundle.wxs
Tools/msi/bundle/packagegroups/launcher.wxs
Tools/msi/distutils.command.bdist_wininst.py [new file with mode: 0644]
Tools/msi/doc/doc.wxs
Tools/msi/launcher/launcher.wixproj
Tools/msi/launcher/launcher.wxs
Tools/msi/launcher/launcher_files.wxs
Tools/msi/launcher/launcher_reg.wxs
Tools/msi/lib/lib_files.wxs
Tools/msi/make_zip.proj
Tools/msi/make_zip.py
Tools/msi/msi.props
Tools/msi/purge.py [new file with mode: 0644]
Tools/nuget/build.bat [new file with mode: 0644]
Tools/nuget/make_pkg.proj [new file with mode: 0644]
Tools/nuget/python.nuspec [new file with mode: 0644]
Tools/nuget/pythonx86.nuspec [new file with mode: 0644]
Tools/scripts/fixcid.py
aclocal.m4
config.guess
config.sub
configure
configure.ac
pyconfig.h.in
setup.py

index a42e98b..10c3288 100644 (file)
@@ -162,12 +162,12 @@ serve:
 
 # for development releases: always build
 autobuild-dev:
-       make dist SPHINXOPTS='-A daily=1 -A versionswitcher=1'
+       make dist SPHINXOPTS='$(SPHINXOPTS) -A daily=1 -A versionswitcher=1'
        -make suspicious
 
 # for quick rebuilds (HTML only)
-autobuild-html:
-       make html SPHINXOPTS='-A daily=1 -A versionswitcher=1'
+autobuild-dev-html:
+       make html SPHINXOPTS='$(SPHINXOPTS) -A daily=1 -A versionswitcher=1'
 
 # for stable releases: only build if not in pre-release stage (alpha, beta)
 # release candidate downloads are okay, since the stable tree can be in that stage
@@ -177,3 +177,10 @@ autobuild-stable:
                exit 1;; \
        esac
        @make autobuild-dev
+
+autobuild-stable-html:
+       @case $(DISTVERSION) in *[ab]*) \
+               echo "Not building; $(DISTVERSION) is not a release version."; \
+               exit 1;; \
+       esac
+       @make autobuild-dev-html
index 983d113..1123972 100644 (file)
@@ -32,8 +32,12 @@ Strings and buffers
 
 These formats allow accessing an object as a contiguous chunk of memory.
 You don't have to provide raw storage for the returned unicode or bytes
-area.  Also, you won't have to release any memory yourself, except with the
-``es``, ``es#``, ``et`` and ``et#`` formats.
+area.
+
+In general, when a format sets a pointer to a buffer, the buffer is
+managed by the corresponding Python object, and the buffer shares
+the lifetime of this object.  You won't have to release any memory yourself.
+The only exceptions are ``es``, ``es#``, ``et`` and ``et#``.
 
 However, when a :c:type:`Py_buffer` structure gets filled, the underlying
 buffer is locked so that the caller can subsequently use the buffer even
@@ -44,6 +48,11 @@ in any early abort case).
 
 Unless otherwise stated, buffers are not NUL-terminated.
 
+Some formats require a read-only :term:`bytes-like object`, and set a
+pointer instead of a buffer structure.  They work by checking that
+the object's :c:member:`PyBufferProcs.bf_releasebuffer` field is *NULL*,
+which disallows mutable objects such as :class:`bytearray`.
+
 .. note::
 
    For all ``#`` variants of formats (``s#``, ``y#``, etc.), the type of
@@ -59,8 +68,8 @@ Unless otherwise stated, buffers are not NUL-terminated.
    Convert a Unicode object to a C pointer to a character string.
    A pointer to an existing string is stored in the character pointer
    variable whose address you pass.  The C string is NUL-terminated.
-   The Python string must not contain embedded NUL bytes; if it does,
-   a :exc:`TypeError` exception is raised. Unicode objects are converted
+   The Python string must not contain embedded null code points; if it does,
+   a :exc:`ValueError` exception is raised. Unicode objects are converted
    to C strings using ``'utf-8'`` encoding. If this conversion fails, a
    :exc:`UnicodeError` is raised.
 
@@ -71,6 +80,10 @@ Unless otherwise stated, buffers are not NUL-terminated.
       preferable to use the ``O&`` format with :c:func:`PyUnicode_FSConverter`
       as *converter*.
 
+   .. versionchanged:: 3.5
+      Previously, :exc:`TypeError` was raised when embedded null code points
+      were encountered in the Python string.
+
 ``s*`` (:class:`str` or :term:`bytes-like object`) [Py_buffer]
    This format accepts Unicode objects as well as bytes-like objects.
    It fills a :c:type:`Py_buffer` structure provided by the caller.
@@ -78,8 +91,8 @@ Unless otherwise stated, buffers are not NUL-terminated.
    Unicode objects are converted to C strings using ``'utf-8'`` encoding.
 
 ``s#`` (:class:`str`, read-only :term:`bytes-like object`) [const char \*, int or :c:type:`Py_ssize_t`]
-   Like ``s*``, except that it doesn't accept mutable bytes-like objects
-   such as :class:`bytearray`.  The result is stored into two C variables,
+   Like ``s*``, except that it doesn't accept mutable objects.
+   The result is stored into two C variables,
    the first one a pointer to a C string, the second one its length.
    The string may contain embedded null bytes. Unicode objects are converted
    to C strings using ``'utf-8'`` encoding.
@@ -99,9 +112,13 @@ Unless otherwise stated, buffers are not NUL-terminated.
 ``y`` (read-only :term:`bytes-like object`) [const char \*]
    This format converts a bytes-like object to a C pointer to a character
    string; it does not accept Unicode objects.  The bytes buffer must not
-   contain embedded NUL bytes; if it does, a :exc:`TypeError`
+   contain embedded null bytes; if it does, a :exc:`ValueError`
    exception is raised.
 
+   .. versionchanged:: 3.5
+      Previously, :exc:`TypeError` was raised when embedded null bytes were
+      encountered in the bytes buffer.
+
 ``y*`` (:term:`bytes-like object`) [Py_buffer]
    This variant on ``s*`` doesn't accept Unicode objects, only
    bytes-like objects.  **This is the recommended way to accept
@@ -127,17 +144,17 @@ Unless otherwise stated, buffers are not NUL-terminated.
    pointer variable, which will be filled with the pointer to an existing
    Unicode buffer.  Please note that the width of a :c:type:`Py_UNICODE`
    character depends on compilation options (it is either 16 or 32 bits).
-   The Python string must not contain embedded NUL characters; if it does,
-   a :exc:`TypeError` exception is raised.
+   The Python string must not contain embedded null code points; if it does,
+   a :exc:`ValueError` exception is raised.
 
-   .. note::
-      Since ``u`` doesn't give you back the length of the string, and it
-      may contain embedded NUL characters, it is recommended to use ``u#``
-      or ``U`` instead.
+   .. versionchanged:: 3.5
+      Previously, :exc:`TypeError` was raised when embedded null code points
+      were encountered in the Python string.
 
 ``u#`` (:class:`str`) [Py_UNICODE \*, int]
    This variant on ``u`` stores into two C variables, the first one a pointer to a
-   Unicode data buffer, the second one its length.
+   Unicode data buffer, the second one its length.  This variant allows
+   null code points.
 
 ``Z`` (:class:`str` or ``None``) [Py_UNICODE \*]
    Like ``u``, but the Python object may also be ``None``, in which case the
@@ -325,7 +342,7 @@ Other objects
 ``p`` (:class:`bool`) [int]
    Tests the value passed in for truth (a boolean **p**\ redicate) and converts
    the result to its equivalent C true/false integer value.
-   Sets the int to 1 if the expression was true and 0 if it was false.
+   Sets the int to ``1`` if the expression was true and ``0`` if it was false.
    This accepts any valid Python value.  See :ref:`truth` for more
    information about how Python tests values for truth.
 
index 45c9488..3d851b7 100644 (file)
@@ -156,7 +156,7 @@ a buffer, see :c:func:`PyObject_GetBuffer`.
    .. c:member:: int ndim
 
       The number of dimensions the memory represents as an n-dimensional array.
-      If it is 0, :c:member:`~Py_buffer.buf` points to a single item representing
+      If it is ``0``, :c:member:`~Py_buffer.buf` points to a single item representing
       a scalar. In this case, :c:member:`~Py_buffer.shape`, :c:member:`~Py_buffer.strides`
       and :c:member:`~Py_buffer.suboffsets` MUST be *NULL*.
 
@@ -427,7 +427,7 @@ Buffer-related functions
 
 .. c:function:: int PyObject_CheckBuffer(PyObject *obj)
 
-   Return 1 if *obj* supports the buffer interface otherwise 0.  When 1 is
+   Return ``1`` if *obj* supports the buffer interface otherwise ``0``.  When ``1`` is
    returned, it doesn't guarantee that :c:func:`PyObject_GetBuffer` will
    succeed.
 
@@ -437,7 +437,7 @@ Buffer-related functions
    Send a request to *exporter* to fill in *view* as specified by  *flags*.
    If the exporter cannot provide a buffer of the exact type, it MUST raise
    :c:data:`PyExc_BufferError`, set :c:member:`view->obj` to *NULL* and
-   return -1.
+   return ``-1``.
 
    On success, fill in *view*, set :c:member:`view->obj` to a new reference
    to *exporter* and return 0. In the case of chained buffer providers
@@ -468,9 +468,9 @@ Buffer-related functions
 
 .. c:function:: int PyBuffer_IsContiguous(Py_buffer *view, char order)
 
-   Return 1 if the memory defined by the *view* is C-style (*order* is
+   Return ``1`` if the memory defined by the *view* is C-style (*order* is
    ``'C'``) or Fortran-style (*order* is ``'F'``) :term:`contiguous` or either one
-   (*order* is ``'A'``).  Return 0 otherwise.
+   (*order* is ``'A'``).  Return ``0`` otherwise.
 
 
 .. c:function:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char order)
@@ -492,7 +492,7 @@ Buffer-related functions
 
    On success, set :c:member:`view->obj` to a new reference to *exporter* and
    return 0. Otherwise, raise :c:data:`PyExc_BufferError`, set
-   :c:member:`view->obj` to *NULL* and return -1;
+   :c:member:`view->obj` to *NULL* and return ``-1``;
 
    If this function is used as part of a :ref:`getbufferproc <buffer-structs>`,
    *exporter* MUST be set to the exporting object and *flags* must be passed
index 23b7128..ee42f85 100644 (file)
@@ -158,7 +158,7 @@ called with a non-bytes parameter.
 
    If *length* is *NULL*, the bytes object
    may not contain embedded null bytes;
-   if it does, the function returns ``-1`` and a :exc:`TypeError` is raised.
+   if it does, the function returns ``-1`` and a :exc:`ValueError` is raised.
 
    The buffer refers to an internal buffer of *obj*, which includes an
    additional null byte at the end (not counted in *length*).  The data
@@ -167,6 +167,10 @@ called with a non-bytes parameter.
    *obj* is not a bytes object at all, :c:func:`PyBytes_AsStringAndSize`
    returns ``-1`` and raises :exc:`TypeError`.
 
+   .. versionchanged:: 3.5
+      Previously, :exc:`TypeError` was raised when embedded null bytes were
+      encountered in the bytes object.
+
 
 .. c:function:: void PyBytes_Concat(PyObject **bytes, PyObject *newpart)
 
@@ -194,5 +198,5 @@ called with a non-bytes parameter.
    desired.  On success, *\*bytes* holds the resized bytes object and ``0`` is
    returned; the address in *\*bytes* may differ from its input value.  If the
    reallocation fails, the original bytes object at *\*bytes* is deallocated,
-   *\*bytes* is set to *NULL*, a memory exception is set, and ``-1`` is
+   *\*bytes* is set to *NULL*, :exc:`MemoryError` is set, and ``-1`` is
    returned.
index 6f6250f..b8642d0 100644 (file)
@@ -120,19 +120,19 @@ Refer to :ref:`using-capsules` for more information on using these objects.
    guaranteed to succeed.
 
    Return a nonzero value if the object is valid and matches the name passed in.
-   Return 0 otherwise.  This function will not fail.
+   Return ``0`` otherwise.  This function will not fail.
 
 .. c:function:: int PyCapsule_SetContext(PyObject *capsule, void *context)
 
    Set the context pointer inside *capsule* to *context*.
 
-   Return 0 on success.  Return nonzero and set an exception on failure.
+   Return ``0`` on success.  Return nonzero and set an exception on failure.
 
 .. c:function:: int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor)
 
    Set the destructor inside *capsule* to *destructor*.
 
-   Return 0 on success.  Return nonzero and set an exception on failure.
+   Return ``0`` on success.  Return nonzero and set an exception on failure.
 
 .. c:function:: int PyCapsule_SetName(PyObject *capsule, const char *name)
 
@@ -140,11 +140,11 @@ Refer to :ref:`using-capsules` for more information on using these objects.
    outlive the capsule.  If the previous *name* stored in the capsule was not
    *NULL*, no attempt is made to free it.
 
-   Return 0 on success.  Return nonzero and set an exception on failure.
+   Return ``0`` on success.  Return nonzero and set an exception on failure.
 
 .. c:function:: int PyCapsule_SetPointer(PyObject *capsule, void *pointer)
 
    Set the void pointer inside *capsule* to *pointer*.  The pointer may not be
    *NULL*.
 
-   Return 0 on success.  Return nonzero and set an exception on failure.
+   Return ``0`` on success.  Return nonzero and set an exception on failure.
index aeff640..cfa5e13 100644 (file)
@@ -118,6 +118,7 @@ Dictionary Objects
    is returned.  This function evaluates the hash function of *key* only once,
    instead of evaluating it independently for the lookup and the insertion.
 
+   .. versionadded:: 3.4
 
 .. c:function:: PyObject* PyDict_Items(PyObject *p)
 
index 19cbb3b..c389888 100644 (file)
@@ -381,7 +381,7 @@ Querying the error indicator
       by code that needs to save and restore the error indicator temporarily, e.g.::
 
          {
-            PyObject **type, **value, **traceback;
+            PyObject *type, *value, *traceback;
             PyErr_Fetch(&type, &value, &traceback);
 
             /* ... code that might produce other errors ... */
index 2936f4f..5273633 100644 (file)
@@ -185,10 +185,10 @@ Importing Modules
 
    Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` file).
    The magic number should be present in the first four bytes of the bytecode
-   file, in little-endian byte order. Returns -1 on error.
+   file, in little-endian byte order. Returns ``-1`` on error.
 
    .. versionchanged:: 3.3
-      Return value of -1 upon failure.
+      Return value of ``-1`` upon failure.
 
 
 .. c:function:: const char * PyImport_GetMagicTag()
@@ -207,13 +207,13 @@ Importing Modules
 
 .. c:function:: PyObject* PyImport_GetImporter(PyObject *path)
 
-   Return an importer object for a :data:`sys.path`/:attr:`pkg.__path__` item
+   Return a finder object for a :data:`sys.path`/:attr:`pkg.__path__` item
    *path*, possibly by fetching it from the :data:`sys.path_importer_cache`
    dict.  If it wasn't yet cached, traverse :data:`sys.path_hooks` until a hook
    is found that can handle the path item.  Return ``None`` if no hook could;
-   this tells our caller it should fall back to the built-in import mechanism.
-   Cache the result in :data:`sys.path_importer_cache`.  Return a new reference
-   to the importer object.
+   this tells our caller that the :term:`path based finder` could not find a
+   finder for this path item. Cache the result in :data:`sys.path_importer_cache`.
+   Return a new reference to the finder object.
 
 
 .. c:function:: void _PyImport_Init()
index 639819c..70b98ae 100644 (file)
@@ -37,11 +37,15 @@ Initializing and finalizing the interpreter
    (without calling :c:func:`Py_Finalize` first).  There is no return value; it is a
    fatal error if the initialization fails.
 
+   .. note::
+      On Windows, changes the console mode from ``O_TEXT`` to ``O_BINARY``, which will
+      also affect non-Python uses of the console using the C Runtime.
+
 
 .. c:function:: void Py_InitializeEx(int initsigs)
 
-   This function works like :c:func:`Py_Initialize` if *initsigs* is 1. If
-   *initsigs* is 0, it skips initialization registration of signal handlers, which
+   This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If
+   *initsigs* is ``0``, it skips initialization registration of signal handlers, which
    might be useful when Python is embedded.
 
 
@@ -110,7 +114,7 @@ Process-wide parameters
    If :c:func:`Py_Finalize` 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
+   Returns ``0`` if successful, a nonzero value on error (e.g. calling after the
    interpreter has already been initialized).
 
    .. versionadded:: 3.4
@@ -345,7 +349,7 @@ Process-wide parameters
    - If the name of an existing script is passed in ``argv[0]``, the absolute
      path of the directory where the script is located is prepended to
      :data:`sys.path`.
-   - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point
+   - Otherwise (that is, if *argc* is ``0`` or ``argv[0]`` doesn't point
      to an existing file name), an empty string is prepended to
      :data:`sys.path`, which is the same as prepending the current working
      directory (``"."``).
@@ -355,7 +359,7 @@ Process-wide parameters
 
    .. note::
       It is recommended that applications embedding the Python interpreter
-      for purposes other than executing a single script pass 0 as *updatepath*,
+      for purposes other than executing a single script pass ``0`` as *updatepath*,
       and update :data:`sys.path` themselves if desired.
       See `CVE-2008-5983 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.
 
@@ -367,14 +371,14 @@ Process-wide parameters
 
    .. versionadded:: 3.1.3
 
-   .. XXX impl. doesn't seem consistent in allowing 0/NULL for the params;
+   .. XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params;
       check w/ Guido.
 
 
 .. c:function:: void PySys_SetArgv(int argc, wchar_t **argv)
 
    This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set
-   to 1 unless the :program:`python` interpreter was started with the
+   to ``1`` unless the :program:`python` interpreter was started with the
    :option:`-I`.
 
    Use :c:func:`Py_DecodeLocale` to decode a bytes string to get a
@@ -714,10 +718,10 @@ with sub-interpreters:
 
 .. c:function:: int PyGILState_Check()
 
-   Return 1 if the current thread is holding the GIL and 0 otherwise.
+   Return ``1`` if the current thread is holding the GIL and ``0`` otherwise.
    This function can be called from any thread at any time.
    Only if it has had its Python thread state initialized and currently is
-   holding the GIL will it return 1.
+   holding the GIL will it return ``1``.
    This is mainly a helper/diagnostic function.  It can be useful
    for example in callback contexts or memory allocation functions when
    knowing that the GIL is locked can allow the caller to perform sensitive
@@ -987,8 +991,8 @@ pointer and a void pointer argument.
    .. index:: single: Py_AddPendingCall()
 
    Schedule a function to be called from the main interpreter thread.  On
-   success, 0 is returned and *func* is queued for being called in the
-   main thread.  On failure, -1 is returned without setting any exception.
+   success, ``0`` is returned and *func* is queued for being called in the
+   main thread.  On failure, ``-1`` is returned without setting any exception.
 
    When successfully queued, *func* will be *eventually* called from the
    main interpreter thread with the argument *arg*.  It will be called
@@ -999,7 +1003,7 @@ pointer and a void pointer argument.
    * with the main thread holding the :term:`global interpreter lock`
      (*func* can therefore use the full C API).
 
-   *func* must return 0 on success, or -1 on failure with an exception
+   *func* must return ``0`` on success, or ``-1`` on failure with an exception
    set.  *func* won't be interrupted to perform another asynchronous
    notification recursively, but it can still be interrupted to switch
    threads if the global interpreter lock is released.
index b348015..68f6a8e 100644 (file)
@@ -232,7 +232,7 @@ All integers are implemented as "long" integer objects of arbitrary size.
    method (if present) to convert it to a :c:type:`PyLongObject`.
 
    If the value of *obj* is out of range for an :c:type:`unsigned long`,
-   return the reduction of that value modulo :const:`ULONG_MAX + 1`.
+   return the reduction of that value modulo ``ULONG_MAX + 1``.
 
 
 .. c:function:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(PyObject *obj)
@@ -242,7 +242,7 @@ All integers are implemented as "long" integer objects of arbitrary size.
    method (if present) to convert it to a :c:type:`PyLongObject`.
 
    If the value of *obj* is out of range for an :c:type:`unsigned long long`,
-   return the reduction of that value modulo :const:`PY_ULLONG_MAX + 1`.
+   return the reduction of that value modulo ``PY_ULLONG_MAX + 1``.
 
 
 .. c:function:: double PyLong_AsDouble(PyObject *pylong)
index fe601b6..a71e942 100644 (file)
@@ -50,21 +50,20 @@ Mapping Protocol
 
 .. c:function:: PyObject* PyMapping_Keys(PyObject *o)
 
-   On success, return a list, a tuple or a dictionary view in case of a dict,
-   of the keys in object *o*. On failure, return *NULL*.
+   On success, return a list or tuple of the keys in object *o*.  On failure,
+   return *NULL*.
 
 
 .. c:function:: PyObject* PyMapping_Values(PyObject *o)
 
-   On success, return a list, a tuple or a dictionary view in case of a dict, of
-   the values in object *o*. On failure, return *NULL*.
+   On success, return a list or tuple of the values in object *o*.  On failure,
+   return *NULL*.
 
 
 .. c:function:: PyObject* PyMapping_Items(PyObject *o)
 
-   On success, return a list, a tuple or a dictionary view in case of a dict, of
-   the items in object *o*, where each item is a tuple containing a key-value
-   pair.  On failure, return *NULL*.
+   On success, return a list or tuple of the items in object *o*, where each item
+   is a tuple containing a key-value pair.  On failure, return *NULL*.
 
 
 .. c:function:: PyObject* PyMapping_GetItemString(PyObject *o, const char *key)
index 904b4b1..7724350 100644 (file)
@@ -59,10 +59,13 @@ Module Objects
    .. index:: single: __dict__ (module attribute)
 
    Return the dictionary object that implements *module*'s namespace; this object
-   is the same as the :attr:`__dict__` attribute of the module object.  This
-   function never fails.  It is recommended extensions use other
-   :c:func:`PyModule_\*` and :c:func:`PyObject_\*` functions rather than directly
-   manipulate a module's :attr:`__dict__`.
+   is the same as the :attr:`~object.__dict__` attribute of the module object.
+   If *module* is not a module object (or a subtype of a module object),
+   :exc:`SystemError` is raised and *NULL* is returned.
+
+   It is recommended extensions use other :c:func:`PyModule_\*` and
+   :c:func:`PyObject_\*` functions rather than directly manipulate a module's
+   :attr:`~object.__dict__`.
 
 
 .. c:function:: PyObject* PyModule_GetNameObject(PyObject *module)
@@ -321,7 +324,7 @@ The available slot types are:
    :c:type:`PyModule_Type`. Any type can be used, as long as it supports
    setting and getting import-related attributes.
    However, only ``PyModule_Type`` instances may be returned if the
-   ``PyModuleDef`` has non-*NULL* ``m_methods``, ``m_traverse``, ``m_clear``,
+   ``PyModuleDef`` has non-*NULL* ``m_traverse``, ``m_clear``,
    ``m_free``; non-zero ``m_size``; or slots other than ``Py_mod_create``.
 
 .. c:var:: Py_mod_exec
index b9ac269..45568fe 100644 (file)
@@ -2,8 +2,8 @@
 
 .. _noneobject:
 
-The None Object
----------------
+The ``None`` Object
+-------------------
 
 .. index:: object: None
 
@@ -23,4 +23,4 @@ same reason.
 .. c:macro:: Py_RETURN_NONE
 
    Properly handle returning :c:data:`Py_None` from within a C function (that is,
-   increment the reference count of None and return it.)
+   increment the reference count of ``None`` and return it.)
index 9bcb649..3c7605a 100644 (file)
@@ -266,7 +266,7 @@ Number Protocol
 .. c:function:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc)
 
    Returns *o* converted to a Py_ssize_t value if *o* can be interpreted as an
-   integer.  If the call fails, an exception is raised and -1 is returned.
+   integer.  If the call fails, an exception is raised and ``-1`` is returned.
 
    If *o* can be converted to a Python int but the attempt to
    convert to a Py_ssize_t value would raise an :exc:`OverflowError`, then the
@@ -278,5 +278,5 @@ Number Protocol
 
 .. c:function:: int PyIndex_Check(PyObject *o)
 
-   Returns True if *o* is an index integer (has the nb_index slot of  the
-   tp_as_number structure filled in).
+   Returns ``1`` if *o* is an index integer (has the nb_index slot of  the
+   tp_as_number structure filled in), and ``0`` otherwise.
index 8de0394..64b6dde 100644 (file)
@@ -114,7 +114,7 @@ or :class:`frozenset` or instances of their subtypes.
 
 .. c:function:: int PySet_Contains(PyObject *anyset, PyObject *key)
 
-   Return 1 if found, 0 if not found, and -1 if an error is encountered.  Unlike
+   Return ``1`` if found, ``0`` if not found, and ``-1`` if an error is encountered.  Unlike
    the Python :meth:`__contains__` method, this function does not automatically
    convert unhashable sets into temporary frozensets.  Raise a :exc:`TypeError` if
    the *key* is unhashable. Raise :exc:`PyExc_SystemError` if *anyset* is not a
@@ -125,8 +125,8 @@ or :class:`frozenset` or instances of their subtypes.
 
    Add *key* to a :class:`set` instance.  Also works with :class:`frozenset`
    instances (like :c:func:`PyTuple_SetItem` it can be used to fill-in the values
-   of brand new frozensets before they are exposed to other code).  Return 0 on
-   success or -1 on failure. Raise a :exc:`TypeError` if the *key* is
+   of brand new frozensets before they are exposed to other code).  Return ``0`` on
+   success or ``-1`` on failure. Raise a :exc:`TypeError` if the *key* is
    unhashable. Raise a :exc:`MemoryError` if there is no room to grow.  Raise a
    :exc:`SystemError` if *set* is not an instance of :class:`set` or its
    subtype.
@@ -138,7 +138,7 @@ subtypes but not for instances of :class:`frozenset` or its subtypes.
 
 .. c:function:: int PySet_Discard(PyObject *set, PyObject *key)
 
-   Return 1 if found and removed, 0 if not found (no action taken), and -1 if an
+   Return ``1`` if found and removed, ``0`` if not found (no action taken), and ``-1`` if an
    error is encountered.  Does not raise :exc:`KeyError` for missing keys.  Raise a
    :exc:`TypeError` if the *key* is unhashable.  Unlike the Python :meth:`~set.discard`
    method, this function does not automatically convert unhashable sets into
index e157df2..a825164 100644 (file)
@@ -32,9 +32,9 @@ Slice Objects
    assuming a sequence of length *length*. Treats indices greater than
    *length* as errors.
 
-   Returns 0 on success and -1 on error with no exception set (unless one of
+   Returns ``0`` on success and ``-1`` on error with no exception set (unless one of
    the indices was not :const:`None` and failed to be converted to an integer,
-   in which case -1 is returned with an exception set).
+   in which case ``-1`` is returned with an exception set).
 
    You probably do not want to use this function.
 
@@ -51,7 +51,7 @@ Slice Objects
    of bounds indices are clipped in a manner consistent with the handling of
    normal slices.
 
-   Returns 0 on success and -1 on error with exception set.
+   Returns ``0`` on success and ``-1`` on error with exception set.
 
    .. versionchanged:: 3.2
       The parameter type for the *slice* parameter was ``PySliceObject*``
index e9e8add..3e8a90c 100644 (file)
@@ -150,9 +150,8 @@ 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 (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.
+:const:`METH_KEYWORDS` can be combined. Any of the calling convention flags
+can be combined with a binding flag.
 
 
 .. data:: METH_VARARGS
@@ -291,7 +290,7 @@ definition with the same method name.
    handles use of the :keyword:`del` statement on that attribute more correctly
    than :c:macro:`T_OBJECT`.
 
-   :attr:`flags` can be 0 for write and read access or :c:macro:`READONLY` for
+   :attr:`flags` can be ``0`` for write and read access or :c:macro:`READONLY` for
    read-only access.  Using :c:macro:`T_STRING` for :attr:`type` implies
    :c:macro:`READONLY`.  Only :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX`
    members can be deleted.  (They are set to *NULL*).
index ac589b8..ac6fd0b 100644 (file)
@@ -111,12 +111,13 @@ type objects) *must* have the :attr:`ob_size` field.
    For statically allocated type objects, the tp_name field should contain a dot.
    Everything before the last dot is made accessible as the :attr:`__module__`
    attribute, and everything after the last dot is made accessible as the
-   :attr:`__name__` attribute.
+   :attr:`~definition.__name__` attribute.
 
    If no dot is present, the entire :c:member:`~PyTypeObject.tp_name` field is made accessible as the
-   :attr:`__name__` attribute, and the :attr:`__module__` attribute is undefined
+   :attr:`~definition.__name__` attribute, and the :attr:`__module__` attribute is undefined
    (unless explicitly set in the dictionary, as explained above).  This means your
-   type will be impossible to pickle.
+   type will be impossible to pickle.  Additionally, it will not be listed in
+   module documentations created with pydoc.
 
    This field is not inherited by subtypes.
 
@@ -198,8 +199,9 @@ type objects) *must* have the :attr:`ob_size` field.
 
    This field is deprecated.  When it is defined, it should point to a function
    that acts the same as the :c:member:`~PyTypeObject.tp_getattro` function, but taking a C string
-   instead of a Python string object to give the attribute name.  The signature is
-   the same as for :c:func:`PyObject_GetAttrString`.
+   instead of a Python string object to give the attribute name.  The signature is ::
+
+      PyObject * tp_getattr(PyObject *o, char *attr_name);
 
    This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattro`: a subtype
    inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when
@@ -212,10 +214,11 @@ type objects) *must* have the :attr:`ob_size` field.
 
    This field is deprecated.  When it is defined, it should point to a function
    that acts the same as the :c:member:`~PyTypeObject.tp_setattro` function, but taking a C string
-   instead of a Python string object to give the attribute name.  The signature is
-   the same as for :c:func:`PyObject_SetAttrString`, but setting
-   *v* to *NULL* to delete an attribute must be supported.
+   instead of a Python string object to give the attribute name.  The signature is ::
+
+      PyObject * tp_setattr(PyObject *o, char *attr_name, PyObject *v);
 
+   The *v* argument is set to *NULL* to delete the attribute.
    This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattro`: a subtype
    inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when
    the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both *NULL*.
@@ -1277,7 +1280,7 @@ Buffer Object Structures
    steps:
 
    (1) Check if the request can be met. If not, raise :c:data:`PyExc_BufferError`,
-       set :c:data:`view->obj` to *NULL* and return -1.
+       set :c:data:`view->obj` to *NULL* and return ``-1``.
 
    (2) Fill in the requested fields.
 
@@ -1285,7 +1288,7 @@ Buffer Object Structures
 
    (4) Set :c:data:`view->obj` to *exporter* and increment :c:data:`view->obj`.
 
-   (5) Return 0.
+   (5) Return ``0``.
 
    If *exporter* is part of a chain or tree of buffer providers, two main
    schemes can be used:
@@ -1328,7 +1331,7 @@ Buffer Object Structures
 
    (1) Decrement an internal counter for the number of exports.
 
-   (2) If the counter is 0, free all memory associated with *view*.
+   (2) If the counter is ``0``, free all memory associated with *view*.
 
    The exporter MUST use the :c:member:`~Py_buffer.internal` field to keep
    track of buffer-specific resources. This field is guaranteed to remain
index a0672ca..256fef3 100644 (file)
@@ -102,7 +102,7 @@ access internal read-only data of Unicode objects:
 
    .. XXX expand on when it is not required
 
-   Returns 0 on success and -1 with an exception set on failure, which in
+   Returns ``0`` on success and ``-1`` with an exception set on failure, which in
    particular happens if memory allocation fails.
 
    .. versionadded:: 3.3
@@ -255,57 +255,57 @@ the Python configuration.
 
 .. c:function:: int Py_UNICODE_ISSPACE(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is a whitespace character.
+   Return ``1`` or ``0`` depending on whether *ch* is a whitespace character.
 
 
 .. c:function:: int Py_UNICODE_ISLOWER(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is a lowercase character.
+   Return ``1`` or ``0`` depending on whether *ch* is a lowercase character.
 
 
 .. c:function:: int Py_UNICODE_ISUPPER(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is an uppercase character.
+   Return ``1`` or ``0`` depending on whether *ch* is an uppercase character.
 
 
 .. c:function:: int Py_UNICODE_ISTITLE(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is a titlecase character.
+   Return ``1`` or ``0`` depending on whether *ch* is a titlecase character.
 
 
 .. c:function:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is a linebreak character.
+   Return ``1`` or ``0`` depending on whether *ch* is a linebreak character.
 
 
 .. c:function:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is a decimal character.
+   Return ``1`` or ``0`` depending on whether *ch* is a decimal character.
 
 
 .. c:function:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is a digit character.
+   Return ``1`` or ``0`` depending on whether *ch* is a digit character.
 
 
 .. c:function:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is a numeric character.
+   Return ``1`` or ``0`` depending on whether *ch* is a numeric character.
 
 
 .. c:function:: int Py_UNICODE_ISALPHA(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is an alphabetic character.
+   Return ``1`` or ``0`` depending on whether *ch* is an alphabetic character.
 
 
 .. c:function:: int Py_UNICODE_ISALNUM(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is an alphanumeric character.
+   Return ``1`` or ``0`` depending on whether *ch* is an alphanumeric character.
 
 
 .. c:function:: int Py_UNICODE_ISPRINTABLE(Py_UNICODE ch)
 
-   Return 1 or 0 depending on whether *ch* is a printable character.
+   Return ``1`` or ``0`` depending on whether *ch* is a printable character.
    Nonprintable characters are those characters defined in the Unicode character
    database as "Other" or "Separator", excepting the ASCII space (0x20) which is
    considered printable.  (Note that printable characters in this context are
@@ -578,13 +578,16 @@ APIs:
    .. versionadded:: 3.3
 
 
-.. c:function:: int PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start, \
-                    PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
+.. c:function:: Py_ssize_t PyUnicode_CopyCharacters(PyObject *to, \
+                                                    Py_ssize_t to_start, \
+                                                    PyObject *from, \
+                                                    Py_ssize_t from_start, \
+                                                    Py_ssize_t how_many)
 
    Copy characters from one Unicode object into another.  This function performs
    character conversion when necessary and falls back to :c:func:`memcpy` if
    possible.  Returns ``-1`` and sets an exception on error, otherwise returns
-   ``0``.
+   the number of copied characters.
 
    .. versionadded:: 3.3
 
@@ -641,7 +644,7 @@ APIs:
 
    Copy the string *u* into a UCS4 buffer, including a null character, if
    *copy_null* is set.  Returns *NULL* and sets an exception on error (in
-   particular, a :exc:`ValueError` if *buflen* is smaller than the length of
+   particular, a :exc:`SystemError` if *buflen* is smaller than the length of
    *u*).  *buffer* is returned on success.
 
    .. versionadded:: 3.3
@@ -682,8 +685,8 @@ Extension modules can continue using them, as they will not be removed in Python
    string content has been filled before using any of the access macros such as
    :c:func:`PyUnicode_KIND`.
 
-   Please migrate to using :c:func:`PyUnicode_FromKindAndData` or
-   :c:func:`PyUnicode_New`.
+   Please migrate to using :c:func:`PyUnicode_FromKindAndData`,
+   :c:func:`PyUnicode_FromWideChar` or :c:func:`PyUnicode_New`.
 
 
 .. c:function:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode)
@@ -697,7 +700,7 @@ Extension modules can continue using them, as they will not be removed in Python
    used in most C functions.
 
    Please migrate to using :c:func:`PyUnicode_AsUCS4`,
-   :c:func:`PyUnicode_Substring`, :c:func:`PyUnicode_ReadChar` or similar new
+   :c:func:`PyUnicode_AsWideChar`, :c:func:`PyUnicode_ReadChar` or similar new
    APIs.
 
 
@@ -790,7 +793,7 @@ system.
    Encode a Unicode object to the current locale encoding. The
    supported error handlers are ``"strict"`` and ``"surrogateescape"``
    (:pep:`383`). The encoder uses ``"strict"`` error handler if
-   *errors* is ``NULL``. Return a :class:`bytes` object. *str* cannot
+   *errors* is ``NULL``. Return a :class:`bytes` object. *unicode* cannot
    contain embedded null characters.
 
    Use :c:func:`PyUnicode_EncodeFSDefault` to encode a string to
@@ -900,7 +903,7 @@ wchar_t Support
 .. c:function:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)
 
    Create a Unicode object from the :c:type:`wchar_t` buffer *w* of the given *size*.
-   Passing -1 as the *size* indicates that the function must itself compute the length,
+   Passing ``-1`` as the *size* indicates that the function must itself compute the length,
    using wcslen.
    Return *NULL* on failure.
 
@@ -910,7 +913,7 @@ wchar_t Support
    Copy the Unicode object contents into the :c:type:`wchar_t` buffer *w*.  At most
    *size* :c:type:`wchar_t` characters are copied (excluding a possibly trailing
    null termination character).  Return the number of :c:type:`wchar_t` characters
-   copied or -1 in case of an error.  Note that the resulting :c:type:`wchar_t*`
+   copied or ``-1`` in case of an error.  Note that the resulting :c:type:`wchar_t*`
    string may or may not be null-terminated.  It is the responsibility of the caller
    to make sure that the :c:type:`wchar_t*` string is null-terminated in case this is
    required by the application. Also, note that the :c:type:`wchar_t*` string
@@ -934,26 +937,6 @@ wchar_t Support
    .. versionadded:: 3.2
 
 
-UCS4 Support
-""""""""""""
-
-.. versionadded:: 3.3
-
-.. XXX are these meant to be public?
-
-.. c:function:: size_t Py_UCS4_strlen(const Py_UCS4 *u)
-                Py_UCS4* Py_UCS4_strcpy(Py_UCS4 *s1, const Py_UCS4 *s2)
-                Py_UCS4* Py_UCS4_strncpy(Py_UCS4 *s1, const Py_UCS4 *s2, size_t n)
-                Py_UCS4* Py_UCS4_strcat(Py_UCS4 *s1, const Py_UCS4 *s2)
-                int Py_UCS4_strcmp(const Py_UCS4 *s1, const Py_UCS4 *s2)
-                int Py_UCS4_strncmp(const Py_UCS4 *s1, const Py_UCS4 *s2, size_t n)
-                Py_UCS4* Py_UCS4_strchr(const Py_UCS4 *s, Py_UCS4 c)
-                Py_UCS4* Py_UCS4_strrchr(const Py_UCS4 *s, Py_UCS4 c)
-
-   These utility functions work on strings of :c:type:`Py_UCS4` characters and
-   otherwise behave like the C standard library functions with the same name.
-
-
 .. _builtincodecs:
 
 Built-in Codecs
@@ -1083,7 +1066,8 @@ These are the UTF-8 codec APIs:
 
    .. deprecated-removed:: 3.3 4.0
       Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
-      :c:func:`PyUnicode_AsUTF8String` or :c:func:`PyUnicode_AsUTF8AndSize`.
+      :c:func:`PyUnicode_AsUTF8String`, :c:func:`PyUnicode_AsUTF8AndSize` or
+      :c:func:`PyUnicode_AsEncodedString`.
 
 
 UTF-32 Codecs
@@ -1156,7 +1140,7 @@ These are the UTF-32 codec APIs:
 
    .. deprecated-removed:: 3.3 4.0
       Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
-      :c:func:`PyUnicode_AsUTF32String`.
+      :c:func:`PyUnicode_AsUTF32String` or :c:func:`PyUnicode_AsEncodedString`.
 
 
 UTF-16 Codecs
@@ -1231,7 +1215,7 @@ These are the UTF-16 codec APIs:
 
    .. deprecated-removed:: 3.3 4.0
       Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
-      :c:func:`PyUnicode_AsUTF16String`.
+      :c:func:`PyUnicode_AsUTF16String` or :c:func:`PyUnicode_AsEncodedString`.
 
 
 UTF-7 Codecs
@@ -1268,9 +1252,8 @@ These are the UTF-7 codec APIs:
    Python "utf-7" codec.
 
    .. deprecated-removed:: 3.3 4.0
-      Part of the old-style :c:type:`Py_UNICODE` API.
-
-   .. XXX replace with what?
+      Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
+      :c:func:`PyUnicode_AsEncodedString`.
 
 
 Unicode-Escape Codecs
@@ -1288,16 +1271,15 @@ These are the "Unicode Escape" codec APIs:
 
 .. c:function:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
 
-   Encode a Unicode object using Unicode-Escape and return the result as Python
-   string object.  Error handling is "strict". Return *NULL* if an exception was
+   Encode a Unicode object using Unicode-Escape and return the result as a
+   bytes object.  Error handling is "strict".  Return *NULL* if an exception was
    raised by the codec.
 
 
 .. c:function:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
 
    Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Unicode-Escape and
-   return a Python string object.  Return *NULL* if an exception was raised by the
-   codec.
+   return a bytes object.  Return *NULL* if an exception was raised by the codec.
 
    .. deprecated-removed:: 3.3 4.0
       Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
@@ -1320,7 +1302,7 @@ These are the "Raw Unicode Escape" codec APIs:
 .. c:function:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
 
    Encode a Unicode object using Raw-Unicode-Escape and return the result as
-   Python string object. Error handling is "strict". Return *NULL* if an exception
+   a bytes object.  Error handling is "strict".  Return *NULL* if an exception
    was raised by the codec.
 
 
@@ -1328,12 +1310,12 @@ These are the "Raw Unicode Escape" codec APIs:
                               Py_ssize_t size, const char *errors)
 
    Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Raw-Unicode-Escape
-   and return a Python string object.  Return *NULL* if an exception was raised by
-   the codec.
+   and return a bytes object.  Return *NULL* if an exception was raised by the codec.
 
    .. deprecated-removed:: 3.3 4.0
       Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
-      :c:func:`PyUnicode_AsRawUnicodeEscapeString`.
+      :c:func:`PyUnicode_AsRawUnicodeEscapeString` or
+      :c:func:`PyUnicode_AsEncodedString`.
 
 
 Latin-1 Codecs
@@ -1364,7 +1346,8 @@ ordinals and only these are accepted by the codecs during encoding.
 
    .. deprecated-removed:: 3.3 4.0
       Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
-      :c:func:`PyUnicode_AsLatin1String`.
+      :c:func:`PyUnicode_AsLatin1String` or
+      :c:func:`PyUnicode_AsEncodedString`.
 
 
 ASCII Codecs
@@ -1395,7 +1378,8 @@ codes generate errors.
 
    .. deprecated-removed:: 3.3 4.0
       Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
-      :c:func:`PyUnicode_AsASCIIString`.
+      :c:func:`PyUnicode_AsASCIIString` or
+      :c:func:`PyUnicode_AsEncodedString`.
 
 
 Character Map Codecs
@@ -1407,11 +1391,11 @@ included in the :mod:`encodings` package). The codec uses mapping to encode and
 decode characters.
 
 Decoding mappings must map single string characters to single Unicode
-characters, integers (which are then interpreted as Unicode ordinals) or None
+characters, integers (which are then interpreted as Unicode ordinals) or ``None``
 (meaning "undefined mapping" and causing an error).
 
 Encoding mappings must map single Unicode characters to single string
-characters, integers (which are then interpreted as Latin-1 ordinals) or None
+characters, integers (which are then interpreted as Latin-1 ordinals) or ``None``
 (meaning "undefined mapping" and causing an error).
 
 The mapping objects provided must only support the __getitem__ mapping
@@ -1452,16 +1436,16 @@ The following codec API is special in that maps Unicode to Unicode.
    *NULL* when an exception was raised by the codec.
 
    The *mapping* table must map Unicode ordinal integers to Unicode ordinal
-   integers or None (causing deletion of the character).
+   integers or ``None`` (causing deletion of the character).
 
    Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
    and sequences work well.  Unmapped character ordinals (ones which cause a
    :exc:`LookupError`) are left untouched and are copied as-is.
 
    .. deprecated-removed:: 3.3 4.0
-      Part of the old-style :c:type:`Py_UNICODE` API.
-
-   .. XXX replace with what?
+      Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
+      :c:func:`PyUnicode_Translate`. or :ref:`generic codec based API
+      <codec-registry>`
 
 
 .. c:function:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, \
@@ -1473,7 +1457,8 @@ The following codec API is special in that maps Unicode to Unicode.
 
    .. deprecated-removed:: 3.3 4.0
       Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
-      :c:func:`PyUnicode_AsCharmapString`.
+      :c:func:`PyUnicode_AsCharmapString` or
+      :c:func:`PyUnicode_AsEncodedString`.
 
 
 MBCS codecs for Windows
@@ -1523,7 +1508,8 @@ the user settings on the machine running the codec.
 
    .. deprecated-removed:: 3.3 4.0
       Part of the old-style :c:type:`Py_UNICODE` API; please migrate to using
-      :c:func:`PyUnicode_AsMBCSString` or :c:func:`PyUnicode_EncodeCodePage`.
+      :c:func:`PyUnicode_AsMBCSString`, :c:func:`PyUnicode_EncodeCodePage` or
+      :c:func:`PyUnicode_AsEncodedString`.
 
 
 Methods & Slots
@@ -1558,7 +1544,7 @@ They all return *NULL* or ``-1`` if an exception occurs.
 .. c:function:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend)
 
    Split a Unicode string at line breaks, returning a list of Unicode strings.
-   CRLF is considered to be one line break.  If *keepend* is 0, the Line break
+   CRLF is considered to be one line break.  If *keepend* is ``0``, the Line break
    characters are not included in the resulting strings.
 
 
@@ -1569,7 +1555,7 @@ They all return *NULL* or ``-1`` if an exception occurs.
    resulting Unicode object.
 
    The mapping table must map Unicode ordinal integers to Unicode ordinal integers
-   or None (causing deletion of the character).
+   or ``None`` (causing deletion of the character).
 
    Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
    and sequences work well.  Unmapped character ordinals (ones which cause a
@@ -1588,16 +1574,16 @@ They all return *NULL* or ``-1`` if an exception occurs.
 .. c:function:: Py_ssize_t PyUnicode_Tailmatch(PyObject *str, PyObject *substr, \
                         Py_ssize_t start, Py_ssize_t end, int direction)
 
-   Return 1 if *substr* matches ``str[start:end]`` at the given tail end
-   (*direction* == -1 means to do a prefix match, *direction* == 1 a suffix match),
-   0 otherwise. Return ``-1`` if an error occurred.
+   Return ``1`` if *substr* matches ``str[start:end]`` at the given tail end
+   (*direction* == ``-1`` means to do a prefix match, *direction* == ``1`` a suffix match),
+   ``0`` otherwise. Return ``-1`` if an error occurred.
 
 
 .. c:function:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, \
                                Py_ssize_t start, Py_ssize_t end, int direction)
 
    Return the first position of *substr* in ``str[start:end]`` using the given
-   *direction* (*direction* == 1 means to do a forward search, *direction* == -1 a
+   *direction* (*direction* == ``1`` means to do a forward search, *direction* == ``-1`` a
    backward search).  The return value is the index of the first match; a value of
    ``-1`` indicates that no match was found, and ``-2`` indicates that an error
    occurred and an exception has been set.
@@ -1607,8 +1593,8 @@ They all return *NULL* or ``-1`` if an exception occurs.
                                Py_ssize_t start, Py_ssize_t end, int direction)
 
    Return the first position of the character *ch* in ``str[start:end]`` using
-   the given *direction* (*direction* == 1 means to do a forward search,
-   *direction* == -1 a backward search).  The return value is the index of the
+   the given *direction* (*direction* == ``1`` means to do a forward search,
+   *direction* == ``-1`` a backward search).  The return value is the index of the
    first match; a value of ``-1`` indicates that no match was found, and ``-2``
    indicates that an error occurred and an exception has been set.
 
@@ -1626,23 +1612,28 @@ They all return *NULL* or ``-1`` if an exception occurs.
                               PyObject *replstr, Py_ssize_t maxcount)
 
    Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and
-   return the resulting Unicode object. *maxcount* == -1 means replace all
+   return the resulting Unicode object. *maxcount* == ``-1`` means replace all
    occurrences.
 
 
 .. c:function:: int PyUnicode_Compare(PyObject *left, PyObject *right)
 
-   Compare two strings and return -1, 0, 1 for less than, equal, and greater than,
+   Compare two strings and return ``-1``, ``0``, ``1`` for less than, equal, and greater than,
    respectively.
 
+   This function returns ``-1`` upon failure, so one should call
+   :c:func:`PyErr_Occurred` to check for errors.
+
 
 .. c:function:: int PyUnicode_CompareWithASCIIString(PyObject *uni, const char *string)
 
-   Compare a unicode object, *uni*, with *string* and return -1, 0, 1 for less
+   Compare a unicode object, *uni*, with *string* and return ``-1``, ``0``, ``1`` for less
    than, equal, and greater than, respectively. It is best to pass only
    ASCII-encoded strings, but the function interprets the input string as
    ISO-8859-1 if it contains non-ASCII characters.
 
+   This function does not raise exceptions.
+
 
 .. c:function:: PyObject* PyUnicode_RichCompare(PyObject *left,  PyObject *right,  int op)
 
@@ -1652,10 +1643,6 @@ They all return *NULL* or ``-1`` if an exception occurs.
    * :const:`Py_True` or :const:`Py_False` for successful comparisons
    * :const:`Py_NotImplemented` in case the type combination is unknown
 
-   Note that :const:`Py_EQ` and :const:`Py_NE` comparisons can cause a
-   :exc:`UnicodeWarning` in case the conversion of the arguments to Unicode fails
-   with a :exc:`UnicodeDecodeError`.
-
    Possible values for *op* are :const:`Py_GT`, :const:`Py_GE`, :const:`Py_EQ`,
    :const:`Py_NE`, :const:`Py_LT`, and :const:`Py_LE`.
 
index 706efdf..d0ceb05 100644 (file)
@@ -219,9 +219,10 @@ the same library that the Python runtime is using.
 .. c:function:: PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)
 
    Execute Python source code from *str* in the context specified by the
-   dictionaries *globals* and *locals* with the compiler flags specified by
-   *flags*.  The parameter *start* specifies the start token that should be used to
-   parse the source code.
+   objects *globals* and *locals* with the compiler flags specified by
+   *flags*.  *globals* must be a dictionary; *locals* can be any object
+   that implements the mapping protocol.  The parameter *start* specifies
+   the start token that should be used to parse the source code.
 
    Returns the result of executing the code as a Python object, or *NULL* if an
    exception was raised.
@@ -287,7 +288,7 @@ the same library that the Python runtime is using.
 
 .. c:function:: PyObject* Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags, int optimize)
 
-   Like :c:func:`Py_CompileStringExFlags`, but *filename* is a byte string
+   Like :c:func:`Py_CompileStringObject`, but *filename* is a byte string
    decoded from the filesystem encoding (:func:`os.fsdecode`).
 
    .. versionadded:: 3.2
@@ -295,16 +296,16 @@ the same library that the Python runtime is using.
 .. c:function:: PyObject* PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
 
    This is a simplified interface to :c:func:`PyEval_EvalCodeEx`, with just
-   the code object, and the dictionaries of global and local variables.
-   The other arguments are set to *NULL*.
+   the code object, and global and local variables.  The other arguments are
+   set to *NULL*.
 
 
 .. c:function:: PyObject* PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject **args, int argcount, PyObject **kws, int kwcount, PyObject **defs, int defcount, PyObject *closure)
 
    Evaluate a precompiled code object, given a particular environment for its
-   evaluation.  This environment consists of dictionaries of global and local
-   variables, arrays of arguments, keywords and defaults, and a closure tuple of
-   cells.
+   evaluation.  This environment consists of a dictionary of global variables,
+   a mapping object of local variables, arrays of arguments, keywords and
+   defaults, and a closure tuple of cells.
 
 
 .. c:type:: PyFrameObject
index d6f20ba..b1bb620 100644 (file)
@@ -60,7 +60,10 @@ templates_path = ['tools/templates']
 
 # Custom sidebar templates, filenames relative to this file.
 html_sidebars = {
-    'index': 'indexsidebar.html',
+    # Defaults taken from http://www.sphinx-doc.org/en/stable/config.html#confval-html_sidebars
+    # Removes the quick search block
+    '**': ['localtoc.html', 'relations.html', 'customsourcelink.html'],
+    'index': ['indexsidebar.html'],
 }
 
 # Additional templates that should be rendered to pages.
index 0672253..b5b7731 100644 (file)
@@ -166,7 +166,7 @@ the full reference.
 
 .. class:: Extension
 
-   The Extension class describes a single C or C++extension module in a setup
+   The Extension class describes a single C or C++ extension module in a setup
    script. It accepts the following keyword arguments in its constructor:
 
    .. tabularcolumns:: |l|L|l|
@@ -205,7 +205,7 @@ the full reference.
    |                        | to or ``None`` to define it    |                           |
    |                        | without a particular value     |                           |
    |                        | (equivalent of ``#define FOO`` |                           |
-   |                        | in source or :option:`-DFOO`   |                           |
+   |                        | in source or :option:`!-DFOO`  |                           |
    |                        | on Unix C compiler command     |                           |
    |                        | line)                          |                           |
    +------------------------+--------------------------------+---------------------------+
@@ -319,11 +319,11 @@ This module provides the following functions.
 
 .. function:: gen_preprocess_options(macros, include_dirs)
 
-   Generate C pre-processor options (:option:`-D`, :option:`!-U`, :option:`!-I`) as
+   Generate C pre-processor options (:option:`!-D`, :option:`!-U`, :option:`!-I`) as
    used by at least two types of compilers: the typical Unix compiler and Visual
    C++. *macros* is the usual thing, a list of 1- or 2-tuples, where ``(name,)``
    means undefine (:option:`!-U`) macro *name*, and ``(name, value)`` means define
-   (:option:`-D`) macro *name* to *value*.  *include_dirs* is just a list of
+   (:option:`!-D`) macro *name* to *value*.  *include_dirs* is just a list of
    directory names to be added to the header file search path (:option:`!-I`).
    Returns a list of command-line options suitable for either Unix compilers or
    Visual C++.
@@ -359,7 +359,7 @@ This module provides the following functions.
 
 .. function:: show_compilers()
 
-   Print list of available compilers (used by the :option:`--help-compiler` options
+   Print list of available compilers (used by the :option:`!--help-compiler` options
    to :command:`build`, :command:`build_ext`, :command:`build_clib`).
 
 
@@ -789,15 +789,15 @@ This module provides the following functions.
 This module provides the :class:`UnixCCompiler` class, a subclass of
 :class:`CCompiler` that handles the typical Unix-style command-line  C compiler:
 
-* macros defined with :option:`-Dname[=value]`
+* macros defined with :option:`!-Dname[=value]`
 
-* macros undefined with :option:`-Uname`
+* macros undefined with :option:`!-Uname`
 
-* include search directories specified with :option:`-Idir`
+* include search directories specified with :option:`!-Idir`
 
-* libraries specified with :option:`-llib`
+* libraries specified with :option:`!-llib`
 
-* library search directories specified with :option:`-Ldir`
+* library search directories specified with :option:`!-Ldir`
 
 * compile handled by :program:`cc` (or similar) executable with :option:`!-c`
   option: compiles :file:`.c` to :file:`.o`
@@ -805,7 +805,7 @@ This module provides the :class:`UnixCCompiler` class, a subclass of
 * link static library handled by :program:`ar` command (possibly with
   :program:`ranlib`)
 
-* link shared library handled by :program:`cc` :option:`-shared`
+* link shared library handled by :program:`cc` :option:`!-shared`
 
 
 :mod:`distutils.msvccompiler` --- Microsoft Compiler
@@ -1318,8 +1318,8 @@ provides the following additional features:
 
 * options set attributes of a passed-in object
 
-* boolean options can have "negative aliases" --- eg. if :option:`--quiet` is
-  the "negative alias" of :option:`--verbose`, then :option:`--quiet` on the
+* boolean options can have "negative aliases" --- eg. if :option:`!--quiet` is
+  the "negative alias" of :option:`!--verbose`, then :option:`!--quiet` on the
   command line sets *verbose* to false.
 
 .. function:: fancy_getopt(options, negative_opt, object, args)
index 523d1e0..bbd2a8c 100644 (file)
@@ -57,7 +57,7 @@ built distributions, such as an RPM package or an executable installer for
 Windows, is far more convenient for users even if your distribution doesn't
 include any extensions.
 
-The :command:`bdist` command has a :option:`--formats` option, similar to the
+The :command:`bdist` command has a :option:`!--formats` option, similar to the
 :command:`sdist` command, which you can use to select the types of built
 distribution to generate: for example, ::
 
@@ -123,7 +123,7 @@ Notes:
    requires external :program:`rpm` utility, version 3.0.4 or better (use ``rpm
    --version`` to find out which version you have)
 
-You don't have to use the :command:`bdist` command with the :option:`--formats`
+You don't have to use the :command:`bdist` command with the :option:`!--formats`
 option; you can also use the command that directly implements the format you're
 interested in.  Some of these :command:`bdist` "sub-commands" actually generate
 several similar formats; for instance, the :command:`bdist_dumb` command
@@ -174,7 +174,7 @@ The usual way to create an RPM of your module distribution is to run the
 
    python setup.py bdist_rpm
 
-or the :command:`bdist` command with the :option:`--format` option::
+or the :command:`bdist` command with the :option:`!--format` option::
 
    python setup.py bdist --formats=rpm
 
@@ -249,7 +249,7 @@ configuration file, :file:`setup.cfg`\ ---see section :ref:`setup-config`.  If
 you distribute or package many Python module distributions, you might want to
 put options that apply to all of them in your personal Distutils configuration
 file (:file:`~/.pydistutils.cfg`).  If you want to temporarily disable
-this file, you can pass the :option:`--no-user-cfg` option to :file:`setup.py`.
+this file, you can pass the :option:`!--no-user-cfg` option to :file:`setup.py`.
 
 There are three steps to building a binary RPM package, all of which are
 handled automatically by the Distutils:
@@ -267,10 +267,10 @@ Normally, RPM bundles the last two steps together; when you use the Distutils,
 all three steps are typically bundled together.
 
 If you wish, you can separate these three steps.  You can use the
-:option:`--spec-only` option to make :command:`bdist_rpm` just create the
+:option:`!--spec-only` option to make :command:`bdist_rpm` just create the
 :file:`.spec` file and exit; in this case, the :file:`.spec` file will be
 written to the "distribution directory"---normally :file:`dist/`, but
-customizable with the :option:`--dist-dir` option.  (Normally, the :file:`.spec`
+customizable with the :option:`!--dist-dir` option.  (Normally, the :file:`.spec`
 file winds up deep in the "build tree," in a temporary directory created by
 :command:`bdist_rpm`.)
 
@@ -307,7 +307,7 @@ is usually as easy as running::
 
    python setup.py bdist_wininst
 
-or the :command:`bdist` command with the :option:`--formats` option::
+or the :command:`bdist` command with the :option:`!--formats` option::
 
    python setup.py bdist --formats=wininst
 
@@ -325,20 +325,20 @@ support.
 The installer will try to compile pure modules into :term:`bytecode` after installation
 on the target system in normal and optimizing mode.  If you don't want this to
 happen for some reason, you can run the :command:`bdist_wininst` command with
-the :option:`--no-target-compile` and/or the :option:`--no-target-optimize`
+the :option:`!--no-target-compile` and/or the :option:`!--no-target-optimize`
 option.
 
 By default the installer will display the cool "Python Powered" logo when it is
 run, but you can also supply your own 152x261 bitmap which must be a Windows
-:file:`.bmp` file with the :option:`--bitmap` option.
+:file:`.bmp` file with the :option:`!--bitmap` option.
 
 The installer will also display a large title on the desktop background window
 when it is run, which is constructed from the name of your distribution and the
 version number.  This can be changed to another text by using the
-:option:`--title` option.
+:option:`!--title` option.
 
 The installer file will be written to the "distribution directory" --- normally
-:file:`dist/`, but customizable with the :option:`--dist-dir` option.
+:file:`dist/`, but customizable with the :option:`!--dist-dir` option.
 
 .. _cross-compile-windows:
 
@@ -350,7 +350,7 @@ Windows platforms.  In practice, this means that with the correct tools
 installed, you can use a 32bit version of Windows to create 64bit extensions
 and vice-versa.
 
-To build for an alternate platform, specify the :option:`--plat-name` option
+To build for an alternate platform, specify the :option:`!--plat-name` option
 to the build command.  Valid values are currently 'win32', 'win-amd64' and
 'win-ia64'.  For example, on a 32bit version of Windows, you could execute::
 
@@ -383,14 +383,14 @@ The Postinstallation script
 ---------------------------
 
 Starting with Python 2.3, a postinstallation script can be specified with the
-:option:`--install-script` option.  The basename of the script must be
+:option:`!--install-script` option.  The basename of the script must be
 specified, and the script filename must also be listed in the scripts argument
 to the setup function.
 
 This script will be run at installation time on the target system after all the
-files have been copied, with ``argv[1]`` set to :option:`-install`, and again at
+files have been copied, with ``argv[1]`` set to :option:`!-install`, and again at
 uninstallation time before the files are removed with ``argv[1]`` set to
-:option:`-remove`.
+:option:`!-remove`.
 
 The installation script runs embedded in the windows installer, every output
 (``sys.stdout``, ``sys.stderr``) is redirected into a buffer and will be
@@ -453,7 +453,7 @@ built-in functions in the installation script.
 Vista User Access Control (UAC)
 ===============================
 
-Starting with Python 2.6, bdist_wininst supports a :option:`--user-access-control`
+Starting with Python 2.6, bdist_wininst supports a :option:`!--user-access-control`
 option.  The default is 'none' (meaning no UAC handling is done), and other
 valid values are 'auto' (meaning prompt for UAC elevation if Python was
 installed for all users) and 'force' (meaning always prompt for elevation).
index 51d8897..21f1acd 100644 (file)
@@ -66,7 +66,7 @@ universal :option:`!--help` option, e.g. ::
      --swig-opts          list of SWIG command line options
    [...]
 
-Note that an option spelled :option:`--foo-bar` on the command-line  is spelled
+Note that an option spelled :option:`!--foo-bar` on the command-line  is spelled
 ``foo_bar`` in configuration files.
 
 .. _distutils-build-ext-inplace:
@@ -75,12 +75,12 @@ For example, say you want your extensions to be built "in-place"---that is, you
 have an extension :mod:`pkg.ext`, and you want the compiled extension file
 (:file:`ext.so` on Unix, say) to be put in the same source directory as your
 pure Python modules :mod:`pkg.mod1` and :mod:`pkg.mod2`.  You can always use the
-:option:`--inplace` option on the command-line to ensure this::
+:option:`!--inplace` option on the command-line to ensure this::
 
    python setup.py build_ext --inplace
 
 But this requires that you always specify the :command:`build_ext` command
-explicitly, and remember to provide :option:`--inplace`. An easier way is to
+explicitly, and remember to provide :option:`!--inplace`. An easier way is to
 "set and forget" this option, by encoding it in :file:`setup.cfg`, the
 configuration file for this distribution::
 
index af9125a..1f5be9c 100644 (file)
@@ -245,7 +245,9 @@ Let's take an example with a simple script::
 
     setup(name='foobar')
 
-Running the ``check`` command will display some warnings::
+Running the ``check`` command will display some warnings:
+
+.. code-block:: shell-session
 
     $ python setup.py check
     running check
@@ -274,7 +276,9 @@ For example, if the :file:`setup.py` script is changed like this::
         url='http://example.com', long_description=desc)
 
 Where the long description is broken, ``check`` will be able to detect it
-by using the :mod:`docutils` parser::
+by using the :mod:`docutils` parser:
+
+.. code-block:: shell-session
 
     $ python setup.py check --restructuredtext
     running check
@@ -286,7 +290,9 @@ Reading the metadata
 
 The :func:`distutils.core.setup` function provides a command-line interface
 that allows you to query the metadata fields of a project through the
-``setup.py`` script of a given project::
+``setup.py`` script of a given project:
+
+.. code-block:: shell-session
 
     $ python setup.py --name
     distribute
index 5139c6d..501fd7c 100644 (file)
@@ -62,7 +62,7 @@ requiring modifications to the Python installation.  This is expected to allow
 third-party extensions to provide support for additional packaging systems, but
 the commands can be used for anything distutils commands can be used for.  A new
 configuration option, ``command_packages`` (command-line option
-:option:`--command-packages`), can be used to specify additional packages to be
+:option:`!--command-packages`), can be used to specify additional packages to be
 searched for modules implementing commands.  Like all distutils options, this
 can be specified on the command line or in a configuration file.  This option
 can only be set in the ``[global]`` section of a configuration file, or before
index 2d7daef..44556e3 100644 (file)
@@ -173,7 +173,7 @@ name of all sections describing a repository.
 Each section describing a repository defines three variables:
 
 - *repository*, that defines the url of the PyPI server. Defaults to
-    ``https://www.python.org/pypi``.
+    ``https://upload.pypi.org/legacy/``.
 - *username*, which is the registered username on the PyPI server.
 - *password*, that will be used to authenticate. If omitted the user
     will be prompt to type it when needed.
@@ -233,7 +233,9 @@ in the root of the package besides :file:`setup.py`.
 
 To prevent registering broken reStructuredText content, you can use the
 :program:`rst2html` program that is provided by the :mod:`docutils` package and
-check the ``long_description`` from the command line::
+check the ``long_description`` from the command line:
+
+.. code-block:: shell-session
 
     $ python setup.py --long-description | rst2html.py > output.html
 
index 914a34f..38e0202 100644 (file)
@@ -201,7 +201,7 @@ The second argument to the :class:`~distutils.core.Extension` constructor is
 a list of source
 files.  Since the Distutils currently only support C, C++, and Objective-C
 extensions, these are normally C/C++/Objective-C source files.  (Be sure to use
-appropriate extensions to distinguish C++\ source files: :file:`.cc` and
+appropriate extensions to distinguish C++ source files: :file:`.cc` and
 :file:`.cpp` seem to be recognized by both Unix and Windows compilers.)
 
 However, you can also include SWIG interface (:file:`.i`) files in the list; the
@@ -446,7 +446,7 @@ command line.  Scripts don't require Distutils to do anything very complicated.
 The only clever feature is that if the first line of the script starts with
 ``#!`` and contains the word "python", the Distutils will adjust the first line
 to refer to the current interpreter location. By default, it is replaced with
-the current interpreter location.  The :option:`--executable` (or :option:`-e`)
+the current interpreter location.  The :option:`!--executable` (or :option:`!-e`)
 option will allow the interpreter path to be explicitly overridden.
 
 The ``scripts`` option simply is a list of files to be handled in this
index fb70514..cc289c9 100644 (file)
@@ -14,7 +14,7 @@ or config file), :command:`sdist` creates the archive of the default format for
 the current platform.  The default format is a gzip'ed tar file
 (:file:`.tar.gz`) on Unix, and ZIP file on Windows.
 
-You can specify as many formats as you like using the :option:`--formats`
+You can specify as many formats as you like using the :option:`!--formats`
 option, for example::
 
    python setup.py sdist --formats=gztar,zip
@@ -133,7 +133,9 @@ described above does not apply in this case.
 
 The manifest template has one command per line, where each command specifies a
 set of files to include or exclude from the source distribution.  For an
-example, again we turn to the Distutils' own manifest template::
+example, again we turn to the Distutils' own manifest template:
+
+.. code-block:: none
 
    include *.txt
    recursive-include examples *.txt *.py
@@ -145,7 +147,7 @@ matching :file:`\*.txt` or :file:`\*.py`, and exclude all directories matching
 :file:`examples/sample?/build`.  All of this is done *after* the standard
 include set, so you can exclude files from the standard set with explicit
 instructions in the manifest template.  (Or, you can use the
-:option:`--no-defaults` option to disable the standard set entirely.)  There are
+:option:`!--no-defaults` option to disable the standard set entirely.)  There are
 several other commands available in the manifest template mini-language; see
 section :ref:`sdist-cmd`.
 
@@ -164,8 +166,8 @@ Now we have our complete list of files, which is written to the manifest for
 future reference, and then used to build the source distribution archive(s).
 
 You can disable the default set of included files with the
-:option:`--no-defaults` option, and you can disable the standard exclude set
-with :option:`--no-prune`.
+:option:`!--no-defaults` option, and you can disable the standard exclude set
+with :option:`!--no-prune`.
 
 Following the Distutils' own manifest template, let's trace how the
 :command:`sdist` command builds the list of files to include in the Distutils
@@ -223,7 +225,7 @@ The normal course of operations for the :command:`sdist` command is as follows:
   in) to create the source distribution archive(s)
 
 There are a couple of options that modify this behaviour.  First, use the
-:option:`--no-defaults` and :option:`--no-prune` to disable the standard
+:option:`!--no-defaults` and :option:`!--no-prune` to disable the standard
 "include" and "exclude" sets.
 
 Second, you might just want to (re)generate the manifest, but not create a source
@@ -231,4 +233,4 @@ distribution::
 
    python setup.py sdist --manifest-only
 
-:option:`-o` is a shortcut for :option:`--manifest-only`.
+:option:`!-o` is a shortcut for :option:`!--manifest-only`.
index b5ccee7..9fe12c2 100644 (file)
@@ -55,7 +55,9 @@ Since distutils also supports creation of binary packages, users don't
 necessarily need a compiler and distutils to install the extension.
 
 A distutils package contains a driver script, :file:`setup.py`. This is a plain
-Python file, which, in the most simple case, could look like this::
+Python file, which, in the most simple case, could look like this:
+
+.. code-block:: python3
 
    from distutils.core import setup, Extension
 
@@ -96,7 +98,9 @@ file, :file:`demo.c`.
 
 In many cases, building an extension is more complex, since additional
 preprocessor defines and libraries may be needed. This is demonstrated in the
-example below. ::
+example below.
+
+.. code-block:: python3
 
    from distutils.core import setup, Extension
 
@@ -161,4 +165,3 @@ commands can be used to do so. ::
    python setup.py bdist_wininst
    python setup.py bdist_rpm
    python setup.py bdist_dumb
-
index acd60ae..64033dc 100644 (file)
@@ -155,7 +155,9 @@ script, such as:
            c = c + b
        return c
 
-then the result should be::
+then the result should be:
+
+.. code-block:: shell-session
 
    $ call multiply multiply 3 2
    Will compute 3 times 2
@@ -289,16 +291,20 @@ available).  This script has several options, of which the following will
 be directly useful to you:
 
 * ``pythonX.Y-config --cflags`` will give you the recommended flags when
-  compiling::
+  compiling:
+
+  .. code-block:: shell-session
 
-   $ /opt/bin/python3.4-config --cflags
-   -I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
+     $ /opt/bin/python3.4-config --cflags
+     -I/opt/include/python3.4m -I/opt/include/python3.4m -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
 
 * ``pythonX.Y-config --ldflags`` will give you the recommended flags when
-  linking::
+  linking:
+
+  .. code-block:: shell-session
 
-   $ /opt/bin/python3.4-config --ldflags
-   -L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic
+     $ /opt/bin/python3.4-config --ldflags
+     -L/opt/lib/python3.4/config-3.4m -lpthread -ldl -lutil -lm -lpython3.4m -Xlinker -export-dynamic
 
 .. note::
    To avoid confusion between several Python installations (and especially
index 523dfab..4ac820a 100644 (file)
@@ -792,7 +792,9 @@ the format string is empty, it returns ``None``; if it contains exactly one
 format unit, it returns whatever object is described by that format unit.  To
 force it to return a tuple of size 0 or one, parenthesize the format string.
 
-Examples (to the left the call, to the right the resulting Python value)::
+Examples (to the left the call, to the right the resulting Python value):
+
+.. code-block:: none
 
    Py_BuildValue("")                        None
    Py_BuildValue("i", 123)                  123
@@ -884,7 +886,7 @@ The :mod:`gc` module exposes a way to run the detector (the
 :func:`~gc.collect` function), as well as configuration
 interfaces and the ability to disable the detector at runtime.  The cycle
 detector is considered an optional component; though it is included by default,
-it can be disabled at build time using the :option:`--without-cycle-gc` option
+it can be disabled at build time using the :option:`!--without-cycle-gc` option
 to the :program:`configure` script on Unix platforms (including Mac OS X).  If
 the cycle detector is disabled in this way, the :mod:`gc` module will not be
 available.
@@ -1348,4 +1350,3 @@ code distribution).
 
 .. [#] These guarantees don't hold when you use the "old" style calling convention ---
    this is still found in much existing code.
-
index f60e208..b8ce437 100644 (file)
@@ -52,11 +52,15 @@ The first bit that will be new is::
    } noddy_NoddyObject;
 
 This is what a Noddy object will contain---in this case, nothing more than what
-every Python object contains---a refcount and a pointer to a type object.
-These are the fields the ``PyObject_HEAD`` macro brings in.  The reason for the
-macro is to standardize the layout and to enable special debugging fields in
-debug builds.  Note that there is no semicolon after the ``PyObject_HEAD``
-macro; one is included in the macro definition.  Be wary of adding one by
+every Python object contains---a field called ``ob_base`` of type
+:c:type:`PyObject`.  :c:type:`PyObject` in turn, contains an ``ob_refcnt``
+field and a pointer to a type object.  These can be accessed using the macros
+:c:macro:`Py_REFCNT` and :c:macro:`Py_TYPE` respectively.  These are the fields
+the :c:macro:`PyObject_HEAD` macro brings in.  The reason for the macro is to
+standardize the layout and to enable special debugging fields in debug builds.
+
+Note that there is no semicolon after the :c:macro:`PyObject_HEAD` macro;
+one is included in the macro definition.  Be wary of adding one by
 accident; it's easy to do from habit, and your compiler might not complain,
 but someone else's probably will!  (On Windows, MSVC is known to call this an
 error and refuse to compile the code.)
@@ -125,7 +129,9 @@ our objects and in some error messages, for example::
 
 Note that the name is a dotted name that includes both the module name and the
 name of the type within the module. The module in this case is :mod:`noddy` and
-the type is :class:`Noddy`, so we set the type name to :class:`noddy.Noddy`. ::
+the type is :class:`Noddy`, so we set the type name to :class:`noddy.Noddy`.
+One side effect of using an undotted name is that the pydoc documentation tool
+will not list the new type in the module documentation. ::
 
    sizeof(noddy_NoddyObject),  /* tp_basicsize */
 
@@ -209,7 +215,9 @@ That's it!  All that remains is to build it; put the above code in a file called
    setup(name="noddy", version="1.0",
          ext_modules=[Extension("noddy", ["noddy.c"])])
 
-in a file called :file:`setup.py`; then typing ::
+in a file called :file:`setup.py`; then typing
+
+.. code-block:: shell-session
 
    $ python setup.py build
 
@@ -1114,10 +1122,10 @@ If :c:member:`~PyTypeObject.tp_methods` is not *NULL*, it must refer to an array
 structure::
 
    typedef struct PyMethodDef {
-       char        *ml_name;       /* method name */
+       const char  *ml_name;       /* method name */
        PyCFunction  ml_meth;       /* implementation function */
        int          ml_flags;      /* flags */
-       char        *ml_doc;        /* docstring */
+       const char  *ml_doc;        /* docstring */
    } PyMethodDef;
 
 One entry should be defined for each method provided by the type; no entries are
@@ -1513,4 +1521,3 @@ might be something like the following::
 .. [#] Even in the third version, we aren't guaranteed to avoid cycles.  Instances of
    string subclasses are allowed and string subclasses could allow cycles even if
    normal strings don't.
-
index 1b6cd7e..108df6d 100644 (file)
@@ -31,7 +31,7 @@ least slightly uneasy when reading (or being required to write) another style.
 Many coding styles place begin/end brackets on a line by themselves.  This makes
 programs considerably longer and wastes valuable screen space, making it harder
 to get a good overview of a program.  Ideally, a function should fit on one
-screen (say, 20-30 lines).  20 lines of Python can do a lot more work than 20
+screen (say, 20--30 lines).  20 lines of Python can do a lot more work than 20
 lines of C.  This is not solely due to the lack of begin/end brackets -- the
 lack of declarations and the high-level data types are also responsible -- but
 the indentation-based syntax certainly helps.
@@ -77,7 +77,7 @@ which is exactly::
 
     1.1999999999999999555910790149937383830547332763671875 (decimal)
 
-The typical precision of 53 bits provides Python floats with 15-16
+The typical precision of 53 bits provides Python floats with 15--16
 decimal digits of accuracy.
 
 For a fuller explanation, please see the :ref:`floating point arithmetic
index 852e35f..3eafdf1 100644 (file)
@@ -146,7 +146,9 @@ this object to :data:`sys.stdout` and :data:`sys.stderr`.  Call print_error, or
 just allow the standard traceback mechanism to work. Then, the output will go
 wherever your ``write()`` method sends it.
 
-The easiest way to do this is to use the :class:`io.StringIO` class::
+The easiest way to do this is to use the :class:`io.StringIO` class:
+
+.. code-block:: pycon
 
    >>> import io, sys
    >>> sys.stdout = io.StringIO()
@@ -156,7 +158,9 @@ The easiest way to do this is to use the :class:`io.StringIO` class::
    foo
    hello world!
 
-A custom object to do the same would look like this::
+A custom object to do the same would look like this:
+
+.. code-block:: pycon
 
    >>> import io, sys
    >>> class StdoutCatcher(io.TextIOBase):
@@ -222,11 +226,15 @@ How do I debug an extension?
 When using GDB with dynamically loaded extensions, you can't set a breakpoint in
 your extension until your extension is loaded.
 
-In your ``.gdbinit`` file (or interactively), add the command::
+In your ``.gdbinit`` file (or interactively), add the command:
+
+.. code-block:: none
 
    br _PyImport_LoadDynamicModule
 
-Then, when you run GDB::
+Then, when you run GDB:
+
+.. code-block:: shell-session
 
    $ gdb /local/bin/python
    gdb) run myscript.py
index 6b773dd..f1e33af 100644 (file)
@@ -252,7 +252,7 @@ outdated.
 
     Guido van Rossum and Jelke de Boer, "Interactively Testing Remote Servers
     Using the Python Programming Language", CWI Quarterly, Volume 4, Issue 4
-    (December 1991), Amsterdam, pp 283-303.
+    (December 1991), Amsterdam, pp 283--303.
 
 
 Are there any books on Python?
@@ -438,7 +438,7 @@ remember the methods for a list, they can do something like this::
    >>> L
    [1]
 
-With the interpreter, documentation is never far from the student as he's
+With the interpreter, documentation is never far from the student as they are
 programming.
 
 There are also good IDEs for Python.  IDLE is a cross-platform IDE for Python
index 98a28c3..477d8c6 100644 (file)
@@ -77,6 +77,16 @@ for Python allow you to write GTK+ 3 applications.  There is also a
 The older PyGtk bindings for the `Gtk+ 2 toolkit <http://www.gtk.org>`_ have
 been implemented by James Henstridge; see <http://www.pygtk.org>.
 
+Kivy
+----
+
+`Kivy <https://kivy.org/>`_ is a cross-platform GUI library supporting both
+desktop operating systems (Windows, macOS, Linux) and mobile devices (Android,
+iOS).  It is written in Python and Cython, and can use a range of windowing
+backends.
+
+Kivy is free and open source software distributed under the MIT license.
+
 FLTK
 ----
 
index cfe9868..3b79b92 100644 (file)
@@ -503,8 +503,8 @@ to count the number of occurrences of a specific optional arguments:
 * Now here's a demonstration of what the "count" action gives. You've probably
   seen this sort of usage before.
 
-* And, just like the "store_true" action, if you don't specify the ``-v`` flag,
-  that flag is considered to have ``None`` value.
+* And if you don't specify the ``-v`` flag, that flag is considered to have
+  ``None`` value.
 
 * As should be expected, specifying the long form of the flag, we should get
   the same output.
index b04edea..491c5a2 100644 (file)
@@ -1,3 +1,5 @@
+.. highlightlang:: c
+
 **********************
 Argument Clinic How-To
 **********************
@@ -30,7 +32,7 @@ Argument Clinic's primary goal
 is to take over responsibility for all argument parsing code
 inside CPython.  This means that, when you convert a function
 to work with Argument Clinic, that function should no longer
-do any of its own argument parsing--the code generated by
+do any of its own argument parsingthe code generated by
 Argument Clinic should be a "black box" to you, where CPython
 calls in at the top, and your code gets called at the bottom,
 with ``PyObject *args`` (and maybe ``PyObject *kwargs``)
@@ -43,12 +45,12 @@ redundant information in a surprising number of places.
 When you use Argument Clinic, you don't have to repeat yourself.
 
 Obviously, no one would want to use Argument Clinic unless
-it's solving their problem--and without creating new problems of
+it's solving their problemand without creating new problems of
 its own.
 So it's paramount that Argument Clinic generate correct code.
 It'd be nice if the code was faster, too, but at the very least
 it should not introduce a major speed regression.  (Eventually Argument
-Clinic *should* make a major speedup possible--we could
+Clinic *should* make a major speedup possiblewe could
 rewrite its code generator to produce tailor-made argument
 parsing code, rather than calling the general-purpose CPython
 argument parsing library.  That would make for the fastest
@@ -78,17 +80,23 @@ Basic Concepts And Usage
 ========================
 
 Argument Clinic ships with CPython; you'll find it in ``Tools/clinic/clinic.py``.
-If you run that script, specifying a C file as an argument::
+If you run that script, specifying a C file as an argument:
+
+.. code-block:: shell-session
 
-    % python3 Tools/clinic/clinic.py foo.c
+    $ python3 Tools/clinic/clinic.py foo.c
 
 Argument Clinic will scan over the file looking for lines that
-look exactly like this::
+look exactly like this:
+
+.. code-block:: none
 
     /*[clinic input]
 
 When it finds one, it reads everything up to a line that looks
-exactly like this::
+exactly like this:
+
+.. code-block:: none
 
     [clinic start generated code]*/
 
@@ -99,7 +107,9 @@ lines, are collectively called an Argument Clinic "block".
 When Argument Clinic parses one of these blocks, it
 generates output.  This output is rewritten into the C file
 immediately after the block, followed by a comment containing a checksum.
-The Argument Clinic block now looks like this::
+The Argument Clinic block now looks like this:
+
+.. code-block:: none
 
     /*[clinic input]
     ... clinic input goes here ...
@@ -113,7 +123,7 @@ line.  However, if the input hasn't changed, the output won't change either.
 
 You should never modify the output portion of an Argument Clinic block.  Instead,
 change the input until it produces the output you want.  (That's the purpose of the
-checksum--to detect if someone changed the output, as these edits would be lost
+checksumto detect if someone changed the output, as these edits would be lost
 the next time Argument Clinic writes out fresh output.)
 
 For the sake of clarity, here's the terminology we'll use with Argument Clinic:
@@ -152,7 +162,9 @@ Let's dive in!
    For my example I'm using ``_pickle.Pickler.dump()``.
 
 2. If the call to the ``PyArg_Parse`` function uses any of the
-   following format units::
+   following format units:
+
+   .. code-block:: none
 
        O&
        O!
@@ -164,7 +176,7 @@ Let's dive in!
    or if it has multiple calls to :c:func:`PyArg_ParseTuple`,
    you should choose a different function.  Argument Clinic *does*
    support all of these scenarios.  But these are advanced
-   topics--let's do something simpler for your first function.
+   topicslet's do something simpler for your first function.
 
    Also, if the function has multiple calls to :c:func:`PyArg_ParseTuple`
    or :c:func:`PyArg_ParseTupleAndKeywords` where it supports different
@@ -186,7 +198,7 @@ Let's dive in!
 
    If the old docstring had a first line that looked like a function
    signature, throw that line away.  (The docstring doesn't need it
-   anymore--when you use ``help()`` on your builtin in the future,
+   anymorewhen you use ``help()`` on your builtin in the future,
    the first line will be built automatically based on the function's
    signature.)
 
@@ -207,7 +219,7 @@ Let's dive in!
 6. Above the docstring, enter the name of the function, followed
    by a blank line.  This should be the Python name of the function,
    and should be the full dotted path
-   to the function--it should start with the name of the module,
+   to the functionit should start with the name of the module,
    include any sub-modules, and if the function is a method on
    a class it should include the class name too.
 
@@ -273,7 +285,7 @@ Let's dive in!
    What's a "converter"?  It establishes both the type
    of the variable used in C, and the method to convert the Python
    value into a C value at runtime.
-   For now you're going to use what's called a "legacy converter"--a
+   For now you're going to use what's called a "legacy converter"a
    convenience syntax intended to make porting old code into Argument
    Clinic easier.
 
@@ -373,15 +385,10 @@ Let's dive in!
         Write a pickled representation of obj to the open file.
         [clinic start generated code]*/
 
-12. Save and close the file, then run ``Tools/clinic/clinic.py`` on it.
-    With luck everything worked and your block now has output!  Reopen
-    the file in your text editor to see::
-
-       /*[clinic input]
-       module _pickle
-       class _pickle.Pickler "PicklerObject *" "&Pickler_Type"
-       [clinic start generated code]*/
-       /*[clinic end generated code: checksum=da39a3ee5e6b4b0d3255bfef95601890afd80709]*/
+12. Save and close the file, then run ``Tools/clinic/clinic.py`` on
+    it.  With luck everything worked---your block now has output, and
+    a ``.c.h`` file has been generated! Reopen the file in your
+    text editor to see::
 
        /*[clinic input]
        _pickle.Pickler.dump
@@ -393,18 +400,20 @@ Let's dive in!
        Write a pickled representation of obj to the open file.
        [clinic start generated code]*/
 
-       PyDoc_STRVAR(_pickle_Pickler_dump__doc__,
-       "Write a pickled representation of obj to the open file.\n"
-       "\n"
-       ...
        static PyObject *
-       _pickle_Pickler_dump_impl(PicklerObject *self, PyObject *obj)
-       /*[clinic end generated code: checksum=3bd30745bf206a48f8b576a1da3d90f55a0a4187]*/
+       _pickle_Pickler_dump(PicklerObject *self, PyObject *obj)
+       /*[clinic end generated code: output=87ecad1261e02ac7 input=552eb1c0f52260d9]*/
 
     Obviously, if Argument Clinic didn't produce any output, it's because
     it found an error in your input.  Keep fixing your errors and retrying
     until Argument Clinic processes your file without complaint.
 
+    For readability, most of the glue code has been generated to a ``.c.h``
+    file.  You'll need to include that in your original ``.c`` file,
+    typically right after the clinic module block::
+
+       #include "clinic/_pickle.c.h"
+
 13. Double-check that the argument-parsing code Argument Clinic generated
     looks basically the same as the existing code.
 
@@ -422,7 +431,7 @@ Let's dive in!
     (Argument Clinic always generates its format strings
     with a ``:`` followed by the name of the function.  If the
     existing code's format string ends with ``;``, to provide
-    usage help, this change is harmless--don't worry about it.)
+    usage help, this change is harmlessdon't worry about it.)
 
     Third, for parameters whose format units require two arguments
     (like a length variable, or an encoding string, or a pointer
@@ -635,7 +644,7 @@ an optional argument on the *left* side of its required argument!
 Another example is ``curses.window.addch()``, which has a group of two
 arguments that must always be specified together.  (The arguments are
 called ``x`` and ``y``; if you call the function passing in ``x``,
-you must also pass in ``y``--and if you don't pass in ``x`` you may not
+you must also pass in ``y``and if you don't pass in ``x`` you may not
 pass in ``y`` either.)
 
 In any case, the goal of Argument Clinic is to support argument parsing
@@ -651,7 +660,7 @@ can *only* be used with positional-only parameters.
           Functions that use *any* other approach for parsing arguments
           should *almost never* be converted to Argument Clinic using
           optional groups.  Functions using optional groups currently
-          cannot have accurate sigantures in Python, because Python just
+          cannot have accurate signatures in Python, because Python just
           doesn't understand the concept.  Please avoid using optional
           groups wherever possible.
 
@@ -886,7 +895,7 @@ Advanced converters
 Remember those format units you skipped for your first
 time because they were advanced?  Here's how to handle those too.
 
-The trick is, all those format units take arguments--either
+The trick is, all those format units take argumentseither
 conversion functions, or types, or strings specifying an encoding.
 (But "legacy converters" don't support arguments.  That's why we
 skipped them for your first function.)  The argument you specified
@@ -1000,7 +1009,7 @@ Using a return converter
 By default the impl function Argument Clinic generates for you returns ``PyObject *``.
 But your C function often computes some C type, then converts it into the ``PyObject *``
 at the last moment.  Argument Clinic handles converting your inputs from Python types
-into native C types--why not have it convert your return value from a native C type
+into native C typeswhy not have it convert your return value from a native C type
 into a Python type too?
 
 That's what a "return converter" does.  It changes your impl function to return
@@ -1025,7 +1034,9 @@ that value, and an error has been set (``PyErr_Occurred()`` returns a true
 value), then the generated code will propagate the error.  Otherwise it will
 encode the value you return like normal.
 
-Currently Argument Clinic supports only a few return converters::
+Currently Argument Clinic supports only a few return converters:
+
+.. code-block:: none
 
     bool
     int
@@ -1182,7 +1193,7 @@ Writing a custom converter
 As we hinted at in the previous section... you can write your own converters!
 A converter is simply a Python class that inherits from ``CConverter``.
 The main purpose of a custom converter is if you have a parameter using
-the ``O&`` format unit--parsing this parameter means calling
+the ``O&`` format unitparsing this parameter means calling
 a :c:func:`PyArg_ParseTuple` "converter function".
 
 Your converter class should be named ``*something*_converter``.
@@ -1224,7 +1235,7 @@ to specify in your subclass.  Here's the current list:
     The default value used to initialize the C variable when
     there is no default, but not specifying a default may
     result in an "uninitialized variable" warning.  This can
-    easily happen when using option groups--although
+    easily happen when using option groupsalthough
     properly-written code will never actually use this value,
     the variable does get passed in to the impl, and the
     C compiler will complain about the "use" of the
@@ -1249,17 +1260,17 @@ Here's the simplest example of a custom converter, from ``Modules/zlibmodule.c``
 
     /*[python input]
 
-    class capped_uint_converter(CConverter):
-        type = 'unsigned int'
-        converter = 'capped_uint_converter'
+    class ssize_t_converter(CConverter):
+        type = 'Py_ssize_t'
+        converter = 'ssize_t_converter'
 
     [python start generated code]*/
     /*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/
 
-This block adds a converter to Argument Clinic named ``capped_uint``.  Parameters
-declared as ``capped_uint`` will be declared as type ``unsigned int``, and will
+This block adds a converter to Argument Clinic named ``ssize_t``.  Parameters
+declared as ``ssize_t`` will be declared as type ``Py_ssize_t``, and will
 be parsed by the ``'O&'`` format unit, which will call the
-``capped_uint_converter`` converter function.  ``capped_uint`` variables
+``ssize_t_converter`` converter function.  ``ssize_t`` variables
 automatically support default values.
 
 More sophisticated custom converters can insert custom C code to
@@ -1335,7 +1346,7 @@ every line of Clinic's generated output.
 
 While changing Clinic's output in this manner can be a boon to readability,
 it may result in Clinic code using types before they are defined, or
-your code attempting to use Clinic-generated code befire it is defined.
+your code attempting to use Clinic-generated code before it is defined.
 These problems can be easily solved by rearranging the declarations in your file,
 or moving where Clinic's generated code goes.  (This is why the default behavior
 of Clinic is to output everything into the current block; while many people
@@ -1379,7 +1390,7 @@ Let's start with defining some terminology:
 
   ``buffer``
     A text buffer where you can save text for later.  Text sent
-    here is appended to the end of any exsiting text.  It's an
+    here is appended to the end of any existing text.  It's an
     error to have any text left in the buffer when Clinic finishes
     processing a file.
 
@@ -1400,7 +1411,7 @@ Let's start with defining some terminology:
     all of processing, even from Clinic blocks *after* the
 
   ``suppress``
-    The text is suppressed--thrown away.
+    The text is suppressedthrown away.
 
 
 Clinic defines five new directives that let you reconfigure its output.
@@ -1583,7 +1594,7 @@ called ``preserve``::
 
     preserve
 
-This tells Clinic that the current contents of the output should be kept, unmodifed.
+This tells Clinic that the current contents of the output should be kept, unmodified.
 This is used internally by Clinic when dumping output into ``file`` files; wrapping
 it in a Clinic block lets Clinic use its existing checksum functionality to ensure
 the file was not modified by hand before it gets overwritten.
@@ -1604,7 +1615,9 @@ code probably looks like this::
     #endif /* HAVE_FUNCTIONNAME */
 
 And then in the ``PyMethodDef`` structure at the bottom the existing code
-will have::
+will have:
+
+.. code-block:: none
 
     #ifdef HAVE_FUNCTIONNAME
     {'functionname', ... },
@@ -1651,10 +1664,12 @@ undefined, this turns into nothing.
 
 However, this causes one ticklish problem: where should Argument Clinic put this
 extra code when using the "block" output preset?  It can't go in the output block,
-because that could be decativated by the ``#ifdef``.  (That's the whole point!)
+because that could be deactivated by the ``#ifdef``.  (That's the whole point!)
 
 In this situation, Argument Clinic writes the extra code to the "buffer" destination.
-This may mean that you get a complaint from Argument Clinic::
+This may mean that you get a complaint from Argument Clinic:
+
+.. code-block:: none
 
     Warning in file "Modules/posixmodule.c" on line 12357:
     Destination buffer 'buffer' not empty at end of file, emptying.
@@ -1674,7 +1689,9 @@ wouldn't make any sense to the Python interpreter.  But using Argument Clinic
 to run Python blocks lets you use Python as a Python preprocessor!
 
 Since Python comments are different from C comments, Argument Clinic
-blocks embedded in Python files look slightly different.  They look like this::
+blocks embedded in Python files look slightly different.  They look like this:
+
+.. code-block:: python3
 
     #/*[python input]
     #print("def foo(): pass")
index 27e7e6f..7cacb0a 100644 (file)
@@ -95,7 +95,7 @@ long/int Unification
 --------------------
 
 Python 3 has only one integer type, :func:`int`.  But it actually
-corresponds to Python 2's :func:`long` type--the :func:`int` type
+corresponds to Python 2's :func:`long` typethe :func:`int` type
 used in Python 2 was removed.  In the C-API, ``PyInt_*`` functions
 are replaced by their ``PyLong_*`` equivalents.
 
index d370eb5..c2bf473 100644 (file)
@@ -302,7 +302,7 @@ The output suggests that bound and unbound methods are two different types.
 While they could have been implemented that way, the actual C implementation of
 :c:type:`PyMethod_Type` in :source:`Objects/classobject.c` is a single object
 with two different representations depending on whether the :attr:`im_self`
-field is set or is *NULL* (the C equivalent of *None*).
+field is set or is *NULL* (the C equivalent of ``None``).
 
 Likewise, the effects of calling a method object depend on the :attr:`im_self`
 field. If set (meaning bound), the original function (stored in the
index 6e21f93..8ae9679 100644 (file)
@@ -1040,7 +1040,7 @@ If you use :func:`operator.add` with :func:`functools.reduce`, you'll add up all
 elements of the iterable.  This case is so common that there's a special
 built-in called :func:`sum` to compute it:
 
-    >>> import functools
+    >>> import functools, operator
     >>> functools.reduce(operator.add, [1,2,3,4], 0)
     10
     >>> sum([1,2,3,4])
index 5e0ff3e..452e367 100644 (file)
@@ -1,3 +1,7 @@
+.. testsetup::
+
+   import ipaddress
+
 .. _ipaddress-howto:
 
 ***************************************
@@ -49,11 +53,6 @@ to use the :func:`ipaddress.ip_address` factory function, which automatically
 determines whether to create an IPv4 or IPv6 address based on the passed in
 value:
 
-.. testsetup::
-   >>> import ipaddress
-
-::
-
    >>> ipaddress.ip_address('192.0.2.1')
    IPv4Address('192.0.2.1')
    >>> ipaddress.ip_address('2001:DB8::1')
index 99b4cdc..f962cd8 100644 (file)
@@ -377,7 +377,9 @@ An example of using these two classes follows (imports omitted)::
     root.warning('Look out!')
     listener.stop()
 
-which, when run, will produce::
+which, when run, will produce:
+
+.. code-block:: none
 
     MainThread: Look out!
 
@@ -1086,7 +1088,7 @@ $-formatting to be used to build the actual "message" part which appears in the
 formatted log output in place of "%(message)s" or "{message}" or "$message".
 It's a little unwieldy to use the class names whenever you want to log
 something, but it's quite palatable if you use an alias such as __ (double
-underscore  not to be confused with _, the single underscore used as a
+underscore --- not to be confused with _, the single underscore used as a
 synonym/alias for :func:`gettext.gettext` or its brethren).
 
 The above classes are not included in Python, though they're easy enough to
@@ -1207,7 +1209,7 @@ do simply by adding new packages or modules and doing ::
 at module level). It's probably one too many things to think about. Developers
 could also add the filter to a :class:`~logging.NullHandler` attached to their
 top-level logger, but this would not be invoked if an application developer
-attached a handler to a lower-level library logger  so output from that
+attached a handler to a lower-level library logger --- so output from that
 handler would not reflect the intentions of the library developer.
 
 In Python 3.2 and later, :class:`~logging.LogRecord` creation is done through a
@@ -1860,7 +1862,9 @@ script, ``chowntest.py``::
     logger = logging.getLogger('mylogger')
     logger.debug('A debug message')
 
-To run this, you will probably need to run as ``root``::
+To run this, you will probably need to run as ``root``:
+
+.. code-block:: shell-session
 
     $ sudo python3.3 chowntest.py
     $ cat chowntest.log
@@ -2485,7 +2489,9 @@ via ``stderr`` and once via ``stdout``). After the ``with`` statement's
 completion, the status is as it was before so message #6 appears (like message
 #1) whereas message #7 doesn't (just like message #2).
 
-If we run the resulting script, the result is as follows::
+If we run the resulting script, the result is as follows:
+
+.. code-block:: shell-session
 
     $ python logctx.py
     1. This should appear just once on stderr.
@@ -2495,12 +2501,16 @@ If we run the resulting script, the result is as follows::
     6. This should appear just once on stderr.
 
 If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following,
-which is the only message written to ``stdout``::
+which is the only message written to ``stdout``:
+
+.. code-block:: shell-session
 
     $ python logctx.py 2>/dev/null
     5. This should appear twice - once on stderr and once on stdout.
 
-Once again, but piping ``stdout`` to ``/dev/null``, we get::
+Once again, but piping ``stdout`` to ``/dev/null``, we get:
+
+.. code-block:: shell-session
 
     $ python logctx.py >/dev/null
     1. This should appear just once on stderr.
index 51e8430..8074b0f 100644 (file)
@@ -106,7 +106,9 @@ A very simple example is::
    logging.warning('Watch out!')  # will print a message to the console
    logging.info('I told you so')  # will not print anything
 
-If you type these lines into a script and run it, you'll see::
+If you type these lines into a script and run it, you'll see:
+
+.. code-block:: none
 
    WARNING:root:Watch out!
 
@@ -230,7 +232,9 @@ append the variable data as arguments. For example::
    import logging
    logging.warning('%s before you %s', 'Look', 'leap!')
 
-will display::
+will display:
+
+.. code-block:: none
 
    WARNING:root:Look before you leap!
 
@@ -460,7 +464,7 @@ ancestor loggers. Because of this, it is unnecessary to define and configure
 handlers for all the loggers an application uses. It is sufficient to
 configure handlers for a top-level logger and create child loggers as needed.
 (You can, however, turn off propagation by setting the *propagate*
-attribute of a logger to *False*.)
+attribute of a logger to ``False``.)
 
 
 .. _handler-basic:
@@ -594,7 +598,9 @@ logger, a console handler, and a simple formatter using Python code::
     logger.error('error message')
     logger.critical('critical message')
 
-Running this module from the command line produces the following output::
+Running this module from the command line produces the following output:
+
+.. code-block:: shell-session
 
     $ python simple_logging_module.py
     2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
@@ -653,7 +659,9 @@ Here is the logging.conf file::
     format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
     datefmt=
 
-The output is nearly identical to that of the non-config-file-based example::
+The output is nearly identical to that of the non-config-file-based example:
+
+.. code-block:: shell-session
 
     $ python simple_logging_config.py
     2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
@@ -739,10 +747,10 @@ circumstances is dependent on the Python version.
 
 For versions of Python prior to 3.2, the behaviour is as follows:
 
-* If *logging.raiseExceptions* is *False* (production mode), the event is
+* If *logging.raiseExceptions* is ``False`` (production mode), the event is
   silently dropped.
 
-* If *logging.raiseExceptions* is *True* (development mode), a message
+* If *logging.raiseExceptions* is ``True`` (development mode), a message
   'No handlers could be found for logger X.Y.Z' is printed once.
 
 In Python 3.2 and later, the behaviour is as follows:
@@ -756,7 +764,7 @@ In Python 3.2 and later, the behaviour is as follows:
   The handler's level is set to ``WARNING``, so all events at this and
   greater severities will be output.
 
-To obtain the pre-3.2 behaviour, ``logging.lastResort`` can be set to *None*.
+To obtain the pre-3.2 behaviour, ``logging.lastResort`` can be set to ``None``.
 
 .. _library-config:
 
@@ -1073,4 +1081,3 @@ take up any memory.
       Useful handlers included with the logging module.
 
    :ref:`A logging cookbook <logging-cookbook>`
-
index c479f22..8562d23 100644 (file)
@@ -17,7 +17,8 @@ Porting Python 2 Code to Python 3
    please see :ref:`cporting-howto`.
 
    If you would like to read one core Python developer's take on why Python 3
-   came into existence, you can read Nick Coghlan's `Python 3 Q & A`_.
+   came into existence, you can read Nick Coghlan's `Python 3 Q & A`_ or
+   Brett Cannon's `Why Python 3 exists`_.
 
    For help with porting, you can email the python-porting_ mailing list with
    questions.
@@ -32,8 +33,7 @@ are:
 #. Make sure you have good test coverage (coverage.py_ can help;
    ``pip install coverage``)
 #. Learn the differences between Python 2 & 3
-#. Use Modernize_ or Futurize_ to update your code (``pip install modernize`` or
-   ``pip install future``, respectively)
+#. Use Futurize_ (or Modernize_) to update your code (e.g. ``pip install future``)
 #. Use Pylint_ to help make sure you don't regress on your Python 3 support
    (``pip install pylint``)
 #. Use caniusepython3_ to find out which of your dependencies are blocking your
@@ -41,10 +41,9 @@ are:
 #. Once your dependencies are no longer blocking you, use continuous integration
    to make sure you stay compatible with Python 2 & 3 (tox_ can help test
    against multiple versions of Python; ``pip install tox``)
-
-If you are dropping support for Python 2 entirely, then after you learn the
-differences between Python 2 & 3 you can run 2to3_ over your code and skip the
-rest of the steps outlined above.
+#. Consider using optional static type checking to make sure your type usage
+   works in both Python 2 & 3 (e.g. use mypy_ to check your typing under both
+   Python 2 & Python 3).
 
 
 Details
@@ -54,7 +53,7 @@ A key point about supporting Python 2 & 3 simultaneously is that you can start
 **today**! Even if your dependencies are not supporting Python 3 yet that does
 not mean you can't modernize your code **now** to support Python 3. Most changes
 required to support Python 3 lead to cleaner code using newer practices even in
-Python 2.
+Python 2 code.
 
 Another key point is that modernizing your Python 2 code to also support
 Python 3 is largely automated for you. While you might have to make some API
@@ -82,12 +81,13 @@ have to import a function instead of using a built-in one, but otherwise the
 overall transformation should not feel foreign to you.
 
 But you should aim for only supporting Python 2.7. Python 2.6 is no longer
-supported and thus is not receiving bugfixes. This means **you** will have to
-work around any issues you come across with Python 2.6. There are also some
+freely supported and thus is not receiving bugfixes. This means **you** will have
+to work around any issues you come across with Python 2.6. There are also some
 tools mentioned in this HOWTO which do not support Python 2.6 (e.g., Pylint_),
 and this will become more commonplace as time goes on. It will simply be easier
 for you if you only support the versions of Python that you have to support.
 
+
 Make sure you specify the proper version support in your ``setup.py`` file
 --------------------------------------------------------------------------
 
@@ -98,6 +98,7 @@ Python 3 yet you should at least have
 also specify each major/minor version of Python that you do support, e.g.
 ``Programming Language :: Python :: 2.7``.
 
+
 Have good test coverage
 -----------------------
 
@@ -106,9 +107,10 @@ to, you will want to make sure your test suite has good coverage. A good rule of
 thumb is that if you want to be confident enough in your test suite that any
 failures that appear after having tools rewrite your code are actual bugs in the
 tools and not in your code. If you want a number to aim for, try to get over 80%
-coverage (and don't feel bad if you can't easily get past 90%). If you
-don't already have a tool to measure test coverage then coverage.py_ is
-recommended.
+coverage (and don't feel bad if you find it hard to get better than 90%
+coverage). If you don't already have a tool to measure test coverage then
+coverage.py_ is recommended.
+
 
 Learn the differences between Python 2 & 3
 -------------------------------------------
@@ -127,13 +129,15 @@ Update your code
 
 Once you feel like you know what is different in Python 3 compared to Python 2,
 it's time to update your code! You have a choice between two tools in porting
-your code automatically: Modernize_ and Futurize_. Which tool you choose will
+your code automatically: Futurize_ and Modernize_. Which tool you choose will
 depend on how much like Python 3 you want your code to be. Futurize_ does its
 best to make Python 3 idioms and practices exist in Python 2, e.g. backporting
 the ``bytes`` type from Python 3 so that you have semantic parity between the
 major versions of Python. Modernize_,
 on the other hand, is more conservative and targets a Python 2/3 subset of
-Python, relying on six_ to help provide compatibility.
+Python, directly relying on six_ to help provide compatibility. As Python 3 is
+the future, it might be best to consider Futurize to begin adjusting to any new
+practices that Python 3 introduces which you are not accustomed to yet.
 
 Regardless of which tool you choose, they will update your code to run under
 Python 3 while staying compatible with the version of Python 2 you started with.
@@ -153,6 +157,7 @@ the built-in ``open()`` function is off by default in Modernize). Luckily,
 though, there are only a couple of things to watch out for which can be
 considered large issues that may be hard to debug if not watched for.
 
+
 Division
 ++++++++
 
@@ -173,6 +178,7 @@ an object defines a ``__truediv__`` method but not ``__floordiv__`` then your
 code would begin to fail (e.g. a user-defined class that uses ``/`` to
 signify some operation but not ``//`` for the same thing or at all).
 
+
 Text versus binary data
 +++++++++++++++++++++++
 
@@ -189,7 +195,7 @@ To make the distinction between text and binary data clearer and more
 pronounced, Python 3 did what most languages created in the age of the internet
 have done and made text and binary data distinct types that cannot blindly be
 mixed together (Python predates widespread access to the internet). For any code
-that only deals with text or only binary data, this separation doesn't pose an
+that deals only with text or only binary data, this separation doesn't pose an
 issue. But for code that has to deal with both, it does mean you might have to
 now care about when you are using text compared to binary data, which is why
 this cannot be entirely automated.
@@ -198,15 +204,15 @@ To start, you will need to decide which APIs take text and which take binary
 (it is **highly** recommended you don't design APIs that can take both due to
 the difficulty of keeping the code working; as stated earlier it is difficult to
 do well). In Python 2 this means making sure the APIs that take text can work
-with ``unicode`` in Python 2 and those that work with binary data work with the
-``bytes`` type from Python 3 and thus a subset of ``str`` in Python 2 (which the
-``bytes`` type in Python 2 is an alias for). Usually the biggest issue is
-realizing which methods exist for which types in Python 2 & 3 simultaneously
+with ``unicode`` and those that work with binary data work with the
+``bytes`` type from Python 3 (which is a subset of ``str`` in Python 2 and acts
+as an alias for ``bytes`` type in Python 2). Usually the biggest issue is
+realizing which methods exist on which types in Python 2 & 3 simultaneously
 (for text that's ``unicode`` in Python 2 and ``str`` in Python 3, for binary
 that's ``str``/``bytes`` in Python 2 and ``bytes`` in Python 3). The following
 table lists the **unique** methods of each data type across Python 2 & 3
 (e.g., the ``decode()`` method is usable on the equivalent binary data type in
-either Python 2 or 3, but it can't be used by the text data type consistently
+either Python 2 or 3, but it can't be used by the textual data type consistently
 between Python 2 and 3 because ``str`` in Python 3 doesn't have the method). Do
 note that as of Python 3.5 the ``__mod__`` method was added to the bytes type.
 
@@ -232,10 +238,11 @@ This allows your code to work with only text internally and thus eliminates
 having to keep track of what type of data you are working with.
 
 The next issue is making sure you know whether the string literals in your code
-represent text or binary data. At minimum you should add a ``b`` prefix to any
-literal that presents binary data. For text you should either use the
-``from __future__ import unicode_literals`` statement or add a ``u`` prefix to
-the text literal.
+represent text or binary data. You should add a ``b`` prefix to any
+literal that presents binary data. For text you should add a ``u`` prefix to
+the text literal. (there is a :mod:`__future__` import to force all unspecified
+literals to be Unicode, but usage has shown it isn't as effective as adding a
+``b`` or ``u`` prefix to all literals explicitly)
 
 As part of this dichotomy you also need to be careful about opening files.
 Unless you have been working on Windows, there is a chance you have not always
@@ -243,11 +250,13 @@ bothered to add the ``b`` mode when opening a binary file (e.g., ``rb`` for
 binary reading).  Under Python 3, binary files and text files are clearly
 distinct and mutually incompatible; see the :mod:`io` module for details.
 Therefore, you **must** make a decision of whether a file will be used for
-binary access (allowing binary data to be read and/or written) or text access
+binary access (allowing binary data to be read and/or written) or textual access
 (allowing text data to be read and/or written). You should also use :func:`io.open`
 for opening files instead of the built-in :func:`open` function as the :mod:`io`
 module is consistent from Python 2 to 3 while the built-in :func:`open` function
-is not (in Python 3 it's actually :func:`io.open`).
+is not (in Python 3 it's actually :func:`io.open`). Do not bother with the
+outdated practice of using :func:`codecs.open` as that's only necessary for
+keeping compatibility with Python 2.5.
 
 The constructors of both ``str`` and ``bytes`` have different semantics for the
 same arguments between Python 2 & 3. Passing an integer to ``bytes`` in Python 2
@@ -274,21 +283,22 @@ To summarize:
 #. Make sure that your code that works with text also works with ``unicode`` and
    code for binary data works with ``bytes`` in Python 2 (see the table above
    for what methods you cannot use for each type)
-#. Mark all binary literals with a ``b`` prefix, use a ``u`` prefix or
-   :mod:`__future__` import statement for text literals
+#. Mark all binary literals with a ``b`` prefix, textual literals with a ``u``
+   prefix
 #. Decode binary data to text as soon as possible, encode text as binary data as
    late as possible
 #. Open files using :func:`io.open` and make sure to specify the ``b`` mode when
    appropriate
-#. Be careful when indexing binary data
+#. Be careful when indexing into binary data
 
 
 Use feature detection instead of version detection
 ++++++++++++++++++++++++++++++++++++++++++++++++++
+
 Inevitably you will have code that has to choose what to do based on what
 version of Python is running. The best way to do this is with feature detection
 of whether the version of Python you're running under supports what you need.
-If for some reason that doesn't work then you should make the version check is
+If for some reason that doesn't work then you should make the version check be
 against Python 2 and not Python 3. To help explain this, let's look at an
 example.
 
@@ -299,7 +309,7 @@ access e.g. the ``importlib.abc`` module by doing the following::
 
   import sys
 
-  if sys.version[0] == 3:
+  if sys.version_info[0] == 3:
       from importlib import abc
   else:
       from importlib2 import abc
@@ -311,7 +321,7 @@ Python 2::
 
   import sys
 
-  if sys.version[0] > 2:
+  if sys.version_info[0] > 2:
       from importlib import abc
   else:
       from importlib2 import abc
@@ -340,14 +350,12 @@ at least the following block of code at the top of it::
     from __future__ import absolute_import
     from __future__ import division
     from __future__ import print_function
-    from __future__ import unicode_literals
 
 You can also run Python 2 with the ``-3`` flag to be warned about various
 compatibility issues your code triggers during execution. If you turn warnings
 into errors with ``-Werror`` then you can make sure that you don't accidentally
 miss a warning.
 
-
 You can also use the Pylint_ project and its ``--py3k`` flag to lint your code
 to receive warnings when your code begins to deviate from Python 3
 compatibility. This also prevents you from having to run Modernize_ or Futurize_
@@ -364,22 +372,23 @@ care about whether your dependencies have also been ported. The caniusepython3_
 project was created to help you determine which projects
 -- directly or indirectly -- are blocking you from supporting Python 3. There
 is both a command-line tool as well as a web interface at
-https://caniusepython3.com .
+https://caniusepython3.com.
 
 The project also provides code which you can integrate into your test suite so
 that you will have a failing test when you no longer have dependencies blocking
 you from using Python 3. This allows you to avoid having to manually check your
 dependencies and to be notified quickly when you can start running on Python 3.
 
+
 Update your ``setup.py`` file to denote Python 3 compatibility
 --------------------------------------------------------------
 
 Once your code works under Python 3, you should update the classifiers in
 your ``setup.py`` to contain ``Programming Language :: Python :: 3`` and to not
-specify sole Python 2 support. This will tell
-anyone using your code that you support Python 2 **and** 3. Ideally you will
-also want to add classifiers for each major/minor version of Python you now
-support.
+specify sole Python 2 support. This will tell anyone using your code that you
+support Python 2 **and** 3. Ideally you will also want to add classifiers for
+each major/minor version of Python you now support.
+
 
 Use continuous integration to stay compatible
 ---------------------------------------------
@@ -404,20 +413,17 @@ don't accidentally break Python 2 or 3 compatibility regardless of which version
 you typically run your tests under while developing.
 
 
-Dropping Python 2 support completely
-====================================
-
-If you are able to fully drop support for Python 2, then the steps required
-to transition to Python 3 simplify greatly.
-
-#. Update your code to only support Python 2.7
-#. Make sure you have good test coverage (coverage.py_ can help)
-#. Learn the differences between Python 2 & 3
-#. Use 2to3_ to rewrite your code to run only under Python 3
+Consider using optional static type checking
+--------------------------------------------
 
-After this your code will be fully Python 3 compliant but in a way that is not
-supported by Python 2. You should also update the classifiers in your
-``setup.py`` to contain ``Programming Language :: Python :: 3 :: Only``.
+Another way to help port your code is to use a static type checker like
+mypy_ or pytype_ on your code. These tools can be used to analyze your code as
+if it's being run under Python 2, then you can run the tool a second time as if
+your code is running under Python 3. By running a static type checker twice like
+this you can discover if you're e.g. misusing binary data type in one version
+of Python compared to another. If you add optional type hints to your code you
+can also explicitly state whether your APIs use textual or binary data, helping
+to make sure everything functions as expected in both versions of Python.
 
 
 .. _2to3: https://docs.python.org/3/library/2to3.html
@@ -428,13 +434,19 @@ supported by Python 2. You should also update the classifiers in your
 .. _importlib: https://docs.python.org/3/library/importlib.html#module-importlib
 .. _importlib2: https://pypi.python.org/pypi/importlib2
 .. _Modernize: https://python-modernize.readthedocs.org/en/latest/
+.. _mypy: http://mypy-lang.org/
 .. _Porting to Python 3: http://python3porting.com/
 .. _Pylint: https://pypi.python.org/pypi/pylint
+
 .. _Python 3 Q & A: https://ncoghlan-devs-python-notes.readthedocs.org/en/latest/python3/questions_and_answers.html
 
+.. _pytype: https://github.com/google/pytype
 .. _python-future: http://python-future.org/
 .. _python-porting: https://mail.python.org/mailman/listinfo/python-porting
 .. _six: https://pypi.python.org/pypi/six
 .. _tox: https://pypi.python.org/pypi/tox
 .. _trove classifier: https://pypi.python.org/pypi?%3Aaction=list_classifiers
+
 .. _"What's New": https://docs.python.org/3/whatsnew/index.html
+
+.. _Why Python 3 exists: http://www.snarky.ca/why-python-3-exists
index de3f461..d9b7c90 100644 (file)
@@ -74,7 +74,9 @@ of the RE by repeating them or changing their meaning.  Much of this document is
 devoted to discussing various metacharacters and what they do.
 
 Here's a complete list of the metacharacters; their meanings will be discussed
-in the rest of this HOWTO. ::
+in the rest of this HOWTO.
+
+.. code-block:: none
 
    . ^ $ * + ? { } [ ] \ | ( )
 
@@ -374,9 +376,7 @@ module.  If you have :mod:`tkinter` available, you may also want to look at
 :source:`Tools/demo/redemo.py`, a demonstration program included with the
 Python distribution.  It allows you to enter REs and strings, and displays
 whether the RE matches or fails. :file:`redemo.py` can be quite useful when
-trying to debug a complicated RE.  Phil Schwartz's `Kodos
-<http://kodos.sourceforge.net/>`_ is also an interactive tool for developing and
-testing RE patterns.
+trying to debug a complicated RE.
 
 This HOWTO uses the standard Python interpreter for its examples. First, run the
 Python interpreter, import the :mod:`re` module, and compile a RE::
index 04394d4..bc71d85 100644 (file)
@@ -106,7 +106,7 @@ mainloop of the web server::
 There's actually 3 general ways in which this loop could work - dispatching a
 thread to handle ``clientsocket``, create a new process to handle
 ``clientsocket``, or restructure this app to use non-blocking sockets, and
-mulitplex between our "server" socket and any active ``clientsocket``\ s using
+multiplex between our "server" socket and any active ``clientsocket``\ s using
 ``select``. More about that later. The important thing to understand now is
 this: this is *all* a "server" socket does. It doesn't send any data. It doesn't
 receive any data. It just produces "client" sockets. Each ``clientsocket`` is
index 0334b26..1280446 100644 (file)
@@ -24,7 +24,7 @@ returns a new sorted list::
     [1, 2, 3, 4, 5]
 
 You can also use the :meth:`list.sort` method. It modifies the list
-in-place (and returns *None* to avoid confusion). Usually it's less convenient
+in-place (and returns ``None`` to avoid confusion). Usually it's less convenient
 than :func:`sorted` - but if you don't need the original list, it's slightly
 more efficient.
 
@@ -58,28 +58,28 @@ A common pattern is to sort complex objects using some of the object's indices
 as keys. For example:
 
     >>> student_tuples = [
-        ('john', 'A', 15),
-        ('jane', 'B', 12),
-        ('dave', 'B', 10),
-    ]
+    ...     ('john', 'A', 15),
+    ...     ('jane', 'B', 12),
+    ...     ('dave', 'B', 10),
+    ... ]
     >>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
 
 The same technique works for objects with named attributes. For example:
 
     >>> class Student:
-            def __init__(self, name, grade, age):
-                self.name = name
-                self.grade = grade
-                self.age = age
-            def __repr__(self):
-                return repr((self.name, self.grade, self.age))
+    ...     def __init__(self, name, grade, age):
+    ...         self.name = name
+    ...         self.grade = grade
+    ...         self.age = age
+    ...     def __repr__(self):
+    ...         return repr((self.name, self.grade, self.age))
 
     >>> student_objects = [
-        Student('john', 'A', 15),
-        Student('jane', 'B', 12),
-        Student('dave', 'B', 10),
-    ]
+    ...     Student('john', 'A', 15),
+    ...     Student('jane', 'B', 12),
+    ...     Student('dave', 'B', 10),
+    ... ]
     >>> sorted(student_objects, key=lambda student: student.age)   # sort by age
     [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
 
@@ -208,15 +208,15 @@ return a negative value for less-than, return zero if they are equal, or return
 a positive value for greater-than. For example, we can do:
 
     >>> def numeric_compare(x, y):
-            return x - y
-    >>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
+    ...     return x - y
+    >>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare) # doctest: +SKIP
     [1, 2, 3, 4, 5]
 
 Or you can reverse the order of comparison with:
 
     >>> def reverse_numeric(x, y):
-            return y - x
-    >>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)
+    ...     return y - x
+    >>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric) # doctest: +SKIP
     [5, 4, 3, 2, 1]
 
 When porting code from Python 2.x to 3.x, the situation can arise when you have
@@ -244,6 +244,12 @@ function. The following wrapper makes that easy to do::
 
 To convert to a key function, just wrap the old comparison function:
 
+.. testsetup::
+
+    from functools import cmp_to_key
+
+.. doctest::
+
     >>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
     [5, 4, 3, 2, 1]
 
index 50a09ba..a48ae1f 100644 (file)
@@ -192,7 +192,7 @@ frequently used than UTF-8.)  UTF-8 uses the following rules:
 UTF-8 has several convenient properties:
 
 1. It can handle any Unicode code point.
-2. A Unicode string is turned into a string of bytes containing no embedded zero
+2. A Unicode string is turned into a sequence of bytes containing no embedded zero
    bytes.  This avoids byte-ordering issues, and means UTF-8 strings can be
    processed by C functions such as ``strcpy()`` and sent through protocols that
    can't handle zero bytes.
@@ -613,7 +613,9 @@ program::
    print(os.listdir(b'.'))
    print(os.listdir('.'))
 
-will produce the following output::
+will produce the following output:
+
+.. code-block:: shell-session
 
    amk:~$ python t.py
    [b'filename\xe4\x94\x80abc', ...]
index 24a4156..18b5c65 100644 (file)
@@ -240,8 +240,8 @@ Error Codes
 ~~~~~~~~~~~
 
 Because the default handlers handle redirects (codes in the 300 range), and
-codes in the 100-299 range indicate success, you will usually only see error
-codes in the 400-599 range.
+codes in the 100--299 range indicate success, you will usually only see error
+codes in the 400--599 range.
 
 :attr:`http.server.BaseHTTPRequestHandler.responses` is a useful dictionary of
 response codes in that shows all the response codes used by RFC 2616. The
@@ -538,6 +538,11 @@ setting up a `Basic Authentication`_ handler: ::
     through a proxy.  However, this can be enabled by extending urllib.request as
     shown in the recipe [#]_.
 
+.. note::
+
+    ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; see
+    the documentation on :func:`~urllib.request.getproxies`.
+
 
 Sockets and Layers
 ==================
@@ -573,7 +578,7 @@ Footnotes
 This document was reviewed and revised by John Lee.
 
 .. [#] Google for example.
-.. [#] Browser sniffing is a very bad practise for website design - building
+.. [#] Browser sniffing is a very bad practice for website design - building
        sites using web standards is much more sensible. Unfortunately a lot of
        sites still send different versions to different browsers.
 .. [#] The user agent for MSIE 6 is
index c1255a6..321f727 100644 (file)
@@ -9,9 +9,9 @@ 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['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!
 
index b22fc59..bc080b0 100644 (file)
@@ -201,7 +201,7 @@ As implied above, the :command:`build` command is responsible for putting the
 files to install into a *build directory*.  By default, this is :file:`build`
 under the distribution root; if you're excessively concerned with speed, or want
 to keep the source tree pristine, you can change the build directory with the
-:option:`--build-base` option. For example::
+:option:`!--build-base` option. For example::
 
    python setup.py build --build-base=/path/to/pybuild/foo-1.0
 
@@ -399,7 +399,7 @@ Installing a new module distribution is as simple as ::
 
    python setup.py install --home=<dir>
 
-where you can supply any directory you like for the :option:`--home` option.  On
+where you can supply any directory you like for the :option:`!--home` option.  On
 Unix, lazy typists can just type a tilde (``~``); the :command:`install` command
 will expand this to your home directory::
 
@@ -410,7 +410,7 @@ to :ref:`modify Python's search path <inst-search-path>` or edit
 :mod:`sitecustomize` (see :mod:`site`) to call :func:`site.addsitedir` or edit
 :data:`sys.path`.
 
-The :option:`--home` option defines the installation base directory.  Files are
+The :option:`!--home` option defines the installation base directory.  Files are
 installed to the following directories under the installation base as follows:
 
 =============== ===========================================================
@@ -455,12 +455,12 @@ be done with ::
 
    /usr/local/bin/python setup.py install --prefix=/mnt/@server/export
 
-In either case, the :option:`--prefix` option defines the installation base, and
-the :option:`--exec-prefix` option defines the platform-specific installation
+In either case, the :option:`!--prefix` option defines the installation base, and
+the :option:`!--exec-prefix` option defines the platform-specific installation
 base, which is used for platform-specific files.  (Currently, this just means
 non-pure module distributions, but could be expanded to C libraries, binary
-executables, etc.)  If :option:`--exec-prefix` is not supplied, it defaults to
-:option:`--prefix`.  Files are installed as follows:
+executables, etc.)  If :option:`!--exec-prefix` is not supplied, it defaults to
+:option:`!--prefix`.  Files are installed as follows:
 
 ================= ==========================================================
 Type of file      Installation directory
@@ -472,13 +472,13 @@ data              :file:`{prefix}`
 C headers         :file:`{prefix}/include/python{X.Y}{abiflags}/{distname}`
 ================= ==========================================================
 
-There is no requirement that :option:`--prefix` or :option:`--exec-prefix`
+There is no requirement that :option:`!--prefix` or :option:`!--exec-prefix`
 actually point to an alternate Python installation; if the directories listed
 above do not already exist, they are created at installation time.
 
 Incidentally, the real reason the prefix scheme is important is simply that a
-standard Unix installation uses the prefix scheme, but with :option:`--prefix`
-and :option:`--exec-prefix` supplied by Python itself as ``sys.prefix`` and
+standard Unix installation uses the prefix scheme, but with :option:`!--prefix`
+and :option:`!--exec-prefix` supplied by Python itself as ``sys.prefix`` and
 ``sys.exec_prefix``.  Thus, you might think you'll never use the prefix scheme,
 but every time you run ``python setup.py install`` without any other options,
 you're using it.
@@ -491,7 +491,7 @@ responsibility to ensure that the interpreter used to run extensions installed
 in this way is compatible with the interpreter used to build them.  The best way
 to do this is to ensure that the two interpreters are the same version of Python
 (possibly different builds, or possibly copies of the same build).  (Of course,
-if your :option:`--prefix` and :option:`--exec-prefix` don't even point to an
+if your :option:`!--prefix` and :option:`!--exec-prefix` don't even point to an
 alternate Python installation, this is immaterial.)
 
 
@@ -501,7 +501,7 @@ Alternate installation: Windows (the prefix scheme)
 ---------------------------------------------------
 
 Windows has no concept of a user's home directory, and since the standard Python
-installation under Windows is simpler than under Unix, the :option:`--prefix`
+installation under Windows is simpler than under Unix, the :option:`!--prefix`
 option has traditionally been used to install additional packages in separate
 locations on Windows. ::
 
@@ -509,8 +509,8 @@ locations on Windows. ::
 
 to install modules to the :file:`\\Temp\\Python` directory on the current drive.
 
-The installation base is defined by the :option:`--prefix` option; the
-:option:`--exec-prefix` option is not supported under Windows, which means that
+The installation base is defined by the :option:`!--prefix` option; the
+:option:`!--exec-prefix` option is not supported under Windows, which means that
 pure Python modules and extension modules are installed into the same location.
 Files are installed as follows:
 
@@ -562,7 +562,7 @@ difference between Python and extension modules.)
 For example, say you're installing a module distribution to your home directory
 under Unix---but you want scripts to go in :file:`~/scripts` rather than
 :file:`~/bin`. As you might expect, you can override this directory with the
-:option:`--install-scripts` option; in this case, it makes most sense to supply
+:option:`!--install-scripts` option; in this case, it makes most sense to supply
 a relative path, which will be interpreted relative to the installation base
 directory (your home directory, in this case)::
 
@@ -572,7 +572,7 @@ Another Unix example: suppose your Python installation was built and installed
 with a prefix of :file:`/usr/local/python`, so under a standard  installation
 scripts will wind up in :file:`/usr/local/python/bin`.  If you want them in
 :file:`/usr/local/bin` instead, you would supply this absolute directory for the
-:option:`--install-scripts` option::
+:option:`!--install-scripts` option::
 
    python setup.py install --install-scripts=/usr/local/bin
 
@@ -932,10 +932,10 @@ Let's examine each of the fields in turn.
   to be in Objective C.
 
 * *cpparg* is an argument for the C preprocessor,  and is anything starting with
-  :option:`!-I`, :option:`-D`, :option:`!-U` or :option:`-C`.
+  :option:`!-I`, :option:`!-D`, :option:`!-U` or :option:`!-C`.
 
-* *library* is anything ending in :file:`.a` or beginning with :option:`-l` or
-  :option:`-L`.
+* *library* is anything ending in :file:`.a` or beginning with :option:`!-l` or
+  :option:`!-L`.
 
 If a particular platform requires a special library on your platform, you can
 add it by editing the :file:`Setup` file and running ``python setup.py build``.
@@ -944,20 +944,20 @@ For example, if the module defined by the line ::
    foo foomodule.c
 
 must be linked with the math library :file:`libm.a` on your platform, simply add
-:option:`-lm` to the line::
+:option:`!-lm` to the line::
 
    foo foomodule.c -lm
 
 Arbitrary switches intended for the compiler or the linker can be supplied with
-the :option:`-Xcompiler` *arg* and :option:`-Xlinker` *arg* options::
+the :option:`!-Xcompiler` *arg* and :option:`!-Xlinker` *arg* options::
 
    foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm
 
-The next option after :option:`-Xcompiler` and :option:`-Xlinker` will be
+The next option after :option:`!-Xcompiler` and :option:`!-Xlinker` will be
 appended to the proper command line, so in the above example the compiler will
-be passed the :option:`-o32` option, and the linker will be passed
-:option:`-shared`.  If a compiler option requires an argument, you'll have to
-supply multiple :option:`-Xcompiler` options; for example, to pass ``-x c++``
+be passed the :option:`!-o32` option, and the linker will be passed
+:option:`!-shared`.  If a compiler option requires an argument, you'll have to
+supply multiple :option:`!-Xcompiler` options; for example, to pass ``-x c++``
 the :file:`Setup` file would have to contain ``-Xcompiler -x -Xcompiler c++``.
 
 Compiler flags can also be supplied through setting the :envvar:`CFLAGS`
index 6fc2865..ace1bfa 100644 (file)
@@ -33,14 +33,18 @@ Here is a sample Python 2.x source file, :file:`example.py`::
    name = raw_input()
    greet(name)
 
-It can be converted to Python 3.x code via 2to3 on the command line::
+It can be converted to Python 3.x code via 2to3 on the command line:
+
+.. code-block:: shell-session
 
    $ 2to3 example.py
 
 A diff against the original source file is printed.  2to3 can also write the
 needed modifications right back to the source file.  (A backup of the original
-file is made unless :option:`-n` is also given.)  Writing the changes back is
-enabled with the :option:`-w` flag::
+file is made unless :option:`!-n` is also given.)  Writing the changes back is
+enabled with the :option:`!-w` flag:
+
+.. code-block:: shell-session
 
    $ 2to3 -w example.py
 
@@ -55,19 +59,25 @@ After transformation, :file:`example.py` looks like this::
 Comments and exact indentation are preserved throughout the translation process.
 
 By default, 2to3 runs a set of :ref:`predefined fixers <2to3-fixers>`.  The
-:option:`-l` flag lists all available fixers.  An explicit set of fixers to run
-can be given with :option:`-f`.  Likewise the :option:`!-x` explicitly disables a
-fixer.  The following example runs only the ``imports`` and ``has_key`` fixers::
+:option:`!-l` flag lists all available fixers.  An explicit set of fixers to run
+can be given with :option:`!-f`.  Likewise the :option:`!-x` explicitly disables a
+fixer.  The following example runs only the ``imports`` and ``has_key`` fixers:
+
+.. code-block:: shell-session
 
    $ 2to3 -f imports -f has_key example.py
 
-This command runs every fixer except the ``apply`` fixer::
+This command runs every fixer except the ``apply`` fixer:
+
+.. code-block:: shell-session
 
    $ 2to3 -x apply example.py
 
 Some fixers are *explicit*, meaning they aren't run by default and must be
 listed on the command line to be run.  Here, in addition to the default fixers,
-the ``idioms`` fixer is run::
+the ``idioms`` fixer is run:
+
+.. code-block:: shell-session
 
    $ 2to3 -f all -f idioms example.py
 
@@ -90,39 +100,43 @@ Since some print statements can be parsed as function calls or statements, 2to3
 cannot always read files containing the print function.  When 2to3 detects the
 presence of the ``from __future__ import print_function`` compiler directive, it
 modifies its internal grammar to interpret :func:`print` as a function.  This
-change can also be enabled manually with the :option:`-p` flag.  Use
-:option:`-p` to run fixers on code that already has had its print statements
+change can also be enabled manually with the :option:`!-p` flag.  Use
+:option:`!-p` to run fixers on code that already has had its print statements
 converted.
 
-The :option:`-o` or :option:`--output-dir` option allows specification of an
+The :option:`!-o` or :option:`!--output-dir` option allows specification of an
 alternate directory for processed output files to be written to.  The
-:option:`-n` flag is required when using this as backup files do not make sense
+:option:`!-n` flag is required when using this as backup files do not make sense
 when not overwriting the input files.
 
 .. versionadded:: 3.2.3
-   The :option:`-o` option was added.
+   The :option:`!-o` option was added.
 
-The :option:`!-W` or :option:`--write-unchanged-files` flag tells 2to3 to always
+The :option:`!-W` or :option:`!--write-unchanged-files` flag tells 2to3 to always
 write output files even if no changes were required to the file.  This is most
-useful with :option:`-o` so that an entire Python source tree is copied with
+useful with :option:`!-o` so that an entire Python source tree is copied with
 translation from one directory to another.
-This option implies the :option:`-w` flag as it would not make sense otherwise.
+This option implies the :option:`!-w` flag as it would not make sense otherwise.
 
 .. versionadded:: 3.2.3
    The :option:`!-W` flag was added.
 
-The :option:`--add-suffix` option specifies a string to append to all output
-filenames.  The :option:`-n` flag is required when specifying this as backups
-are not necessary when writing to different filenames.  Example::
+The :option:`!--add-suffix` option specifies a string to append to all output
+filenames.  The :option:`!-n` flag is required when specifying this as backups
+are not necessary when writing to different filenames.  Example:
+
+.. code-block:: shell-session
 
    $ 2to3 -n -W --add-suffix=3 example.py
 
 Will cause a converted file named ``example.py3`` to be written.
 
 .. versionadded:: 3.2.3
-   The :option:`--add-suffix` option was added.
+   The :option:`!--add-suffix` option was added.
+
+To translate an entire project from one directory tree to another use:
 
-To translate an entire project from one directory tree to another use::
+.. code-block:: shell-session
 
    $ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode
 
index 10789e9..c6b2bf6 100644 (file)
@@ -45,7 +45,9 @@ produces either the sum or the max::
    print(args.accumulate(args.integers))
 
 Assuming the Python code above is saved into a file called ``prog.py``, it can
-be run at the command line and provides useful help messages::
+be run at the command line and provides useful help messages:
+
+.. code-block:: shell-session
 
    $ python prog.py -h
    usage: prog.py [-h] [--sum] N [N ...]
@@ -60,7 +62,9 @@ be run at the command line and provides useful help messages::
     --sum       sum the integers (default: find the max)
 
 When run with the appropriate arguments, it prints either the sum or the max of
-the command-line integers::
+the command-line integers:
+
+.. code-block:: shell-session
 
    $ python prog.py 1 2 3 4
    4
@@ -68,7 +72,9 @@ the command-line integers::
    $ python prog.py 1 2 3 4 --sum
    10
 
-If invalid arguments are passed in, it will issue an error::
+If invalid arguments are passed in, it will issue an error:
+
+.. code-block:: shell-session
 
    $ python prog.py a b c
    usage: prog.py [-h] [--sum] N [N ...]
@@ -182,7 +188,7 @@ The following sections describe how each of these are used.
 prog
 ^^^^
 
-By default, :class:`ArgumentParser` objects uses ``sys.argv[0]`` to determine
+By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine
 how to display the name of the program in help messages.  This default is almost
 always desirable because it will make the help messages match how the program was
 invoked on the command line.  For example, consider a file named
@@ -194,7 +200,9 @@ invoked on the command line.  For example, consider a file named
    args = parser.parse_args()
 
 The help for this program will display ``myprogram.py`` as the program name
-(regardless of where the program was invoked from)::
+(regardless of where the program was invoked from):
+
+.. code-block:: shell-session
 
    $ python myprogram.py --help
    usage: myprogram.py [-h] [--foo FOO]
@@ -550,7 +558,7 @@ conflict_handler
 ^^^^^^^^^^^^^^^^
 
 :class:`ArgumentParser` objects do not allow two actions with the same option
-string.  By default, :class:`ArgumentParser` objects raises an exception if an
+string.  By default, :class:`ArgumentParser` objects raise an exception if an
 attempt is made to create an argument with an option string that is already in
 use::
 
@@ -596,7 +604,9 @@ the parser's help message. For example, consider a file named
    args = parser.parse_args()
 
 If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
-help will be printed::
+help will be printed:
+
+.. code-block:: shell-session
 
    $ python myprogram.py --help
    usage: myprogram.py [-h] [--foo FOO]
@@ -1542,7 +1552,7 @@ Sub-commands
      positional arguments
 
    * description - description for the sub-parser group in help output, by
-     default None
+     default ``None``
 
    * prog - usage information that will be displayed with sub-command help,
      by default the name of the program and any positional arguments before the
@@ -1555,12 +1565,12 @@ Sub-commands
      encountered at the command line
 
    * dest_ - name of the attribute under which sub-command name will be
-     stored; by default None and no value is stored
+     stored; by default ``None`` and no value is stored
 
-   * help_ - help for sub-parser group in help output, by default None
+   * help_ - help for sub-parser group in help output, by default ``None``
 
    * metavar_ - string presenting available sub-commands in help; by default it
-     is None and presents sub-commands in form {cmd1, cmd2, ..}
+     is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}
 
    Some example usage::
 
@@ -1948,10 +1958,11 @@ Customizing file parsing
    The method is called once per line read from the argument file, in order.
 
    A useful override of this method is one that treats each space-separated word
-   as an argument::
+   as an argument.  The following example demonstrates how to do this::
 
-    def convert_arg_line_to_args(self, arg_line):
-        return arg_line.split()
+    class MyArgumentParser(argparse.ArgumentParser):
+        def convert_arg_line_to_args(self, arg_line):
+            return arg_line.split()
 
 
 Exiting methods
index 24f3f62..4ac7bb5 100644 (file)
@@ -254,7 +254,7 @@ When an array object is printed or converted to a string, it is represented as
 empty, otherwise it is a string if the *typecode* is ``'u'``, otherwise it is a
 list of numbers.  The string is guaranteed to be able to be converted back to an
 array with the same type and value using :func:`eval`, so long as the
-:func:`array` function has been imported using ``from array import array``.
+:class:`~array.array` class has been imported using ``from array import array``.
 Examples::
 
    array('l')
index 8c3b7e4..8d4ae2c 100644 (file)
@@ -99,6 +99,7 @@ Abstract Grammar
 The abstract grammar is currently defined as follows:
 
 .. literalinclude:: ../../Parser/Python.asdl
+   :language: none
 
 
 :mod:`ast` Helpers
index 156c5c0..cc4a14b 100644 (file)
@@ -21,7 +21,7 @@ enable *debug mode*.
 To enable all debug checks for an application:
 
 * Enable the asyncio debug mode globally by setting the environment variable
-  :envvar:`PYTHONASYNCIODEBUG` to ``1``, or by calling :meth:`BaseEventLoop.set_debug`.
+  :envvar:`PYTHONASYNCIODEBUG` to ``1``, or by calling :meth:`AbstractEventLoop.set_debug`.
 * Set the log level of the :ref:`asyncio logger <asyncio-logger>` to
   :py:data:`logging.DEBUG`. For example, call
   ``logging.basicConfig(level=logging.DEBUG)`` at startup.
@@ -33,18 +33,18 @@ Examples debug checks:
 
 * Log :ref:`coroutines defined but never "yielded from"
   <asyncio-coroutine-not-scheduled>`
-* :meth:`~BaseEventLoop.call_soon` and :meth:`~BaseEventLoop.call_at` methods
+* :meth:`~AbstractEventLoop.call_soon` and :meth:`~AbstractEventLoop.call_at` methods
   raise an exception if they are called from the wrong thread.
 * Log the execution time of the selector
 * Log callbacks taking more than 100 ms to be executed. The
-  :attr:`BaseEventLoop.slow_callback_duration` attribute is the minimum
+  :attr:`AbstractEventLoop.slow_callback_duration` attribute is the minimum
   duration in seconds of "slow" callbacks.
 * :exc:`ResourceWarning` warnings are emitted when transports and event loops
   are :ref:`not closed explicitly <asyncio-close-transports>`.
 
 .. seealso::
 
-   The :meth:`BaseEventLoop.set_debug` method and the :ref:`asyncio logger
+   The :meth:`AbstractEventLoop.set_debug` method and the :ref:`asyncio logger
    <asyncio-logger>`.
 
 
@@ -68,7 +68,7 @@ For example, write::
 
 Don't schedule directly a call to the :meth:`~Future.set_result` or the
 :meth:`~Future.set_exception` method of a future with
-:meth:`BaseEventLoop.call_soon`: the future can be cancelled before its method
+:meth:`AbstractEventLoop.call_soon`: the future can be cancelled before its method
 is called.
 
 If you wait for a future, you should check early if the future was cancelled to
@@ -96,7 +96,7 @@ the same thread. But when the task uses ``yield from``, the task is suspended
 and the event loop executes the next task.
 
 To schedule a callback from a different thread, the
-:meth:`BaseEventLoop.call_soon_threadsafe` method should be used. Example::
+:meth:`AbstractEventLoop.call_soon_threadsafe` method should be used. Example::
 
     loop.call_soon_threadsafe(callback, *args)
 
@@ -116,7 +116,7 @@ To schedule a coroutine object from a different thread, the
      future = asyncio.run_coroutine_threadsafe(coro_func(), loop)
      result = future.result(timeout)  # Wait for the result with a timeout
 
-The :meth:`BaseEventLoop.run_in_executor` method can be used with a thread pool
+The :meth:`AbstractEventLoop.run_in_executor` method can be used with a thread pool
 executor to execute a callback in different thread to not block the thread of
 the event loop.
 
@@ -145,7 +145,7 @@ APIs like :ref:`protocols <asyncio-protocol>`.
 
 An executor can be used to run a task in a different thread or even in a
 different process, to not block the thread of the event loop. See the
-:meth:`BaseEventLoop.run_in_executor` method.
+:meth:`AbstractEventLoop.run_in_executor` method.
 
 .. seealso::
 
@@ -161,6 +161,14 @@ Logging
 The :mod:`asyncio` module logs information with the :mod:`logging` module in
 the logger ``'asyncio'``.
 
+The default log level for the :mod:`asyncio` module is :py:data:`logging.INFO`.
+For those not wanting such verbosity from :mod:`asyncio` the log level can
+be changed.  For example, to change the level to :py:data:`logging.WARNING`:
+
+.. code-block:: none
+
+   logging.getLogger('asyncio').setLevel(logging.WARNING)
+
 
 .. _asyncio-coroutine-not-scheduled:
 
@@ -168,7 +176,7 @@ Detect coroutine objects never scheduled
 ----------------------------------------
 
 When a coroutine function is called and its result is not passed to
-:func:`ensure_future` or to the :meth:`BaseEventLoop.create_task` method,
+:func:`ensure_future` or to the :meth:`AbstractEventLoop.create_task` method,
 the execution of the coroutine object will never be scheduled which is
 probably a bug.  :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>`
 to :ref:`log a warning <asyncio-logger>` to detect it.
@@ -191,7 +199,7 @@ Output in debug mode::
         test()
 
 The fix is to call the :func:`ensure_future` function or the
-:meth:`BaseEventLoop.create_task` method with the coroutine object.
+:meth:`AbstractEventLoop.create_task` method with the coroutine object.
 
 .. seealso::
 
@@ -267,7 +275,7 @@ coroutine in another coroutine and use classic try/except::
     loop.run_forever()
     loop.close()
 
-Another option is to use the :meth:`BaseEventLoop.run_until_complete`
+Another option is to use the :meth:`AbstractEventLoop.run_until_complete`
 function::
 
     task = asyncio.ensure_future(bug())
@@ -321,14 +329,18 @@ operations::
     print("Pending tasks at exit: %s" % asyncio.Task.all_tasks(loop))
     loop.close()
 
-Expected output::
+Expected output:
+
+.. code-block:: none
 
     (1) create file
     (2) write into file
     (3) close file
     Pending tasks at exit: set()
 
-Actual output::
+Actual output:
+
+.. code-block:: none
 
     (3) close file
     (2) write into file
@@ -369,13 +381,17 @@ Pending task destroyed
 If a pending task is destroyed, the execution of its wrapped :ref:`coroutine
 <coroutine>` did not complete. It is probably a bug and so a warning is logged.
 
-Example of log::
+Example of log:
+
+.. code-block:: none
 
     Task was destroyed but it is pending!
     task: <Task pending coro=<kill_me() done, defined at test.py:5> wait_for=<Future pending cb=[Task._wakeup()]>>
 
 :ref:`Enable the debug mode of asyncio <asyncio-debug-mode>` to get the
-traceback where the task was created. Example of log in debug mode::
+traceback where the task was created. Example of log in debug mode:
+
+.. code-block:: none
 
     Task was destroyed but it is pending!
     source_traceback: Object created at (most recent call last):
index 7ec3aa1..d720160 100644 (file)
@@ -20,14 +20,23 @@ It provides multiple facilities, including:
 
 .. class:: BaseEventLoop
 
-   Base class of event loops.
+   This class is an implementation detail.  It is a subclass of
+   :class:`AbstractEventLoop` and may be a base class of concrete
+   event loop implementations found in :mod:`asyncio`.  It should not
+   be used directly; use :class:`AbstractEventLoop` instead.
+   ``BaseEventLoop`` should not be subclassed by third-party code; the
+   internal interface is not stable.
+
+.. class:: AbstractEventLoop
+
+   Abstract base class of event loops.
 
    This class is :ref:`not thread safe <asyncio-multithreading>`.
 
 Run an event loop
 -----------------
 
-.. method:: BaseEventLoop.run_forever()
+.. method:: AbstractEventLoop.run_forever()
 
    Run until :meth:`stop` is called.  If :meth:`stop` is called before
    :meth:`run_forever()` is called, this polls the I/O selector once
@@ -40,7 +49,7 @@ Run an event loop
 
    .. versionchanged:: 3.5.1
 
-.. method:: BaseEventLoop.run_until_complete(future)
+.. method:: AbstractEventLoop.run_until_complete(future)
 
    Run until the :class:`Future` is done.
 
@@ -49,11 +58,11 @@ Run an event loop
 
    Return the Future's result, or raise its exception.
 
-.. method:: BaseEventLoop.is_running()
+.. method:: AbstractEventLoop.is_running()
 
    Returns running status of event loop.
 
-.. method:: BaseEventLoop.stop()
+.. method:: AbstractEventLoop.stop()
 
    Stop running the event loop.
 
@@ -62,13 +71,13 @@ Run an event loop
 
    .. versionchanged:: 3.5.1
 
-.. method:: BaseEventLoop.is_closed()
+.. method:: AbstractEventLoop.is_closed()
 
    Returns ``True`` if the event loop was closed.
 
    .. versionadded:: 3.4.2
 
-.. method:: BaseEventLoop.close()
+.. method:: AbstractEventLoop.close()
 
    Close the event loop. The loop must not be running.  Pending
    callbacks will be lost.
@@ -95,7 +104,7 @@ keywords to your callback, use :func:`functools.partial`. For example,
    parameters in debug mode, whereas ``lambda`` functions have a poor
    representation.
 
-.. method:: BaseEventLoop.call_soon(callback, \*args)
+.. method:: AbstractEventLoop.call_soon(callback, \*args)
 
    Arrange for a callback to be called as soon as possible.  The callback is
    called after :meth:`call_soon` returns, when control returns to the event
@@ -113,7 +122,7 @@ keywords to your callback, use :func:`functools.partial`. For example,
    :ref:`Use functools.partial to pass keywords to the callback
    <asyncio-pass-keywords>`.
 
-.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
+.. method:: AbstractEventLoop.call_soon_threadsafe(callback, \*args)
 
    Like :meth:`call_soon`, but thread safe.
 
@@ -136,7 +145,7 @@ a different clock than :func:`time.time`.
    Timeouts (relative *delay* or absolute *when*) should not exceed one day.
 
 
-.. method:: BaseEventLoop.call_later(delay, callback, *args)
+.. method:: AbstractEventLoop.call_later(delay, callback, *args)
 
    Arrange for the *callback* to be called after the given *delay*
    seconds (either an int or float).
@@ -155,11 +164,11 @@ a different clock than :func:`time.time`.
    :ref:`Use functools.partial to pass keywords to the callback
    <asyncio-pass-keywords>`.
 
-.. method:: BaseEventLoop.call_at(when, callback, *args)
+.. method:: AbstractEventLoop.call_at(when, callback, *args)
 
    Arrange for the *callback* to be called at the given absolute timestamp
    *when* (an int or float), using the same time reference as
-   :meth:`BaseEventLoop.time`.
+   :meth:`AbstractEventLoop.time`.
 
    This method's behavior is the same as :meth:`call_later`.
 
@@ -169,7 +178,7 @@ a different clock than :func:`time.time`.
    :ref:`Use functools.partial to pass keywords to the callback
    <asyncio-pass-keywords>`.
 
-.. method:: BaseEventLoop.time()
+.. method:: AbstractEventLoop.time()
 
    Return the current time, as a :class:`float` value, according to the
    event loop's internal clock.
@@ -182,7 +191,7 @@ a different clock than :func:`time.time`.
 Futures
 -------
 
-.. method:: BaseEventLoop.create_future()
+.. method:: AbstractEventLoop.create_future()
 
    Create an :class:`asyncio.Future` object attached to the loop.
 
@@ -196,7 +205,7 @@ Futures
 Tasks
 -----
 
-.. method:: BaseEventLoop.create_task(coro)
+.. method:: AbstractEventLoop.create_task(coro)
 
    Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
    a future. Return a :class:`Task` object.
@@ -210,10 +219,10 @@ Tasks
 
    .. versionadded:: 3.4.2
 
-.. method:: BaseEventLoop.set_task_factory(factory)
+.. method:: AbstractEventLoop.set_task_factory(factory)
 
    Set a task factory that will be used by
-   :meth:`BaseEventLoop.create_task`.
+   :meth:`AbstractEventLoop.create_task`.
 
    If *factory* is ``None`` the default task factory will be set.
 
@@ -224,7 +233,7 @@ Tasks
 
    .. versionadded:: 3.4.4
 
-.. method:: BaseEventLoop.get_task_factory()
+.. method:: AbstractEventLoop.get_task_factory()
 
    Return a task factory, or ``None`` if the default one is in use.
 
@@ -234,7 +243,7 @@ Tasks
 Creating connections
 --------------------
 
-.. coroutinemethod:: BaseEventLoop.create_connection(protocol_factory, host=None, port=None, \*, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None)
+.. coroutinemethod:: AbstractEventLoop.create_connection(protocol_factory, host=None, port=None, \*, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None)
 
    Create a streaming transport connection to a given Internet *host* and
    *port*: socket family :py:data:`~socket.AF_INET` or
@@ -309,7 +318,7 @@ Creating connections
       (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
 
 
-.. coroutinemethod:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)
+.. coroutinemethod:: AbstractEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)
 
    Create datagram connection: socket family :py:data:`~socket.AF_INET` or
    :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
@@ -337,7 +346,7 @@ Creating connections
 
    * *reuse_address* tells the kernel to reuse a local socket in
      TIME_WAIT state, without waiting for its natural timeout to
-     expire. If not specified will automatically be set to True on
+     expire. If not specified will automatically be set to ``True`` on
      UNIX.
 
    * *reuse_port* tells the kernel to allow this endpoint to be bound to the
@@ -360,7 +369,7 @@ Creating connections
    :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
 
 
-.. coroutinemethod:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
+.. coroutinemethod:: AbstractEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
 
    Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
    type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
@@ -371,7 +380,11 @@ Creating connections
    establish the connection in the background.  When successful, the
    coroutine returns a ``(transport, protocol)`` pair.
 
-   See the :meth:`BaseEventLoop.create_connection` method for parameters.
+   *path* is the name of a UNIX domain socket, and is required unless a *sock*
+   parameter is specified.  Abstract UNIX sockets, :class:`str`, and
+   :class:`bytes` paths are supported.
+
+   See the :meth:`AbstractEventLoop.create_connection` method for parameters.
 
    Availability: UNIX.
 
@@ -379,7 +392,7 @@ Creating connections
 Creating listening connections
 ------------------------------
 
-.. coroutinemethod:: BaseEventLoop.create_server(protocol_factory, host=None, port=None, \*, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None)
+.. coroutinemethod:: AbstractEventLoop.create_server(protocol_factory, host=None, port=None, \*, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None)
 
    Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
    *host* and *port*.
@@ -415,7 +428,7 @@ Creating listening connections
 
    * *reuse_address* tells the kernel to reuse a local socket in
      TIME_WAIT state, without waiting for its natural timeout to
-     expire. If not specified will automatically be set to True on
+     expire. If not specified will automatically be set to ``True`` on
      UNIX.
 
    * *reuse_port* tells the kernel to allow this endpoint to be bound to the
@@ -439,15 +452,32 @@ Creating listening connections
       The *host* parameter can now be a sequence of strings.
 
 
-.. coroutinemethod:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
+.. coroutinemethod:: AbstractEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
 
-   Similar to :meth:`BaseEventLoop.create_server`, but specific to the
+   Similar to :meth:`AbstractEventLoop.create_server`, but specific to the
    socket family :py:data:`~socket.AF_UNIX`.
 
    This method is a :ref:`coroutine <coroutine>`.
 
    Availability: UNIX.
 
+.. coroutinemethod:: BaseEventLoop.connect_accepted_socket(protocol_factory, sock, \*, ssl=None)
+
+   Handle an accepted connection.
+
+   This is used by servers that accept connections outside of
+   asyncio but that use asyncio to handle them.
+
+   Parameters:
+
+   * *sock* is a preexisting socket object returned from an ``accept``
+     call.
+
+   * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
+     accepted connections.
+
+   This method is a :ref:`coroutine <coroutine>`.  When completed, the
+   coroutine returns a ``(transport, protocol)`` pair.
 
 Watch file descriptors
 ----------------------
@@ -457,7 +487,7 @@ On Windows with :class:`SelectorEventLoop`, only socket handles are supported
 
 On Windows with :class:`ProactorEventLoop`, these methods are not supported.
 
-.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
+.. method:: AbstractEventLoop.add_reader(fd, callback, \*args)
 
    Start watching the file descriptor for read availability and then call the
    *callback* with specified arguments.
@@ -465,11 +495,11 @@ On Windows with :class:`ProactorEventLoop`, these methods are not supported.
    :ref:`Use functools.partial to pass keywords to the callback
    <asyncio-pass-keywords>`.
 
-.. method:: BaseEventLoop.remove_reader(fd)
+.. method:: AbstractEventLoop.remove_reader(fd)
 
    Stop watching the file descriptor for read availability.
 
-.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
+.. method:: AbstractEventLoop.add_writer(fd, callback, \*args)
 
    Start watching the file descriptor for write availability and then call the
    *callback* with specified arguments.
@@ -477,19 +507,19 @@ On Windows with :class:`ProactorEventLoop`, these methods are not supported.
    :ref:`Use functools.partial to pass keywords to the callback
    <asyncio-pass-keywords>`.
 
-.. method:: BaseEventLoop.remove_writer(fd)
+.. method:: AbstractEventLoop.remove_writer(fd)
 
    Stop watching the file descriptor for write availability.
 
 The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
-example uses the low-level :meth:`BaseEventLoop.add_reader` method to register
+example uses the low-level :meth:`AbstractEventLoop.add_reader` method to register
 the file descriptor of a socket.
 
 
 Low-level socket operations
 ---------------------------
 
-.. coroutinemethod:: BaseEventLoop.sock_recv(sock, nbytes)
+.. coroutinemethod:: AbstractEventLoop.sock_recv(sock, nbytes)
 
    Receive data from the socket.  Modeled after blocking
    :meth:`socket.socket.recv` method.
@@ -503,7 +533,7 @@ Low-level socket operations
 
    This method is a :ref:`coroutine <coroutine>`.
 
-.. coroutinemethod:: BaseEventLoop.sock_sendall(sock, data)
+.. coroutinemethod:: AbstractEventLoop.sock_sendall(sock, data)
 
    Send data to the socket.  Modeled after blocking
    :meth:`socket.socket.sendall` method.
@@ -519,7 +549,7 @@ Low-level socket operations
 
    This method is a :ref:`coroutine <coroutine>`.
 
-.. coroutinemethod:: BaseEventLoop.sock_connect(sock, address)
+.. coroutinemethod:: AbstractEventLoop.sock_connect(sock, address)
 
    Connect to a remote socket at *address*.  Modeled after
    blocking :meth:`socket.socket.connect` method.
@@ -533,16 +563,16 @@ Low-level socket operations
       ``address`` no longer needs to be resolved.  ``sock_connect``
       will try to check if the *address* is already resolved by calling
       :func:`socket.inet_pton`.  If not,
-      :meth:`BaseEventLoop.getaddrinfo` will be used to resolve the
+      :meth:`AbstractEventLoop.getaddrinfo` will be used to resolve the
       *address*.
 
    .. seealso::
 
-      :meth:`BaseEventLoop.create_connection`
+      :meth:`AbstractEventLoop.create_connection`
       and  :func:`asyncio.open_connection() <open_connection>`.
 
 
-.. coroutinemethod:: BaseEventLoop.sock_accept(sock)
+.. coroutinemethod:: AbstractEventLoop.sock_accept(sock)
 
    Accept a connection.  Modeled after blocking
    :meth:`socket.socket.accept`.
@@ -559,18 +589,18 @@ Low-level socket operations
 
    .. seealso::
 
-      :meth:`BaseEventLoop.create_server` and :func:`start_server`.
+      :meth:`AbstractEventLoop.create_server` and :func:`start_server`.
 
 
 Resolve host name
 -----------------
 
-.. coroutinemethod:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
+.. coroutinemethod:: AbstractEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
 
    This method is a :ref:`coroutine <coroutine>`, similar to
    :meth:`socket.getaddrinfo` function but non-blocking.
 
-.. coroutinemethod:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
+.. coroutinemethod:: AbstractEventLoop.getnameinfo(sockaddr, flags=0)
 
    This method is a :ref:`coroutine <coroutine>`, similar to
    :meth:`socket.getnameinfo` function but non-blocking.
@@ -582,7 +612,7 @@ Connect pipes
 On Windows with :class:`SelectorEventLoop`, these methods are not supported.
 Use :class:`ProactorEventLoop` to support pipes on Windows.
 
-.. coroutinemethod:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
+.. coroutinemethod:: AbstractEventLoop.connect_read_pipe(protocol_factory, pipe)
 
    Register read pipe in eventloop.
 
@@ -596,7 +626,7 @@ Use :class:`ProactorEventLoop` to support pipes on Windows.
 
    This method is a :ref:`coroutine <coroutine>`.
 
-.. coroutinemethod:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
+.. coroutinemethod:: AbstractEventLoop.connect_write_pipe(protocol_factory, pipe)
 
    Register write pipe in eventloop.
 
@@ -612,8 +642,8 @@ Use :class:`ProactorEventLoop` to support pipes on Windows.
 
 .. seealso::
 
-   The :meth:`BaseEventLoop.subprocess_exec` and
-   :meth:`BaseEventLoop.subprocess_shell` methods.
+   The :meth:`AbstractEventLoop.subprocess_exec` and
+   :meth:`AbstractEventLoop.subprocess_shell` methods.
 
 
 UNIX signals
@@ -621,7 +651,7 @@ UNIX signals
 
 Availability: UNIX only.
 
-.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
+.. method:: AbstractEventLoop.add_signal_handler(signum, callback, \*args)
 
    Add a handler for a signal.
 
@@ -631,7 +661,7 @@ Availability: UNIX only.
    :ref:`Use functools.partial to pass keywords to the callback
    <asyncio-pass-keywords>`.
 
-.. method:: BaseEventLoop.remove_signal_handler(sig)
+.. method:: AbstractEventLoop.remove_signal_handler(sig)
 
    Remove a handler for a signal.
 
@@ -649,7 +679,7 @@ Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
 pool of processes). By default, an event loop uses a thread pool executor
 (:class:`~concurrent.futures.ThreadPoolExecutor`).
 
-.. coroutinemethod:: BaseEventLoop.run_in_executor(executor, func, \*args)
+.. coroutinemethod:: AbstractEventLoop.run_in_executor(executor, func, \*args)
 
    Arrange for a *func* to be called in the specified executor.
 
@@ -661,7 +691,14 @@ pool of processes). By default, an event loop uses a thread pool executor
 
    This method is a :ref:`coroutine <coroutine>`.
 
-.. method:: BaseEventLoop.set_default_executor(executor)
+   .. versionchanged:: 3.5.3
+      :meth:`BaseEventLoop.run_in_executor` no longer configures the
+      ``max_workers`` of the thread pool executor it creates, instead
+      leaving it up to the thread pool executor
+      (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
+      default.
+
+.. method:: AbstractEventLoop.set_default_executor(executor)
 
    Set the default executor used by :meth:`run_in_executor`.
 
@@ -671,7 +708,7 @@ Error Handling API
 
 Allows customizing how exceptions are handled in the event loop.
 
-.. method:: BaseEventLoop.set_exception_handler(handler)
+.. method:: AbstractEventLoop.set_exception_handler(handler)
 
    Set *handler* as the new event loop exception handler.
 
@@ -684,14 +721,14 @@ Allows customizing how exceptions are handled in the event loop.
    will be a ``dict`` object (see :meth:`call_exception_handler`
    documentation for details about context).
 
-.. method:: BaseEventLoop.get_exception_handler()
+.. method:: AbstractEventLoop.get_exception_handler()
 
    Return the exception handler, or ``None`` if the default one
    is in use.
 
    .. versionadded:: 3.5.2
 
-.. method:: BaseEventLoop.default_exception_handler(context)
+.. method:: AbstractEventLoop.default_exception_handler(context)
 
    Default exception handler.
 
@@ -702,7 +739,7 @@ Allows customizing how exceptions are handled in the event loop.
    *context* parameter has the same meaning as in
    :meth:`call_exception_handler`.
 
-.. method:: BaseEventLoop.call_exception_handler(context)
+.. method:: AbstractEventLoop.call_exception_handler(context)
 
    Call the current event loop exception handler.
 
@@ -726,7 +763,7 @@ Allows customizing how exceptions are handled in the event loop.
 Debug mode
 ----------
 
-.. method:: BaseEventLoop.get_debug()
+.. method:: AbstractEventLoop.get_debug()
 
    Get the debug mode (:class:`bool`) of the event loop.
 
@@ -736,7 +773,7 @@ Debug mode
 
    .. versionadded:: 3.4.2
 
-.. method:: BaseEventLoop.set_debug(enabled: bool)
+.. method:: AbstractEventLoop.set_debug(enabled: bool)
 
    Set the debug mode of the event loop.
 
@@ -753,7 +790,7 @@ Server
 
    Server listening on sockets.
 
-   Object created by the :meth:`BaseEventLoop.create_server` method and the
+   Object created by the :meth:`AbstractEventLoop.create_server` method and the
    :func:`start_server` function. Don't instantiate the class directly.
 
    .. method:: close()
@@ -784,9 +821,9 @@ Handle
 
 .. class:: Handle
 
-   A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
-   :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
-   and :func:`BaseEventLoop.call_at`.
+   A callback wrapper object returned by :func:`AbstractEventLoop.call_soon`,
+   :func:`AbstractEventLoop.call_soon_threadsafe`, :func:`AbstractEventLoop.call_later`,
+   and :func:`AbstractEventLoop.call_at`.
 
    .. method:: cancel()
 
@@ -802,7 +839,7 @@ Event loop examples
 Hello World with call_soon()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Example using the :meth:`BaseEventLoop.call_soon` method to schedule a
+Example using the :meth:`AbstractEventLoop.call_soon` method to schedule a
 callback. The callback displays ``"Hello World"`` and then stops the event
 loop::
 
@@ -833,7 +870,7 @@ Display the current date with call_later()
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Example of callback displaying the current date every second. The callback uses
-the :meth:`BaseEventLoop.call_later` method to reschedule itself during 5
+the :meth:`AbstractEventLoop.call_later` method to reschedule itself during 5
 seconds, and then stops the event loop::
 
     import asyncio
@@ -869,7 +906,7 @@ Watch a file descriptor for read events
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Wait until a file descriptor received some data using the
-:meth:`BaseEventLoop.add_reader` method and then close the event loop::
+:meth:`AbstractEventLoop.add_reader` method and then close the event loop::
 
     import asyncio
     try:
@@ -907,7 +944,7 @@ Wait until a file descriptor received some data using the
 
    The :ref:`register an open socket to wait for data using a protocol
    <asyncio-register-socket>` example uses a low-level protocol created by the
-   :meth:`BaseEventLoop.create_connection` method.
+   :meth:`AbstractEventLoop.create_connection` method.
 
    The :ref:`register an open socket to wait for data using streams
    <asyncio-register-socket-streams>` example uses high-level streams
@@ -918,7 +955,7 @@ Set signal handlers for SIGINT and SIGTERM
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
-the :meth:`BaseEventLoop.add_signal_handler` method::
+the :meth:`AbstractEventLoop.add_signal_handler` method::
 
     import asyncio
     import functools
index b8f29d7..1dc18fc 100644 (file)
@@ -35,7 +35,7 @@ asyncio currently provides two implementations of event loops:
 .. class:: SelectorEventLoop
 
    Event loop based on the :mod:`selectors` module. Subclass of
-   :class:`BaseEventLoop`.
+   :class:`AbstractEventLoop`.
 
    Use the most efficient selector available on the platform.
 
@@ -46,7 +46,7 @@ asyncio currently provides two implementations of event loops:
 .. class:: ProactorEventLoop
 
    Proactor event loop for Windows using "I/O Completion Ports" aka IOCP.
-   Subclass of :class:`BaseEventLoop`.
+   Subclass of :class:`AbstractEventLoop`.
 
    Availability: Windows.
 
@@ -76,11 +76,11 @@ Windows
 
 Common limits of Windows event loops:
 
-- :meth:`~BaseEventLoop.create_unix_connection` and
-  :meth:`~BaseEventLoop.create_unix_server` are not supported: the socket
+- :meth:`~AbstractEventLoop.create_unix_connection` and
+  :meth:`~AbstractEventLoop.create_unix_server` are not supported: the socket
   family :data:`socket.AF_UNIX` is specific to UNIX
-- :meth:`~BaseEventLoop.add_signal_handler` and
-  :meth:`~BaseEventLoop.remove_signal_handler` are not supported
+- :meth:`~AbstractEventLoop.add_signal_handler` and
+  :meth:`~AbstractEventLoop.remove_signal_handler` are not supported
 - :meth:`EventLoopPolicy.set_child_watcher` is not supported.
   :class:`ProactorEventLoop` supports subprocesses. It has only one
   implementation to watch child processes, there is no need to configure it.
@@ -89,19 +89,19 @@ Common limits of Windows event loops:
 
 - :class:`~selectors.SelectSelector` is used which only supports sockets
   and is limited to 512 sockets.
-- :meth:`~BaseEventLoop.add_reader` and :meth:`~BaseEventLoop.add_writer` only
+- :meth:`~AbstractEventLoop.add_reader` and :meth:`~AbstractEventLoop.add_writer` only
   accept file descriptors of sockets
 - Pipes are not supported
-  (ex: :meth:`~BaseEventLoop.connect_read_pipe`,
-  :meth:`~BaseEventLoop.connect_write_pipe`)
+  (ex: :meth:`~AbstractEventLoop.connect_read_pipe`,
+  :meth:`~AbstractEventLoop.connect_write_pipe`)
 - :ref:`Subprocesses <asyncio-subprocess>` are not supported
-  (ex: :meth:`~BaseEventLoop.subprocess_exec`,
-  :meth:`~BaseEventLoop.subprocess_shell`)
+  (ex: :meth:`~AbstractEventLoop.subprocess_exec`,
+  :meth:`~AbstractEventLoop.subprocess_shell`)
 
 :class:`ProactorEventLoop` specific limits:
 
-- :meth:`~BaseEventLoop.create_datagram_endpoint` (UDP) is not supported
-- :meth:`~BaseEventLoop.add_reader` and :meth:`~BaseEventLoop.add_writer` are
+- :meth:`~AbstractEventLoop.create_datagram_endpoint` (UDP) is not supported
+- :meth:`~AbstractEventLoop.add_reader` and :meth:`~AbstractEventLoop.add_writer` are
   not supported
 
 The resolution of the monotonic clock on Windows is usually around 15.6 msec.
@@ -167,7 +167,7 @@ An event loop policy must implement the following interface:
 
       Get the event loop for the current context.
 
-      Returns an event loop object implementing the :class:`BaseEventLoop`
+      Returns an event loop object implementing the :class:`AbstractEventLoop`
       interface.
 
       Raises an exception in case no event loop has been set for the current
index 23d34d0..c0342f7 100644 (file)
@@ -11,7 +11,7 @@ Transports
 
 Transports are classes provided by :mod:`asyncio` in order to abstract
 various kinds of communication channels.  You generally won't instantiate
-a transport yourself; instead, you will call a :class:`BaseEventLoop` method
+a transport yourself; instead, you will call an :class:`AbstractEventLoop` method
 which will create the transport and try to initiate the underlying
 communication channel, calling you back when it succeeds.
 
@@ -87,6 +87,19 @@ BaseTransport
 
         - ``'subprocess'``: :class:`subprocess.Popen` instance
 
+   .. method:: set_protocol(protocol)
+
+      Set a new protocol.  Switching protocol should only be done when both
+      protocols are documented to support the switch.
+
+      .. versionadded:: 3.5.3
+
+   .. method:: get_protocol
+
+      Return the current protocol.
+
+      .. versionadded:: 3.5.3
+
    .. versionchanged:: 3.5.1
       ``'ssl_object'`` info was added to SSL sockets.
 
@@ -372,10 +385,10 @@ The following callbacks are called on :class:`Protocol` instances:
    (for example by calling :meth:`write_eof`, if the other end also uses
    asyncio).
 
-   This method may return a false value (including None), in which case
+   This method may return a false value (including ``None``), in which case
    the transport will close itself.  Conversely, if this method returns a
    true value, closing the transport is up to the protocol.  Since the
-   default implementation returns None, it implicitly closes the connection.
+   default implementation returns ``None``, it implicitly closes the connection.
 
    .. note::
       Some transports such as SSL don't support half-closed connections,
@@ -475,7 +488,7 @@ Protocol examples
 TCP echo client protocol
 ------------------------
 
-TCP echo client  using the :meth:`BaseEventLoop.create_connection` method, send
+TCP echo client  using the :meth:`AbstractEventLoop.create_connection` method, send
 data and wait until the connection is closed::
 
     import asyncio
@@ -506,10 +519,10 @@ data and wait until the connection is closed::
     loop.close()
 
 The event loop is running twice. The
-:meth:`~BaseEventLoop.run_until_complete` method is preferred in this short
+:meth:`~AbstractEventLoop.run_until_complete` method is preferred in this short
 example to raise an exception if the server is not listening, instead of
 having to write a short coroutine to handle the exception and stop the
-running loop. At :meth:`~BaseEventLoop.run_until_complete` exit, the loop is
+running loop. At :meth:`~AbstractEventLoop.run_until_complete` exit, the loop is
 no longer running, so there is no need to stop the loop in case of an error.
 
 .. seealso::
@@ -523,7 +536,7 @@ no longer running, so there is no need to stop the loop in case of an error.
 TCP echo server protocol
 ------------------------
 
-TCP echo server using the :meth:`BaseEventLoop.create_server` method, send back
+TCP echo server using the :meth:`AbstractEventLoop.create_server` method, send back
 received data and close the connection::
 
     import asyncio
@@ -577,7 +590,7 @@ methods are not coroutines.
 UDP echo client protocol
 ------------------------
 
-UDP echo client using the :meth:`BaseEventLoop.create_datagram_endpoint`
+UDP echo client using the :meth:`AbstractEventLoop.create_datagram_endpoint`
 method, send data and close the transport when we received the answer::
 
     import asyncio
@@ -623,7 +636,7 @@ method, send data and close the transport when we received the answer::
 UDP echo server protocol
 ------------------------
 
-UDP echo server using the :meth:`BaseEventLoop.create_datagram_endpoint`
+UDP echo server using the :meth:`AbstractEventLoop.create_datagram_endpoint`
 method, send back received data::
 
     import asyncio
@@ -660,7 +673,7 @@ Register an open socket to wait for data using a protocol
 ---------------------------------------------------------
 
 Wait until a socket receives data using the
-:meth:`BaseEventLoop.create_connection` method with a protocol, and then close
+:meth:`AbstractEventLoop.create_connection` method with a protocol, and then close
 the event loop ::
 
     import asyncio
@@ -708,7 +721,7 @@ the event loop ::
 
    The :ref:`watch a file descriptor for read events
    <asyncio-watch-read-event>` example uses the low-level
-   :meth:`BaseEventLoop.add_reader` method to register the file descriptor of a
+   :meth:`AbstractEventLoop.add_reader` method to register the file descriptor of a
    socket.
 
    The :ref:`register an open socket to wait for data using streams
index 08fe071..6177b4b 100644 (file)
@@ -18,14 +18,14 @@ Stream functions
 
 .. coroutinefunction:: open_connection(host=None, port=None, \*, loop=None, limit=None, \*\*kwds)
 
-   A wrapper for :meth:`~BaseEventLoop.create_connection()` returning a (reader,
+   A wrapper for :meth:`~AbstractEventLoop.create_connection()` returning a (reader,
    writer) pair.
 
    The reader returned is a :class:`StreamReader` instance; the writer is
    a :class:`StreamWriter` instance.
 
    The arguments are all the usual arguments to
-   :meth:`BaseEventLoop.create_connection` except *protocol_factory*; most
+   :meth:`AbstractEventLoop.create_connection` except *protocol_factory*; most
    common are positional host and port, with various optional keyword arguments
    following.
 
@@ -38,7 +38,7 @@ Stream functions
 .. coroutinefunction:: start_server(client_connected_cb, host=None, port=None, \*, loop=None, limit=None, \*\*kwds)
 
    Start a socket server, with a callback for each client connected. The return
-   value is the same as :meth:`~BaseEventLoop.create_server()`.
+   value is the same as :meth:`~AbstractEventLoop.create_server()`.
 
    The *client_connected_cb* parameter is called with two parameters:
    *client_reader*, *client_writer*.  *client_reader* is a
@@ -49,7 +49,7 @@ Stream functions
    converted into a :class:`Task`.
 
    The rest of the arguments are all the usual arguments to
-   :meth:`~BaseEventLoop.create_server()` except *protocol_factory*; most
+   :meth:`~AbstractEventLoop.create_server()` except *protocol_factory*; most
    common are positional *host* and *port*, with various optional keyword
    arguments following.
 
@@ -61,7 +61,7 @@ Stream functions
 
 .. coroutinefunction:: open_unix_connection(path=None, \*, loop=None, limit=None, **kwds)
 
-   A wrapper for :meth:`~BaseEventLoop.create_unix_connection()` returning
+   A wrapper for :meth:`~AbstractEventLoop.create_unix_connection()` returning
    a (reader, writer) pair.
 
    See :func:`open_connection` for information about return value and other
@@ -142,7 +142,7 @@ StreamReader
 
       This method is a :ref:`coroutine <coroutine>`.
 
-   .. coroutinemethod:: readuntil(separator=b'\n')
+   .. coroutinemethod:: readuntil(separator=b'\\n')
 
       Read data from the stream until ``separator`` is found.
 
@@ -321,7 +321,7 @@ TCP echo client using the :func:`asyncio.open_connection` function::
 .. seealso::
 
    The :ref:`TCP echo client protocol <asyncio-tcp-echo-client-protocol>`
-   example uses the :meth:`BaseEventLoop.create_connection` method.
+   example uses the :meth:`AbstractEventLoop.create_connection` method.
 
 
 .. _asyncio-tcp-echo-server-streams:
@@ -366,7 +366,7 @@ TCP echo server using the :func:`asyncio.start_server` function::
 .. seealso::
 
    The :ref:`TCP echo server protocol <asyncio-tcp-echo-server-protocol>`
-   example uses the :meth:`BaseEventLoop.create_server` method.
+   example uses the :meth:`AbstractEventLoop.create_server` method.
 
 
 Get HTTP headers
@@ -458,10 +458,10 @@ Coroutine waiting until a socket receives data using the
 
    The :ref:`register an open socket to wait for data using a protocol
    <asyncio-register-socket>` example uses a low-level protocol created by the
-   :meth:`BaseEventLoop.create_connection` method.
+   :meth:`AbstractEventLoop.create_connection` method.
 
    The :ref:`watch a file descriptor for read events
    <asyncio-watch-read-event>` example uses the low-level
-   :meth:`BaseEventLoop.add_reader` method to register the file descriptor of a
+   :meth:`AbstractEventLoop.add_reader` method to register the file descriptor of a
    socket.
 
index 51ce427..dc93a74 100644 (file)
@@ -32,7 +32,7 @@ Create a subprocess: high-level API using Process
    Create a subprocess.
 
    The *limit* parameter sets the buffer limit passed to the
-   :class:`StreamReader`. See :meth:`BaseEventLoop.subprocess_exec` for other
+   :class:`StreamReader`. See :meth:`AbstractEventLoop.subprocess_exec` for other
    parameters.
 
    Return a :class:`~asyncio.subprocess.Process` instance.
@@ -44,7 +44,7 @@ Create a subprocess: high-level API using Process
    Run the shell command *cmd*.
 
    The *limit* parameter sets the buffer limit passed to the
-   :class:`StreamReader`. See :meth:`BaseEventLoop.subprocess_shell` for other
+   :class:`StreamReader`. See :meth:`AbstractEventLoop.subprocess_shell` for other
    parameters.
 
    Return a :class:`~asyncio.subprocess.Process` instance.
@@ -58,8 +58,8 @@ Create a subprocess: high-level API using Process
 
    This function is a :ref:`coroutine <coroutine>`.
 
-Use the :meth:`BaseEventLoop.connect_read_pipe` and
-:meth:`BaseEventLoop.connect_write_pipe` methods to connect pipes.
+Use the :meth:`AbstractEventLoop.connect_read_pipe` and
+:meth:`AbstractEventLoop.connect_write_pipe` methods to connect pipes.
 
 
 Create a subprocess: low-level API using subprocess.Popen
@@ -67,7 +67,7 @@ Create a subprocess: low-level API using subprocess.Popen
 
 Run subprocesses asynchronously using the :mod:`subprocess` module.
 
-.. coroutinemethod:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
+.. coroutinemethod:: AbstractEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
 
    Create a subprocess from one or more string arguments (character strings or
    bytes strings encoded to the :ref:`filesystem encoding
@@ -87,19 +87,19 @@ Run subprocesses asynchronously using the :mod:`subprocess` module.
 
    * *stdin*: Either a file-like object representing the pipe to be connected
      to the subprocess's standard input stream using
-     :meth:`~BaseEventLoop.connect_write_pipe`, or the constant
+     :meth:`~AbstractEventLoop.connect_write_pipe`, or the constant
      :const:`subprocess.PIPE` (the default). By default a new pipe will be
      created and connected.
 
    * *stdout*: Either a file-like object representing the pipe to be connected
      to the subprocess's standard output stream using
-     :meth:`~BaseEventLoop.connect_read_pipe`, or the constant
+     :meth:`~AbstractEventLoop.connect_read_pipe`, or the constant
      :const:`subprocess.PIPE` (the default). By default a new pipe will be
      created and connected.
 
    * *stderr*: Either a file-like object representing the pipe to be connected
      to the subprocess's standard error stream using
-     :meth:`~BaseEventLoop.connect_read_pipe`, or one of the constants
+     :meth:`~AbstractEventLoop.connect_read_pipe`, or one of the constants
      :const:`subprocess.PIPE` (the default) or :const:`subprocess.STDOUT`.
      By default a new pipe will be created and connected. When
      :const:`subprocess.STDOUT` is specified, the subprocess's standard error
@@ -116,7 +116,7 @@ Run subprocesses asynchronously using the :mod:`subprocess` module.
 
    See the constructor of the :class:`subprocess.Popen` class for parameters.
 
-.. coroutinemethod:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
+.. coroutinemethod:: AbstractEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, \*\*kwargs)
 
    Create a subprocess from *cmd*, which is a character string or a bytes
    string encoded to the :ref:`filesystem encoding <filesystem-encoding>`,
@@ -126,7 +126,7 @@ Run subprocesses asynchronously using the :mod:`subprocess` module.
    The *protocol_factory* must instanciate a subclass of the
    :class:`asyncio.SubprocessProtocol` class.
 
-   See :meth:`~BaseEventLoop.subprocess_exec` for more details about
+   See :meth:`~AbstractEventLoop.subprocess_exec` for more details about
    the remaining arguments.
 
    Returns a pair of ``(transport, protocol)``, where *transport* is an
@@ -143,8 +143,8 @@ Run subprocesses asynchronously using the :mod:`subprocess` module.
 
 .. seealso::
 
-   The :meth:`BaseEventLoop.connect_read_pipe` and
-   :meth:`BaseEventLoop.connect_write_pipe` methods.
+   The :meth:`AbstractEventLoop.connect_read_pipe` and
+   :meth:`AbstractEventLoop.connect_write_pipe` methods.
 
 
 Constants
@@ -329,7 +329,7 @@ Subprocess using transport and protocol
 
 Example of a subprocess protocol using to get the output of a subprocess and to
 wait for the subprocess exit. The subprocess is created by the
-:meth:`BaseEventLoop.subprocess_exec` method::
+:meth:`AbstractEventLoop.subprocess_exec` method::
 
     import asyncio
     import sys
index de6ee58..9bff1c4 100644 (file)
@@ -59,7 +59,7 @@ the coroutine object returned by the call doesn't do anything until you
 schedule its execution.  There are two basic ways to start it running:
 call ``await coroutine`` or ``yield from coroutine`` from another coroutine
 (assuming the other coroutine is already running!), or schedule its execution
-using the :func:`ensure_future` function or the :meth:`BaseEventLoop.create_task`
+using the :func:`ensure_future` function or the :meth:`AbstractEventLoop.create_task`
 method.
 
 
@@ -108,7 +108,7 @@ Example of coroutine displaying ``"Hello World"``::
 .. seealso::
 
    The :ref:`Hello World with call_soon() <asyncio-hello-world-callback>`
-   example uses the :meth:`BaseEventLoop.call_soon` method to schedule a
+   example uses the :meth:`AbstractEventLoop.call_soon` method to schedule a
    callback.
 
 
@@ -151,7 +151,7 @@ The same coroutine implemented using a generator::
 
    The :ref:`display the current date with call_later()
    <asyncio-date-callback>` example uses a callback with the
-   :meth:`BaseEventLoop.call_later` method.
+   :meth:`AbstractEventLoop.call_later` method.
 
 
 Example: Chain coroutines
@@ -182,12 +182,12 @@ Sequence diagram of the example:
 .. image:: tulip_coro.png
    :align: center
 
-The "Task" is created by the :meth:`BaseEventLoop.run_until_complete` method
+The "Task" is created by the :meth:`AbstractEventLoop.run_until_complete` method
 when it gets a coroutine object instead of a task.
 
 The diagram shows the control flow, it does not describe exactly how things
 work internally. For example, the sleep coroutine creates an internal future
-which uses :meth:`BaseEventLoop.call_later` to wake up the task in 1 second.
+which uses :meth:`AbstractEventLoop.call_later` to wake up the task in 1 second.
 
 
 InvalidStateError
@@ -223,7 +223,7 @@ Future
      raise an exception when the future isn't done yet.
 
    - Callbacks registered with :meth:`add_done_callback` are always called
-     via the event loop's :meth:`~BaseEventLoop.call_soon_threadsafe`.
+     via the event loop's :meth:`~AbstractEventLoop.call_soon_threadsafe`.
 
    - This class is not compatible with the :func:`~concurrent.futures.wait` and
      :func:`~concurrent.futures.as_completed` functions in the
@@ -245,7 +245,7 @@ Future
 
    .. method:: done()
 
-      Return True if the future is done.
+      Return ``True`` if the future is done.
 
       Done means either that a result / exception are available, or that the
       future was cancelled.
@@ -273,7 +273,7 @@ Future
 
       The callback is called with a single argument - the future object. If the
       future is already done when this is called, the callback is scheduled
-      with :meth:`~BaseEventLoop.call_soon`.
+      with :meth:`~AbstractEventLoop.call_soon`.
 
       :ref:`Use functools.partial to pass parameters to the callback
       <asyncio-pass-keywords>`. For example,
@@ -323,11 +323,11 @@ Example combining a :class:`Future` and a :ref:`coroutine function
 
 The coroutine function is responsible for the computation (which takes 1 second)
 and it stores the result into the future. The
-:meth:`~BaseEventLoop.run_until_complete` method waits for the completion of
+:meth:`~AbstractEventLoop.run_until_complete` method waits for the completion of
 the future.
 
 .. note::
-   The :meth:`~BaseEventLoop.run_until_complete` method uses internally the
+   The :meth:`~AbstractEventLoop.run_until_complete` method uses internally the
    :meth:`~Future.add_done_callback` method to be notified when the future is
    done.
 
@@ -374,7 +374,7 @@ Task
 
    A task is responsible for executing a coroutine object in an event loop.  If
    the wrapped coroutine yields from a future, the task suspends the execution
-   of the wrapped coroutine and waits for the completition of the future. When
+   of the wrapped coroutine and waits for the completion of the future. When
    the future is done, the execution of the wrapped coroutine restarts with the
    result or the exception of the future.
 
@@ -396,7 +396,7 @@ Task
    logged: see :ref:`Pending task destroyed <asyncio-pending-task-destroyed>`.
 
    Don't directly create :class:`Task` instances: use the :func:`ensure_future`
-   function or the :meth:`BaseEventLoop.create_task` method.
+   function or the :meth:`AbstractEventLoop.create_task` method.
 
    This class is :ref:`not thread safe <asyncio-multithreading>`.
 
@@ -486,7 +486,7 @@ Example executing 3 tasks (A, B, C) in parallel::
         asyncio.ensure_future(factorial("A", 2)),
         asyncio.ensure_future(factorial("B", 3)),
         asyncio.ensure_future(factorial("C", 4))]
-    loop.run_until_complete(asyncio.wait(tasks))
+    loop.run_until_complete(asyncio.gather(*tasks))
     loop.close()
 
 Output::
@@ -546,7 +546,7 @@ Task functions
 
    .. seealso::
 
-      The :meth:`BaseEventLoop.create_task` method.
+      The :meth:`AbstractEventLoop.create_task` method.
 
 .. function:: async(coro_or_future, \*, loop=None)
 
@@ -562,7 +562,7 @@ Task functions
    All futures must share the same event loop.  If all the tasks are done
    successfully, the returned future's result is the list of results (in the
    order of the original sequence, not necessarily the order of results
-   arrival).  If *return_exceptions* is True, exceptions in the tasks are
+   arrival).  If *return_exceptions* is true, exceptions in the tasks are
    treated the same as successful results, and gathered in the result list;
    otherwise, the first raised exception will be immediately propagated to the
    returned future.
index f764c68..76bd9e9 100644 (file)
@@ -1,5 +1,5 @@
-:mod:`asyncio` -- Asynchronous I/O, event loop, coroutines and tasks
-====================================================================
+:mod:`asyncio` --- Asynchronous I/O, event loop, coroutines and tasks
+=====================================================================
 
 .. module:: asyncio
    :synopsis: Asynchronous I/O, event loop, coroutines and tasks.
index 61061be..c838be7 100644 (file)
@@ -57,7 +57,7 @@ any that have been added to the map during asynchronous service) is closed.
 
    Enter a polling loop that terminates after count passes or all open
    channels have been closed.  All arguments are optional.  The *count*
-   parameter defaults to None, resulting in the loop terminating only when all
+   parameter defaults to ``None``, resulting in the loop terminating only when all
    channels have been closed.  The *timeout* argument sets the timeout
    parameter for the appropriate :func:`~select.select` or :func:`~select.poll`
    call, measured in seconds; the default is 30 seconds.  The *use_poll*
index 8ee9921..116ffcf 100644 (file)
@@ -241,7 +241,7 @@ The :mod:`bdb` module also defines two classes:
    .. method:: set_continue()
 
       Stop only at breakpoints or when finished.  If there are no breakpoints,
-      set the system trace function to None.
+      set the system trace function to ``None``.
 
    .. method:: set_quit()
 
index 878d8db..49da59a 100644 (file)
@@ -115,8 +115,10 @@ The :mod:`binascii` module defines the following functions:
 
 .. function:: crc_hqx(data, value)
 
-   Compute the binhex4 crc value of *data*, starting with *value* as the
-   initial crc, and return the result.
+   Compute a 16-bit CRC value of *data*, starting with *value* as the
+   initial CRC, and return the result.  This uses the CRC-CCITT polynomial
+   *x*:sup:`16` + *x*:sup:`12` + *x*:sup:`5` + 1, often represented as
+   0x1021.  This CRC is used in the binhex4 format.
 
 
 .. function:: crc32(data[, value])
index 4b589a5..8fb1fef 100644 (file)
@@ -37,6 +37,6 @@ that wants to implement an :func:`open` function that wraps the built-in
 
 As an implementation detail, most modules have the name ``__builtins__`` made
 available as part of their globals.  The value of ``__builtins__`` is normally
-either this module or the value of this module's :attr:`__dict__` attribute.
+either this module or the value of this module's :attr:`~object.__dict__` attribute.
 Since this is an implementation detail, it may not be used by alternate
 implementations of Python.
index df76e33..41e9e28 100644 (file)
@@ -47,7 +47,7 @@ it's the base calendar for all computations.
 
    .. method:: itermonthdates(year, month)
 
-      Return an iterator for the month *month* (1-12) in the year *year*. This
+      Return an iterator for the month *month* (1--12) in the year *year*. This
       iterator will return all days (as :class:`datetime.date` objects) for the
       month and all days before the start of the month or after the end of the
       month that are required to get a complete week.
index 0bc2c35..41219ee 100644 (file)
@@ -442,7 +442,9 @@ installing a copy of this module file (:file:`cgi.py`) as a CGI script.  When
 invoked as a script, the file will dump its environment and the contents of the
 form in HTML form. Give it the right mode etc, and send it a request.  If it's
 installed in the standard :file:`cgi-bin` directory, it should be possible to
-send it a request by entering a URL into your browser of the form::
+send it a request by entering a URL into your browser of the form:
+
+.. code-block:: none
 
    http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home
 
@@ -534,4 +536,3 @@ Common problems and solutions
    order the field values should be supplied in, but knowing whether a request
    was received from a conforming browser, or even from a browser at all, is
    tedious and error-prone.
-
index 62ddb6b..e113ffc 100644 (file)
@@ -275,6 +275,6 @@ 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.
+   in numerical analysis. Clarendon Press (1987) pp165--211.
 
 
index 61ef0f6..f40cfdf 100644 (file)
@@ -314,7 +314,9 @@ immediate playback::
 
 
 Here is a sample session with the turtle shell showing the help functions, using
-blank lines to repeat commands, and the simple record and playback facility::
+blank lines to repeat commands, and the simple record and playback facility:
+
+.. code-block:: none
 
     Welcome to the turtle shell.   Type help or ? to list commands.
 
@@ -373,4 +375,3 @@ blank lines to repeat commands, and the simple record and playback facility::
 
     (turtle) bye
     Thank you for using Turtle
-
index 1add300..f38e41b 100644 (file)
@@ -224,6 +224,10 @@ wider range of codecs when working with binary files:
    The *errors* argument (as well as any
    other keyword argument) is passed through to the incremental encoder.
 
+   This function requires that the codec accept text :class:`str` objects
+   to encode. Therefore it does not support bytes-to-bytes encoders such as
+   ``base64_codec``.
+
 
 .. function:: iterdecode(iterator, encoding, errors='strict', **kwargs)
 
@@ -232,6 +236,11 @@ wider range of codecs when working with binary files:
    The *errors* argument (as well as any
    other keyword argument) is passed through to the incremental decoder.
 
+   This function requires that the codec accept :class:`bytes` objects
+   to decode. Therefore it does not support text-to-text encoders such as
+   ``rot_13``, although ``rot_13`` may be used equivalently with
+   :func:`iterencode`.
+
 
 The module also provides the following constants which are useful for reading
 and writing to platform dependent files:
@@ -849,7 +858,7 @@ Encodings and Unicode
 ---------------------
 
 Strings are stored internally as sequences of code points in
-range ``0x0``-``0x10FFFF``.  (See :pep:`393` for
+range ``0x0``--``0x10FFFF``.  (See :pep:`393` for
 more details about the implementation.)
 Once a string object is used outside of CPU and memory, endianness
 and how these arrays are stored as bytes become an issue.  As with other
@@ -859,7 +868,7 @@ There are a variety of different text serialisation codecs, which are
 collectivity referred to as :term:`text encodings <text encoding>`.
 
 The simplest text encoding (called ``'latin-1'`` or ``'iso-8859-1'``) maps
-the code points 0-255 to the bytes ``0x0``-``0xff``, which means that a string
+the code points 0--255 to the bytes ``0x0``--``0xff``, which means that a string
 object that contains code points above ``U+00FF`` can't be encoded with this
 codec. Doing so will raise a :exc:`UnicodeEncodeError` that looks
 like the following (although the details of the error message may differ):
@@ -868,7 +877,7 @@ position 3: ordinal not in range(256)``.
 
 There's another group of encodings (the so called charmap encodings) that choose
 a different subset of all Unicode code points and how these code points are
-mapped to the bytes ``0x0``-``0xff``. To see how this is done simply open
+mapped to the bytes ``0x0``--``0xff``. To see how this is done simply open
 e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
 Windows). There's a string constant with 256 characters that shows you which
 character is mapped to which byte value.
index 61682cc..aeb6a73 100644 (file)
@@ -55,6 +55,9 @@ ABC                        Inherits from          Abstract Methods        Mixin
                                                   ``__len__``,
                                                   ``insert``
 
+: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``
@@ -119,6 +122,7 @@ ABC                        Inherits from          Abstract Methods        Mixin
 
 .. class:: Sequence
            MutableSequence
+           ByteString
 
    ABCs for read-only and mutable :term:`sequences <sequence>`.
 
@@ -135,7 +139,6 @@ ABC                        Inherits from          Abstract Methods        Mixin
       The index() method added support for *stop* and *start*
       arguments.
 
-
 .. class:: Set
            MutableSet
 
index 4936b3a..d0aa62e 100644 (file)
@@ -263,7 +263,7 @@ For example::
         is less than one, :meth:`elements` will ignore it.
 
             >>> c = Counter(a=4, b=2, c=0, d=-2)
-            >>> list(c.elements())
+            >>> sorted(c.elements())
             ['a', 'a', 'a', 'a', 'b', 'b']
 
     .. method:: most_common([n])
@@ -273,7 +273,7 @@ For example::
         :func:`most_common` returns *all* elements in the counter.
         Elements with equal counts are ordered arbitrarily:
 
-            >>> Counter('abracadabra').most_common(3)
+            >>> Counter('abracadabra').most_common(3)  # doctest: +SKIP
             [('a', 5), ('r', 2), ('b', 2)]
 
     .. method:: subtract([iterable-or-mapping])
@@ -329,7 +329,7 @@ counts, but the output will exclude results with counts of zero or less.
     Counter({'a': 4, 'b': 3})
     >>> c - d                       # subtract (keeping only positive counts)
     Counter({'a': 2})
-    >>> c & d                       # intersection:  min(c[x], d[x])
+    >>> c & d                       # intersection:  min(c[x], d[x]) # doctest: +SKIP
     Counter({'a': 1, 'b': 1})
     >>> c | d                       # union:  max(c[x], d[x])
     Counter({'a': 3, 'b': 2})
@@ -412,7 +412,7 @@ or subtracting from an empty counter.
     position of the underlying data representation.
 
 
-    If *maxlen* is not specified or is *None*, deques may grow to an
+    If *maxlen* is not specified or is ``None``, deques may grow to an
     arbitrary length.  Otherwise, the deque is bounded to the specified maximum
     length.  Once a bounded length deque is full, when new items are added, a
     corresponding number of items are discarded from the opposite end.  Bounded
@@ -520,7 +520,7 @@ or subtracting from an empty counter.
 
     .. attribute:: maxlen
 
-        Maximum size of a deque or *None* if unbounded.
+        Maximum size of a deque or ``None`` if unbounded.
 
         .. versionadded:: 3.1
 
@@ -698,7 +698,7 @@ sequence of key-value pairs into a dictionary of lists:
     >>> for k, v in s:
     ...     d[k].append(v)
     ...
-    >>> list(d.items())
+    >>> sorted(d.items())
     [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
 
 When each key is encountered for the first time, it is not already in the
@@ -713,7 +713,7 @@ simpler and faster than an equivalent technique using :meth:`dict.setdefault`:
     >>> for k, v in s:
     ...     d.setdefault(k, []).append(v)
     ...
-    >>> list(d.items())
+    >>> sorted(d.items())
     [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
 
 Setting the :attr:`default_factory` to :class:`int` makes the
@@ -725,8 +725,8 @@ languages):
     >>> for k in s:
     ...     d[k] += 1
     ...
-    >>> list(d.items())
-    [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
+    >>> sorted(d.items())
+    [('i', 4), ('m', 1), ('p', 2), ('s', 4)]
 
 When a letter is first encountered, it is missing from the mapping, so the
 :attr:`default_factory` function calls :func:`int` to supply a default count of
@@ -752,7 +752,7 @@ Setting the :attr:`default_factory` to :class:`set` makes the
     >>> for k, v in s:
     ...     d[k].add(v)
     ...
-    >>> list(d.items())
+    >>> sorted(d.items())
     [('blue', {2, 4}), ('red', {1, 3})]
 
 
@@ -793,11 +793,6 @@ they add the ability to access fields by name instead of position index.
     Named tuple instances do not have per-instance dictionaries, so they are
     lightweight and require no more memory than regular tuples.
 
-    For simple uses, where the only requirement is to be able to refer to a set
-    of values by name using attribute-style access, the
-    :class:`types.SimpleNamespace` type can be a suitable alternative to using
-    a namedtuple.
-
     .. versionchanged:: 3.1
         Added support for *rename*.
 
@@ -914,15 +909,15 @@ functionality with a subclass.  Here is how to add a calculated field and
 a fixed-width print format:
 
     >>> 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)
+    ...     __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)
+    ...     print(p)
     Point: x= 3.000  y= 4.000  hypot= 5.000
     Point: x=14.000  y= 0.714  hypot=14.018
 
index eeae96a..8d141a2 100644 (file)
@@ -66,7 +66,7 @@ The structure of INI files is described `in the following section
 <#supported-ini-file-structure>`_.  Essentially, the file
 consists of sections, each of which contains keys with values.
 :mod:`configparser` classes can read and write such files.  Let's start by
-creating the above configuration file programatically.
+creating the above configuration file programmatically.
 
 .. doctest::
 
@@ -150,8 +150,8 @@ Since this task is so common, config parsers provide a range of handy getter
 methods to handle integers, floats and booleans.  The last one is the most
 interesting because simply passing the value to ``bool()`` would do no good
 since ``bool('False')`` is still ``True``.  This is why config parsers also
-provide :meth:`getboolean`.  This method is case-insensitive and recognizes
-Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
+provide :meth:`~ConfigParser.getboolean`.  This method is case-insensitive and
+recognizes Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
 ``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_.  For example:
 
 .. doctest::
@@ -163,8 +163,9 @@ Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
    >>> config.getboolean('bitbucket.org', 'Compression')
    True
 
-Apart from :meth:`getboolean`, config parsers also provide equivalent
-:meth:`getint` and :meth:`getfloat` methods.  You can register your own
+Apart from :meth:`~ConfigParser.getboolean`, config parsers also
+provide equivalent :meth:`~ConfigParser.getint` and
+:meth:`~ConfigParser.getfloat` methods.  You can register your own
 converters and customize the provided ones. [1]_
 
 Fallback Values
@@ -205,8 +206,9 @@ the ``fallback`` keyword-only argument:
    ...            fallback='No such things as monsters')
    'No such things as monsters'
 
-The same ``fallback`` argument can be used with the :meth:`getint`,
-:meth:`getfloat` and :meth:`getboolean` methods, for example:
+The same ``fallback`` argument can be used with the
+:meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat` and
+:meth:`~ConfigParser.getboolean` methods, for example:
 
 .. doctest::
 
@@ -670,14 +672,15 @@ the :meth:`__init__` options:
 * *converters*, default value: not set
 
   Config parsers provide option value getters that perform type conversion.  By
-  default :meth:`getint`, :meth:`getfloat`, and :meth:`getboolean` are
-  implemented.  Should other getters be desirable, users may define them in
-  a subclass or pass a dictionary where each key is a name of the converter and
-  each value is a callable implementing said conversion.  For instance, passing
-  ``{'decimal': decimal.Decimal}`` would add :meth:`getdecimal` on both the
-  parser object and all section proxies.  In other words, it will be possible
-  to write both ``parser_instance.getdecimal('section', 'key', fallback=0)``
-  and ``parser_instance['section'].getdecimal('key', 0)``.
+  default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, and
+  :meth:`~ConfigParser.getboolean` are implemented.  Should other getters be
+  desirable, users may define them in a subclass or pass a dictionary where each
+  key is a name of the converter and each value is a callable implementing said
+  conversion.  For instance, passing ``{'decimal': decimal.Decimal}`` would add
+  :meth:`getdecimal` on both the parser object and all section proxies.  In
+  other words, it will be possible to write both
+  ``parser_instance.getdecimal('section', 'key', fallback=0)`` and
+  ``parser_instance['section'].getdecimal('key', 0)``.
 
   If the converter needs to access the state of the parser, it can be
   implemented as a method on a config parser subclass.  If the name of this
@@ -690,11 +693,11 @@ be overridden by subclasses or by attribute assignment.
 
 .. attribute:: BOOLEAN_STATES
 
-  By default when using :meth:`getboolean`, config parsers consider the
-  following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
-  following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``.  You
-  can override this by specifying a custom dictionary of strings and their
-  Boolean outcomes. For example:
+  By default when using :meth:`~ConfigParser.getboolean`, config parsers
+  consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``,
+  ``'on'`` and the following values ``False``: ``'0'``, ``'no'``, ``'false'``,
+  ``'off'``.  You can override this by specifying a custom dictionary of strings
+  and their Boolean outcomes. For example:
 
   .. doctest::
 
index a8adcad..d0b861d 100644 (file)
@@ -48,7 +48,7 @@ copy operations:
   reference to themselves) may cause a recursive loop.
 
 * Because deep copy copies *everything* it may copy too much, e.g.,
-  administrative data structures that should be shared even between copies.
+  even administrative data structures that should be shared even between copies.
 
 The :func:`deepcopy` function avoids these problems by:
 
index a675790..b25fbbb 100644 (file)
@@ -1253,7 +1253,7 @@ the library to load.
 
    Try to find a library and return a pathname.  *name* is the library name without
    any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
-   is the form used for the posix linker option :option:`-l`).  If no library can
+   is the form used for the posix linker option :option:`!-l`).  If no library can
    be found, returns ``None``.
 
 The exact functionality is system dependent.
@@ -1354,10 +1354,11 @@ function is used to load the library into the process, and to get a handle to
 it.
 
 The *mode* parameter can be used to specify how the library is loaded.  For
-details, consult the :manpage:`dlopen(3)` manpage, on Windows, *mode* is
-ignored.
+details, consult the :manpage:`dlopen(3)` manpage.  On Windows, *mode* is
+ignored.  On posix systems, RTLD_NOW is always added, and is not
+configurable.
 
-The *use_errno* parameter, when set to True, enables a ctypes mechanism that
+The *use_errno* parameter, when set to true, enables a ctypes mechanism that
 allows accessing the system :data:`errno` error number in a safe way.
 :mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
 variable; if you call foreign functions created with ``use_errno=True`` then the
@@ -1368,7 +1369,7 @@ The function :func:`ctypes.get_errno` returns the value of the ctypes private
 copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
 to a new value and returns the former value.
 
-The *use_last_error* parameter, when set to True, enables the same mechanism for
+The *use_last_error* parameter, when set to true, enables the same mechanism for
 the Windows error code which is managed by the :func:`GetLastError` and
 :func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
 :func:`ctypes.set_last_error` are used to request and change the ctypes private
@@ -1578,7 +1579,7 @@ type and the argument types of the function.
 
    The returned function prototype creates functions that use the standard C
    calling convention.  The function will release the GIL during the call.  If
-   *use_errno* is set to True, the ctypes private copy of the system
+   *use_errno* is set to true, the ctypes private copy of the system
    :data:`errno` variable is exchanged with the real :data:`errno` value before
    and after the call; *use_last_error* does the same for the Windows error
    code.
@@ -1664,32 +1665,30 @@ different ways, depending on the type and number of the parameters in the call:
 
    The optional third item is the default value for this parameter.
 
-This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
+This example demonstrates how to wrap the Windows ``MessageBoxW`` function so
 that it supports default parameters and named arguments. The C declaration from
 the windows header file is this::
 
    WINUSERAPI int WINAPI
-   MessageBoxA(
+   MessageBoxW(
        HWND hWnd,
-       LPCSTR lpText,
-       LPCSTR lpCaption,
+       LPCWSTR lpText,
+       LPCWSTR lpCaption,
        UINT uType);
 
 Here is the wrapping with :mod:`ctypes`::
 
    >>> from ctypes import c_int, WINFUNCTYPE, windll
-   >>> from ctypes.wintypes import HWND, LPCSTR, UINT
-   >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
-   >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
-   >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
-   >>>
+   >>> from ctypes.wintypes import HWND, LPCWSTR, UINT
+   >>> prototype = WINFUNCTYPE(c_int, HWND, LPCWSTR, LPCWSTR, UINT)
+   >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", "Hello from ctypes"), (1, "flags", 0)
+   >>> MessageBox = prototype(("MessageBoxW", windll.user32), paramflags)
 
-The MessageBox foreign function can now be called in these ways::
+The ``MessageBox`` foreign function can now be called in these ways::
 
    >>> MessageBox()
    >>> MessageBox(text="Spam, spam, spam")
    >>> MessageBox(flags=2, text="foo bar")
-   >>>
 
 A second example demonstrates output parameters.  The win32 ``GetWindowRect``
 function retrieves the dimensions of a specified window by copying them into
@@ -1832,7 +1831,7 @@ Utility functions
 
    Try to find a library and return a pathname.  *name* is the library name
    without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
-   number (this is the form used for the posix linker option :option:`-l`).  If
+   number (this is the form used for the posix linker option :option:`!-l`).  If
    no library can be found, returns ``None``.
 
    The exact functionality is system dependent.
index f3661d9..b6ac251 100644 (file)
@@ -115,12 +115,12 @@ C library:
 
 .. function:: isblank(c)
 
-   Checks for an ASCII whitespace character.
+   Checks for an ASCII whitespace character; space or horizontal tab.
 
 
 .. function:: iscntrl(c)
 
-   Checks for an ASCII control character (in the range 0x00 to 0x1f).
+   Checks for an ASCII control character (in the range 0x00 to 0x1f or 0x7f).
 
 
 .. function:: isdigit(c)
@@ -213,7 +213,7 @@ it returns a string.
 
    Return a string representation of the ASCII character *c*.  If *c* is printable,
    this string is the character itself.  If the character is a control character
-   (0x00-0x1f) the string consists of a caret (``'^'``) followed by the
+   (0x00--0x1f) the string consists of a caret (``'^'``) followed by the
    corresponding uppercase letter. If the character is an ASCII delete (0x7f) the
    string is ``'^?'``.  If the character has its meta bit (0x80) set, the meta bit
    is stripped, the preceding rules applied, and ``'!'`` prepended to the result.
index b12a325..d746eaf 100644 (file)
@@ -316,7 +316,7 @@ The module :mod:`curses` defines the following functions:
    Return the name of the key numbered *k*.  The name of a key generating printable
    ASCII character is the key's character.  The name of a control-key combination
    is a two-character string consisting of a caret followed by the corresponding
-   printable ASCII character.  The name of an alt-key combination (128-255) is a
+   printable ASCII character.  The name of an alt-key combination (128--255) is a
    string consisting of the prefix 'M-' followed by the name of the corresponding
    ASCII character.
 
index 9254ae8..4f3cfe3 100644 (file)
@@ -1296,8 +1296,8 @@ Using datetime with tzinfo:
 
 .. _datetime-time:
 
-:class:`time` Objects
----------------------
+:class:`.time` Objects
+----------------------
 
 A time object represents a (local) time of day, independent of any particular
 day, and subject to adjustment via a :class:`tzinfo` object.
@@ -1382,7 +1382,7 @@ Supported operations:
   ``!=``.  The latter cases return :const:`False` or :const:`True`, respectively.
 
   .. versionchanged:: 3.3
-     Equality comparisons between naive and aware :class:`time` instances
+     Equality comparisons between naive and aware :class:`~datetime.time` instances
      don't raise :exc:`TypeError`.
 
 * hash, use as dict key
@@ -1460,7 +1460,7 @@ Instance methods:
 
 Example:
 
-    >>> from datetime import time, tzinfo
+    >>> from datetime import time, tzinfo, timedelta
     >>> class GMT1(tzinfo):
     ...     def utcoffset(self, dt):
     ...         return timedelta(hours=1)
index 6f64196..2a1db91 100644 (file)
@@ -128,6 +128,9 @@ The individual submodules are described in the following sections.
    :platform: Unix
    :synopsis: GNU's reinterpretation of dbm.
 
+**Source code:** :source:`Lib/dbm/gnu.py`
+
+--------------
 
 This module is quite similar to the :mod:`dbm` module, but uses the GNU library
 ``gdbm`` instead to provide some additional functionality.  Please note that the
@@ -237,6 +240,9 @@ supported.
    :platform: Unix
    :synopsis: The standard "database" interface, based on ndbm.
 
+**Source code:** :source:`Lib/dbm/ndbm.py`
+
+--------------
 
 The :mod:`dbm.ndbm` module provides an interface to the Unix "(n)dbm" library.
 Dbm objects behave like mappings (dictionaries), except that keys and values are
@@ -299,6 +305,8 @@ to locate the appropriate header file to simplify building this module.
 .. module:: dbm.dumb
    :synopsis: Portable implementation of the simple DBM interface.
 
+**Source code:** :source:`Lib/dbm/dumb.py`
+
 .. index:: single: databases
 
 .. note::
@@ -308,6 +316,8 @@ to locate the appropriate header file to simplify building this module.
    module is not written for speed and is not nearly as heavily used as the other
    database modules.
 
+--------------
+
 The :mod:`dbm.dumb` module provides a persistent dictionary-like interface which
 is written entirely in Python.  Unlike other modules such as :mod:`dbm.gnu` no
 external library is required.  As with other persistent mappings, the keys and
index 528f97b..b5ce0b1 100644 (file)
@@ -163,7 +163,7 @@ an exception::
    >>> c.traps[FloatOperation] = True
    >>> Decimal(3.14)
    Traceback (most recent call last):
-   File "<stdin>", line 1, in <module>
+     File "<stdin>", line 1, in <module>
    decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
    >>> Decimal('3.5') < 3.7
    Traceback (most recent call last):
@@ -836,11 +836,13 @@ Decimal objects
 
    .. method:: to_eng_string(context=None)
 
-      Convert to an engineering-type string.
+      Convert to a string, using engineering notation if an exponent is needed.
+
+      Engineering notation has an exponent which is a multiple of 3.  This
+      can leave up to 3 digits to the left of the decimal place and may
+      require the addition of either one or two trailing zeros.
 
-      Engineering notation has an exponent which is a multiple of 3, so there
-      are up to 3 digits left of the decimal place.  For example, converts
-      ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.
+      For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.
 
    .. method:: to_integral(rounding=None, context=None)
 
@@ -1410,7 +1412,11 @@ In addition to the three supplied contexts, new contexts can be created with the
 
    .. method:: to_eng_string(x)
 
-      Converts a number to a string, using scientific notation.
+      Convert to a string, using engineering notation if an exponent is needed.
+
+      Engineering notation has an exponent which is a multiple of 3.  This
+      can leave up to 3 digits to the left of the decimal place and may
+      require the addition of either one or two trailing zeros.
 
 
    .. method:: to_integral_exact(x)
index 59a6478..6743bdc 100644 (file)
@@ -170,8 +170,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
 
       >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
       >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
-      >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
-      ...     sys.stdout.write(line)  # doctest: +NORMALIZE_WHITESPACE
+      >>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py', tofile='after.py'))
       *** before.py
       --- after.py
       ***************
@@ -209,7 +208,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
       >>> import keyword
       >>> get_close_matches('wheel', keyword.kwlist)
       ['while']
-      >>> get_close_matches('apple', keyword.kwlist)
+      >>> get_close_matches('pineapple', keyword.kwlist)
       []
       >>> get_close_matches('accept', keyword.kwlist)
       ['except']
@@ -303,8 +302,7 @@ diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
 
       >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
       >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
-      >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
-      ...     sys.stdout.write(line)   # doctest: +NORMALIZE_WHITESPACE
+      >>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py'))
       --- before.py
       +++ after.py
       @@ -1,4 +1,4 @@
index d2d8ac7..f86725b 100644 (file)
@@ -56,12 +56,12 @@ code.
    notably :func:`get_instructions`, as iterating over a :class:`Bytecode`
    instance yields the bytecode operations as :class:`Instruction` instances.
 
-   If *first_line* is not None, it indicates the line number that should be
+   If *first_line* is not ``None``, it indicates the line number that should be
    reported for the first source line in the disassembled code.  Otherwise, the
    source line information (if any) is taken directly from the disassembled code
    object.
 
-   If *current_offset* is not None, it refers to an instruction offset in the
+   If *current_offset* is not ``None``, it refers to an instruction offset in the
    disassembled code. Setting this means :meth:`.dis` will display a "current
    instruction" marker against the specified opcode.
 
@@ -197,7 +197,7 @@ operation is being performed, so the intermediate analysis object isn't useful:
    The iterator generates a series of :class:`Instruction` named tuples giving
    the details of each operation in the supplied code.
 
-   If *first_line* is not None, it indicates the line number that should be
+   If *first_line* is not ``None``, it indicates the line number that should be
    reported for the first source line in the disassembled code.  Otherwise, the
    source line information (if any) is taken directly from the disassembled code
    object.
@@ -249,7 +249,7 @@ details of bytecode instructions as :class:`Instruction` instances:
 
    .. data:: arg
 
-      numeric argument to operation (if any), otherwise None
+      numeric argument to operation (if any), otherwise ``None``
 
 
    .. data:: argval
@@ -269,7 +269,7 @@ details of bytecode instructions as :class:`Instruction` instances:
 
    .. data:: starts_line
 
-      line started by this opcode (if any), otherwise None
+      line started by this opcode (if any), otherwise ``None``
 
 
    .. data:: is_jump_target
index c58f417..131206d 100644 (file)
@@ -88,14 +88,18 @@ Here's a complete but small example module::
        doctest.testmod()
 
 If you run :file:`example.py` directly from the command line, :mod:`doctest`
-works its magic::
+works its magic:
+
+.. code-block:: shell-session
 
    $ python example.py
    $
 
 There's no output!  That's normal, and it means all the examples worked.  Pass
 ``-v`` to the script, and :mod:`doctest` prints a detailed log of what
-it's trying, and prints a summary at the end::
+it's trying, and prints a summary at the end:
+
+.. code-block:: shell-session
 
    $ python example.py -v
    Trying:
@@ -109,7 +113,9 @@ it's trying, and prints a summary at the end::
        [1, 1, 2, 6, 24, 120]
    ok
 
-And so on, eventually ending with::
+And so on, eventually ending with:
+
+.. code-block:: none
 
    Trying:
        factorial(1e100)
@@ -196,7 +202,9 @@ file.  This can be done with the :func:`testfile` function::
 That short script executes and verifies any interactive Python examples
 contained in the file :file:`example.txt`.  The file content is treated as if it
 were a single giant docstring; the file doesn't need to contain a Python
-program!   For example, perhaps :file:`example.txt` contains this::
+program!   For example, perhaps :file:`example.txt` contains this:
+
+.. code-block:: none
 
    The ``example`` module
    ======================
@@ -1207,7 +1215,7 @@ DocTest Objects
 
    .. attribute:: docstring
 
-      The string that the test was extracted from, or 'None' if the string is
+      The string that the test was extracted from, or ``None`` if the string is
       unavailable, or if the test was not extracted from a string.
 
 
@@ -1312,7 +1320,7 @@ DocTestFinder objects
       not specified, then ``obj.__name__`` is used.
 
       The optional parameter *module* is the module that contains the given object.
-      If the module is not specified or is None, then the test finder will attempt
+      If the module is not specified or is ``None``, then the test finder will attempt
       to automatically determine the correct module.  The object's module is used:
 
       * As a default namespace, if *globs* is not specified.
index cbbcb78..ad93b5c 100644 (file)
@@ -59,9 +59,11 @@ way we could process it:
 
 .. literalinclude:: ../includes/email-read-alternative-new-api.py
 
-Up to the prompt, the output from the above is::
+Up to the prompt, the output from the above is:
 
-    To: Penelope Pussycat <"penelope@example.com">, Fabrette Pussycat <"fabrette@example.com">
+.. code-block:: none
+
+    To: Penelope Pussycat <penelope@example.com>, Fabrette Pussycat <fabrette@example.com>
     From: Pepé Le Pew <pepe@example.com>
     Subject: Ayons asperges pour le déjeuner
 
index cd63728..a9c078b 100644 (file)
@@ -347,7 +347,7 @@ Currently the email package provides only one concrete content manager,
 
    .. method:: get_content(msg, errors='replace')
 
-      Return the payload of the part as either a string (for ``text`` parts), a
+      Return the payload of the part as either a string (for ``text`` parts), an
       :class:`~email.message.EmailMessage` object (for ``message/rfc822``
       parts), or a ``bytes`` object (for all other non-multipart types).  Raise
       a :exc:`KeyError` if called on a ``multipart``.  If the part is a
@@ -433,5 +433,5 @@ Currently the email package provides only one concrete content manager,
 
        If *headers* is specified and is a list of strings of the form
        ``headername: headervalue`` or a list of ``header`` objects
-       (distinguised from strings by having a ``name`` attribute), add the
+       (distinguished from strings by having a ``name`` attribute), add the
        headers to *msg*.
index f3e9e18..d53ab33 100644 (file)
@@ -50,9 +50,9 @@ The following function has been added as a useful debugging tool.  It should
 
    .. testsetup::
 
-      >>> import email
-      >>> from email.iterators import _structure
-      >>> somefile = open('Lib/test/test_email/data/msg_02.txt')
+      import email
+      from email.iterators import _structure
+      somefile = open('../Lib/test/test_email/data/msg_02.txt')
 
    .. doctest::
 
@@ -74,9 +74,9 @@ The following function has been added as a useful debugging tool.  It should
                   text/plain
           text/plain
 
-   .. testsetup::
+   .. testcleanup::
 
-      >>> somefile.close()
+      somefile.close()
 
    Optional *fp* is a file-like object to print the output to.  It must be
    suitable for Python's :func:`print` function.  *level* is used internally.
index 91a694f..2907975 100644 (file)
@@ -602,10 +602,10 @@ Here are the methods of the :class:`Message` class:
 
       .. 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
+         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::
 
@@ -628,7 +628,7 @@ Here are the methods of the :class:`Message` class:
       .. doctest::
 
          >>> for part in msg.walk():
-         ...     print(part.get_content_maintype() == 'multipart'),
+         ...     print(part.get_content_maintype() == 'multipart',
          ...           part.is_multipart())
          True True
          False False
@@ -640,11 +640,11 @@ Here are the methods of the :class:`Message` class:
          >>> _structure(msg)
          multipart/report
              text/plain
-         message/delivery-status
-             text/plain
-             text/plain
-         message/rfc822
-             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
index 93c09ad..b8eb7c5 100644 (file)
@@ -202,12 +202,12 @@ have the same API as the :class:`Parser` and :class:`BytesParser` classes.
       reading the headers or not.  The default is ``False``, meaning it parses
       the entire contents of the file.
 
-   .. method:: parsebytes(bytes, headersonly=False)
+   .. method:: parsebytes(text, headersonly=False)
 
-      Similar to the :meth:`parse` method, except it takes a byte string object
-      instead of a file-like object.  Calling this method on a byte string is
-      exactly 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 :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`.
 
       Optional *headersonly* is as with the :meth:`parse` method.
 
@@ -233,7 +233,7 @@ in the top-level :mod:`email` package namespace.
 .. function:: message_from_bytes(s, _class=email.message.Message, *, \
                                  policy=policy.compat32)
 
-   Return a message object structure from a byte string.  This is exactly
+   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
    constructor.
@@ -250,7 +250,7 @@ in the top-level :mod:`email` package namespace.
    and *policy* are interpreted as with the :class:`~email.parser.Parser` class
    constructor.
 
-   .. versionchanged::
+   .. versionchanged:: 3.3
       Removed the *strict* argument.  Added the *policy* keyword.
 
 .. function:: message_from_binary_file(fp, _class=email.message.Message, *, \
index 47f3212..2a6047d 100644 (file)
@@ -63,16 +63,15 @@ file on disk and pass it to the system ``sendmail`` program on a Unix system:
 
 .. testsetup::
 
-   >>> from unittest import mock
-   >>> mocker = mock.patch('subprocess.Popen')
-   >>> m = mocker.start()
-   >>> proc = mock.MagicMock()
-   >>> m.return_value = proc
-   >>> proc.stdin.close.return_value = None
-   >>> mymsg = open('mymsg.txt', 'w')
-   >>> mymsg.write('To: abc@xyz.com\n\n')
-   17
-   >>> mymsg.flush()
+   from unittest import mock
+   mocker = mock.patch('subprocess.Popen')
+   m = mocker.start()
+   proc = mock.MagicMock()
+   m.return_value = proc
+   proc.stdin.close.return_value = None
+   mymsg = open('mymsg.txt', 'w')
+   mymsg.write('To: abc@xyz.com\n\n')
+   mymsg.flush()
 
 .. doctest::
 
@@ -88,12 +87,12 @@ file on disk and pass it to the system ``sendmail`` program on a Unix system:
    >>> p.stdin.close()
    >>> rc = p.wait()
 
-.. testsetup::
+.. testcleanup::
 
-   >>> mymsg.close()
-   >>> mocker.stop()
-   >>> import os
-   >>> os.remove('mymsg.txt')
+   mymsg.close()
+   mocker.stop()
+   import os
+   os.remove('mymsg.txt')
 
 Here we are telling :class:`~email.generator.BytesGenerator` to use the RFC
 correct line separator characters when creating the binary string to feed into
index 6aeeabc..c797f63 100644 (file)
@@ -96,7 +96,7 @@ Module API
    Bootstraps ``pip`` into the current or designated environment.
 
    *root* specifies an alternative root directory to install relative to.
-   If *root* is None, then installation uses the default install location
+   If *root* is ``None``, then installation uses the default install location
    for the current environment.
 
    *upgrade* indicates whether or not to upgrade an existing installation
index 60467b4..a3d5afc 100644 (file)
@@ -431,7 +431,7 @@ The solution is to specify the module name explicitly as follows::
     the source, pickling will be disabled.
 
 The new pickle protocol 4 also, in some circumstances, relies on
-:attr:`__qualname__` being set to the location where pickle will be able
+:attr:`~definition.__qualname__` being set to the location where pickle will be able
 to find the class.  For example, if the class was made available in class
 SomeData in the global scope::
 
index 85ac484..9fc9c7c 100644 (file)
@@ -74,7 +74,8 @@ patterns.
 
 .. function:: translate(pattern)
 
-   Return the shell-style *pattern* converted to a regular expression.
+   Return the shell-style *pattern* converted to a regular expression for
+   using with :func:`re.match`.
 
    Example:
 
index 233e11f..1e35f37 100644 (file)
@@ -57,7 +57,7 @@ The module defines the following items:
     >>> with FTP("ftp1.at.proftpd.org") as ftp:
     ...     ftp.login()
     ...     ftp.dir()
-    ...
+    ... # doctest: +SKIP
     '230 Anonymous login ok, restrictions apply.'
     dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
     dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
index c3563f3..2f14949 100644 (file)
@@ -304,7 +304,7 @@ are always available.  They are listed here in alphabetical order.
    :func:`dir` reports their attributes.
 
    If the object does not provide :meth:`__dir__`, the function tries its best to
-   gather information from the object's :attr:`__dict__` attribute, if defined, and
+   gather information from the object's :attr:`~object.__dict__` attribute, if defined, and
    from its type object.  The resulting list is not necessarily complete, and may
    be inaccurate when the object has a custom :func:`__getattr__`.
 
@@ -686,7 +686,7 @@ are always available.  They are listed here in alphabetical order.
    preceded by ``+`` or ``-`` (with no space in between) and surrounded by
    whitespace.  A base-n literal consists of the digits 0 to n-1, with ``a``
    to ``z`` (or ``A`` to ``Z``) having
-   values 10 to 35.  The default *base* is 10. The allowed values are 0 and 2-36.
+   values 10 to 35.  The default *base* is 10. The allowed values are 0 and 2--36.
    Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``,
    ``0o``/``0O``, or ``0x``/``0X``, as with integer literals in code.  Base 0
    means to interpret exactly as a code literal, so that the actual base is 2,
@@ -949,7 +949,7 @@ are always available.  They are listed here in alphabetical order.
    the list of supported encodings.
 
    *errors* is an optional string that specifies how encoding and decoding
-   errors are to be handled--this cannot be used in binary mode.
+   errors are to be handledthis cannot be used in binary mode.
    A variety of standard error handlers are available
    (listed under :ref:`error-handlers`), though any
    error handling name that has been registered with
@@ -1234,8 +1234,8 @@ are always available.  They are listed here in alphabetical order.
 .. function:: round(number[, ndigits])
 
    Return the floating point value *number* rounded to *ndigits* digits after
-   the decimal point.  If *ndigits* is omitted, it returns the nearest integer
-   to its input.  Delegates to ``number.__round__(ndigits)``.
+   the decimal point.  If *ndigits* is omitted or is ``None``, it returns the
+   nearest integer to its input.  Delegates to ``number.__round__(ndigits)``.
 
    For the built-in types supporting :func:`round`, values are rounded to the
    closest multiple of 10 to the power minus *ndigits*; if two multiples are
@@ -1446,7 +1446,7 @@ are always available.  They are listed here in alphabetical order.
 
    With three arguments, return a new type object.  This is essentially a
    dynamic form of the :keyword:`class` statement. The *name* string is the
-   class name and becomes the :attr:`~class.__name__` attribute; the *bases*
+   class name and becomes the :attr:`~definition.__name__` attribute; the *bases*
    tuple itemizes the base classes and becomes the :attr:`~class.__bases__`
    attribute; and the *dict* dictionary is the namespace containing definitions
    for class body and is copied to a standard dictionary to become the
@@ -1464,12 +1464,12 @@ are always available.  They are listed here in alphabetical order.
 .. function:: vars([object])
 
    Return the :attr:`~object.__dict__` attribute for a module, class, instance,
-   or any other object with a :attr:`__dict__` attribute.
+   or any other object with a :attr:`~object.__dict__` attribute.
 
-   Objects such as modules and instances have an updateable :attr:`__dict__`
+   Objects such as modules and instances have an updateable :attr:`~object.__dict__`
    attribute; however, other objects may have write restrictions on their
-   :attr:`__dict__` attributes (for example, classes use a
-   dictproxy to prevent direct dictionary updates).
+   :attr:`~object.__dict__` attributes (for example, classes use a
+   :class:`types.MappingProxyType` to prevent direct dictionary updates).
 
    Without an argument, :func:`vars` acts like :func:`locals`.  Note, the
    locals dictionary is only useful for reads since updates to the locals
index abdd66f..9a8defe 100644 (file)
@@ -52,11 +52,11 @@ The :mod:`functools` module defines the following functions:
    Since a dictionary is used to cache results, the positional and keyword
    arguments to the function must be hashable.
 
-   If *maxsize* is set to None, the LRU feature is disabled and the cache can
+   If *maxsize* is set to ``None``, the LRU feature is disabled and the cache can
    grow without bound.  The LRU feature performs best when *maxsize* is a
    power-of-two.
 
-   If *typed* is set to True, function arguments of different types will be
+   If *typed* is set to true, function arguments of different types will be
    cached separately.  For example, ``f(3)`` and ``f(3.0)`` will be treated
    as distinct calls with distinct results.
 
@@ -474,7 +474,7 @@ have three read-only attributes:
 
 :class:`partial` objects are like :class:`function` objects in that they are
 callable, weak referencable, and can have attributes.  There are some important
-differences.  For instance, the :attr:`__name__` and :attr:`__doc__` attributes
+differences.  For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes
 are not created automatically.  Also, :class:`partial` objects defined in
 classes behave like static methods and do not transform into bound methods
 during instance attribute look-up.
index 4af16a9..87d6824 100644 (file)
@@ -38,7 +38,7 @@ The :mod:`gc` module provides the following functions:
    Returns true if automatic collection is enabled.
 
 
-.. function:: collect(generations=2)
+.. function:: collect(generation=2)
 
    With no arguments, run a full collection.  The optional argument *generation*
    may be an integer specifying which generation to collect (from 0 to 2).  A
index ea439b5..3a87bf5 100644 (file)
@@ -621,7 +621,7 @@ In this case, you are marking translatable strings with the function
 However, you will need to teach your message extraction program to
 look for translatable strings marked with :func:`N_`. :program:`xgettext`,
 :program:`pygettext`, ``pybabel extract``, and :program:`xpot` all
-support this through the use of the :option:`-k` command-line switch.
+support this through the use of the :option:`!-k` command-line switch.
 The choice of :func:`N_` here is totally arbitrary; it could have just
 as easily been :func:`MarkThisStringForTranslation`.
 
index 30be335..a2e96ca 100644 (file)
    single: message digest, MD5
    single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512
 
+.. testsetup::
+
+   import hashlib
+
+
 --------------
 
 This module implements a common interface to many different secure hash and
index bb44866..adbf78a 100644 (file)
@@ -111,7 +111,7 @@ This module also provides the following helper function:
 
       If *a* and *b* are of different lengths, or if an error occurs,
       a timing attack could theoretically reveal information about the
-      types and lengths of *a* and *b*--but not their values.
+      types and lengths of *a* and *b*but not their values.
 
 
    .. versionadded:: 3.3
index 16abb40..ac844a6 100644 (file)
@@ -61,7 +61,9 @@ as they are encountered::
    parser.feed('<html><head><title>Test</title></head>'
                '<body><h1>Parse me!</h1></body></html>')
 
-The output will then be::
+The output will then be:
+
+.. code-block:: none
 
    Encountered a start tag: html
    Encountered a start tag: head
index 8954648..e1acf92 100644 (file)
@@ -20,7 +20,7 @@ HTTPS protocols.  It is normally not used directly --- the module
 
 .. seealso::
 
-    The `Requests package <https://requests.readthedocs.org/>`_
+    The `Requests package <http://docs.python-requests.org/>`_
     is recommended for a higher-level HTTP client interface.
 
 .. note::
@@ -31,8 +31,7 @@ HTTPS protocols.  It is normally not used directly --- the module
 The module provides the following classes:
 
 
-.. class:: HTTPConnection(host, port=None[, timeout], \
-                          source_address=None)
+.. class:: HTTPConnection(host, port=None[, timeout], source_address=None)
 
    An :class:`HTTPConnection` instance represents one transaction with an HTTP
    server.  It should be instantiated passing it a host and optional port
@@ -196,7 +195,6 @@ The constants defined in this module are:
 
    The default port for the HTTP protocol (always ``80``).
 
-
 .. data:: HTTPS_PORT
 
    The default port for the HTTPS protocol (always ``443``).
@@ -227,12 +225,12 @@ HTTPConnection Objects
    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-8851-1, the default for HTTP.  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-8851-1 unless the ``mode`` attribute contains the substring ``b``,
+   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.
@@ -318,14 +316,15 @@ As an alternative to using the :meth:`request` method described above, you can
 also send your request step by step, by using the four functions below.
 
 
-.. method:: HTTPConnection.putrequest(request, selector, skip_host=False, skip_accept_encoding=False)
+.. method:: HTTPConnection.putrequest(method, url, skip_host=False, \
+                                      skip_accept_encoding=False)
 
-   This should be the first call after the connection to the server has been made.
-   It sends a line to the server consisting of the *request* string, the *selector*
-   string, and the HTTP version (``HTTP/1.1``).  To disable automatic sending of
-   ``Host:`` or ``Accept-Encoding:`` headers (for example to accept additional
-   content encodings), specify *skip_host* or *skip_accept_encoding* with non-False
-   values.
+   This should be the first call after the connection to the server has been
+   made. It sends a line to the server consisting of the *method* string,
+   the *url* string, and the HTTP version (``HTTP/1.1``).  To disable automatic
+   sending of ``Host:`` or ``Accept-Encoding:`` headers (for example to accept
+   additional content encodings), specify *skip_host* or *skip_accept_encoding*
+   with non-False values.
 
 
 .. method:: HTTPConnection.putheader(header, argument[, ...])
@@ -384,7 +383,6 @@ statement.
    return all of the values joined by ', '.  If 'default' is any iterable other
    than a single string, its elements are similarly returned joined by commas.
 
-
 .. method:: HTTPResponse.getheaders()
 
    Return a list of (header, value) tuples.
@@ -399,22 +397,18 @@ statement.
    headers.  :class:`http.client.HTTPMessage` is a subclass of
    :class:`email.message.Message`.
 
-
 .. attribute:: HTTPResponse.version
 
    HTTP protocol version used by server.  10 for HTTP/1.0, 11 for HTTP/1.1.
 
-
 .. attribute:: HTTPResponse.status
 
    Status code returned by server.
 
-
 .. attribute:: HTTPResponse.reason
 
    Reason phrase returned by server.
 
-
 .. attribute:: HTTPResponse.debuglevel
 
    A debugging hook.  If :attr:`debuglevel` is greater than zero, messages
index 16c4fac..ae7fb97 100644 (file)
@@ -277,7 +277,7 @@ of which this module provides three different variants:
 
    .. method:: date_time_string(timestamp=None)
 
-      Returns the date and time given by *timestamp* (which must be None or in
+      Returns the date and time given by *timestamp* (which must be ``None`` or in
       the format returned by :func:`time.time`), formatted for a message
       header. If *timestamp* is omitted, it uses the current date and time.
 
index 9ca92ce..a629bc5 100644 (file)
@@ -226,6 +226,9 @@ View Last Restart
 Restart Shell
   Restart the shell to clean the environment.
 
+Interrupt Execution
+  Stop a running program.
+
 Debug menu (Shell window only)
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
@@ -524,14 +527,14 @@ functions to be used from IDLE's Python shell.
 Command line usage
 ^^^^^^^^^^^^^^^^^^
 
-::
+.. code-block:: none
 
    idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...
 
    -c command  run command in the shell window
    -d          enable debugger and open shell window
    -e          open editor window
-   -h          print help message with legal combinatios and exit
+   -h          print help message with legal combinations and exit
    -i          open shell window
    -r file     run file in shell window
    -s          run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
@@ -562,11 +565,13 @@ objects that get input from and send output to the Shell window.
 When this window has the focus, it controls the keyboard and screen.
 This is normally transparent, but functions that directly access the keyboard
 and screen will not work.  If ``sys`` is reset with ``importlib.reload(sys)``,
-IDLE's changes are lost and things li ke ``input``, ``raw_input``, and
+IDLE's changes are lost and things like ``input``, ``raw_input``, and
 ``print`` will not work correctly.
 
 With IDLE's Shell, one enters, edits, and recalls complete statements.
-Some consoles only work with a single physical line at a time.
+Some consoles only work with a single physical line at a time.  IDLE uses
+``exec`` to run each statement.  As a result, ``'__builtins__'`` is always
+defined for each statement.
 
 Running without a subprocess
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
index c25e7d8..771ca43 100644 (file)
@@ -120,7 +120,7 @@ The following utility functions are defined:
 
    Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local
    time.  The return value is a :class:`time.struct_time` tuple or
-   None if the string has wrong format.
+   ``None`` if the string has wrong format.
 
 .. function:: Int2AP(num)
 
index 3302446..526c9f3 100644 (file)
@@ -1,5 +1,5 @@
-:mod:`importlib` -- The implementation of :keyword:`import`
-===========================================================
+:mod:`importlib` --- The implementation of :keyword:`import`
+============================================================
 
 .. module:: importlib
    :synopsis: The implementation of the import machinery.
@@ -118,7 +118,7 @@ Functions
    :exc:`ValueError` is raised). Otherwise a search using :attr:`sys.meta_path`
    is done. ``None`` is returned if no loader is found.
 
-   A dotted name does not have its parent's implicitly imported as that requires
+   A dotted name does not have its parents implicitly imported as that requires
    loading them and that may not be desired. To properly import a submodule you
    will need to import all parent packages of the submodule and use the correct
    argument to *path*.
@@ -211,6 +211,11 @@ Functions
 .. module:: importlib.abc
     :synopsis: Abstract base classes related to import
 
+**Source code:** :source:`Lib/importlib/abc.py`
+
+--------------
+
+
 The :mod:`importlib.abc` module contains all of the core abstract base classes
 used by :keyword:`import`. Some subclasses of the core abstract base classes
 are also provided to help in implementing the core ABCs.
@@ -624,7 +629,7 @@ ABC hierarchy::
     .. method:: path_stats(path)
 
         Optional abstract method which returns a :class:`dict` containing
-        metadata about the specifed path.  Supported dictionary keys are:
+        metadata about the specified path.  Supported dictionary keys are:
 
         - ``'mtime'`` (mandatory): an integer or floating-point number
           representing the modification time of the source code;
@@ -700,6 +705,10 @@ ABC hierarchy::
 .. module:: importlib.machinery
     :synopsis: Importers and path hooks
 
+**Source code:** :source:`Lib/importlib/machinery.py`
+
+--------------
+
 This module contains the various objects that help :keyword:`import`
 find and load modules.
 
@@ -1035,7 +1044,7 @@ find and load modules.
    (``__loader__``)
 
    The loader to use for loading.  For namespace packages this should be
-   set to None.
+   set to ``None``.
 
    .. attribute:: origin
 
@@ -1043,33 +1052,33 @@ find and load modules.
 
    Name of the place from which the module is loaded, e.g. "builtin" for
    built-in modules and the filename for modules loaded from source.
-   Normally "origin" should be set, but it may be None (the default)
+   Normally "origin" should be set, but it may be ``None`` (the default)
    which indicates it is unspecified.
 
    .. attribute:: submodule_search_locations
 
    (``__path__``)
 
-   List of strings for where to find submodules, if a package (None
+   List of strings for where to find submodules, if a package (``None``
    otherwise).
 
    .. attribute:: loader_state
 
    Container of extra module-specific data for use during loading (or
-   None).
+   ``None``).
 
    .. attribute:: cached
 
    (``__cached__``)
 
-   String for where the compiled module should be stored (or None).
+   String for where the compiled module should be stored (or ``None``).
 
    .. attribute:: parent
 
    (``__package__``)
 
    (Read-only) Fully-qualified name of the package to which the module
-   belongs as a submodule (or None).
+   belongs as a submodule (or ``None``).
 
    .. attribute:: has_location
 
@@ -1082,6 +1091,11 @@ find and load modules.
 .. module:: importlib.util
     :synopsis: Utility code for importers
 
+
+**Source code:** :source:`Lib/importlib/util.py`
+
+--------------
+
 This module contains the various objects that help in the construction of
 an :term:`importer`.
 
index b28d0f9..62a3988 100644 (file)
@@ -152,9 +152,9 @@ attributes:
 |           | co_firstlineno  | number of first line in   |
 |           |                 | Python source code        |
 +-----------+-----------------+---------------------------+
-|           | co_flags        | bitmap: 1=optimized ``|`` |
-|           |                 | 2=newlocals ``|`` 4=\*arg |
-|           |                 | ``|`` 8=\*\*arg           |
+|           | co_flags        | bitmap of ``CO_*`` flags, |
+|           |                 | read more :ref:`here      |
+|           |                 | <inspect-module-co-flags>`|
 +-----------+-----------------+---------------------------+
 |           | co_lnotab       | encoded mapping of line   |
 |           |                 | numbers to bytecode       |
@@ -374,8 +374,9 @@ attributes:
    are true.
 
    This, for example, is true of ``int.__add__``.  An object passing this test
-   has a :attr:`__get__` attribute but not a :attr:`__set__` attribute, but
-   beyond that the set of attributes varies.  :attr:`__name__` is usually
+   has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
+   method, but beyond that the set of attributes varies.  A
+   :attr:`~definition.__name__` attribute is usually
    sensible, and :attr:`__doc__` often is.
 
    Methods implemented via descriptors that also pass one of the other tests
@@ -388,11 +389,11 @@ attributes:
 
    Return true if the object is a data descriptor.
 
-   Data descriptors have both a :attr:`__get__` and a :attr:`__set__` attribute.
+   Data descriptors have both a :attr:`~object.__get__` and a :attr:`~object.__set__` method.
    Examples are properties (defined in Python), getsets, and members.  The
    latter two are defined in C and there are more specific tests available for
    those types, which is robust across Python implementations.  Typically, data
-   descriptors will also have :attr:`__name__` and :attr:`__doc__` attributes
+   descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
    (properties, getsets, and members have both of these attributes), but this is
    not guaranteed.
 
@@ -1231,6 +1232,61 @@ updated as expected:
    .. versionadded:: 3.5
 
 
+.. _inspect-module-co-flags:
+
+Code Objects Bit Flags
+----------------------
+
+Python code objects have a ``co_flags`` attribute, which is a bitmap of
+the following flags:
+
+.. data:: CO_NEWLOCALS
+
+   If set, a new dict will be created for the frame's ``f_locals`` when
+   the code object is executed.
+
+.. data:: CO_VARARGS
+
+   The code object has a variable positional parameter (``*args``-like).
+
+.. data:: CO_VARKEYWORDS
+
+   The code object has a variable keyword parameter (``**kwargs``-like).
+
+.. data:: CO_GENERATOR
+
+   The flag is set when the code object is a generator function, i.e.
+   a generator object is returned when the code object is executed.
+
+.. data:: CO_NOFREE
+
+   The flag is set if there are no free or cell variables.
+
+.. 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.
+
+   .. 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.
+
+   .. versionadded:: 3.5
+
+.. note::
+   The flags are specific to CPython, and may not be defined in other
+   Python implementations.  Furthermore, the flags are an implementation
+   detail, and can be removed or deprecated in future Python releases.
+   It's recommended to use public APIs from the :mod:`inspect` module
+   for any introspection needs.
+
+
+
 .. _inspect-module-cli:
 
 Command Line Interface
index 23df18f..4da6e09 100644 (file)
@@ -537,7 +537,7 @@ Raw File I/O
    The *name* can be one of two things:
 
    * a character string or :class:`bytes` object representing the path to the
-     file which will be opened. In this case closefd must be True (the default)
+     file which will be opened. In this case closefd must be ``True`` (the default)
      otherwise an error will be raised.
    * an integer representing the number of an existing OS-level file descriptor
      to which the resulting :class:`FileIO` object will give access. When the
index 23526b6..50fb778 100644 (file)
@@ -24,6 +24,10 @@ This is the full module API reference—for an overview and introduction, see
 
 .. versionadded:: 3.3
 
+.. testsetup::
+   >>> import ipaddress
+   >>> from ipaddress import (ip_network, IPv4Address, IPv4Interface,
+   ...                        IPv4Network)
 
 Convenience factory functions
 -----------------------------
@@ -39,13 +43,6 @@ IP addresses, networks and interfaces:
    A :exc:`ValueError` is raised if *address* does not represent a valid IPv4
    or IPv6 address.
 
-.. testsetup::
-   >>> import ipaddress
-   >>> from ipaddress import (ip_network, IPv4Address, IPv4Interface,
-   ...                        IPv4Network)
-
-::
-
    >>> ipaddress.ip_address('192.168.0.1')
    IPv4Address('192.168.0.1')
    >>> ipaddress.ip_address('2001:db8::')
@@ -102,7 +99,7 @@ write code that handles both IP versions correctly.
    The following constitutes a valid IPv4 address:
 
    1. A string in decimal-dot notation, consisting of four decimal integers in
-      the inclusive range 0-255, separated by dots (e.g. ``192.168.0.1``). Each
+      the inclusive range 0--255, separated by dots (e.g. ``192.168.0.1``). Each
       integer represents an octet (byte) in the address. Leading zeroes are
       tolerated only for values less than 8 (as there is no ambiguity
       between the decimal and octal interpretations of such strings).
@@ -159,7 +156,7 @@ write code that handles both IP versions correctly.
       This is the name that could be used for performing a PTR lookup, not the
       resolved hostname itself.
 
-   .. versionadded:: 3.5
+      .. versionadded:: 3.5
 
    .. attribute:: is_multicast
 
index 174e734..f487535 100644 (file)
@@ -102,7 +102,7 @@ Extending :class:`JSONEncoder`::
 
 .. highlight:: bash
 
-Using json.tool from the shell to validate and pretty-print::
+Using :mod:`json.tool` from the shell to validate and pretty-print::
 
     $ echo '{"json":"obj"}' | python -m json.tool
     {
@@ -135,7 +135,7 @@ Basic Usage
    :term:`file-like object`) using this :ref:`conversion table
    <py-to-json-table>`.
 
-   If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not
+   If *skipkeys* is true (default: ``False``), then dict keys that are not
    of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`,
    ``None``) will be skipped instead of raising a :exc:`TypeError`.
 
@@ -143,18 +143,19 @@ Basic Usage
    :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str`
    input.
 
-   If *ensure_ascii* is ``True`` (the default), the output is guaranteed to
+   If *ensure_ascii* is true (the default), the output is guaranteed to
    have all incoming non-ASCII characters escaped.  If *ensure_ascii* is
-   ``False``, these characters will be output as-is.
+   false, these characters will be output as-is.
 
-   If *check_circular* is ``False`` (default: ``True``), then the circular
+   If *check_circular* is false (default: ``True``), then the circular
    reference check for container types will be skipped and a circular reference
    will result in an :exc:`OverflowError` (or worse).
 
-   If *allow_nan* is ``False`` (default: ``True``), then it will be a
+   If *allow_nan* is false (default: ``True``), then it will be a
    :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
-   ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of
-   using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
+   ``inf``, ``-inf``) in strict compliance of the JSON specification.
+   If *allow_nan* is true, their JavaScript equivalents (``NaN``,
+   ``Infinity``, ``-Infinity``) will be used.
 
    If *indent* is a non-negative integer or string, then JSON array elements and
    object members will be pretty-printed with that indent level.  An indent level
@@ -174,10 +175,12 @@ Basic Usage
    .. versionchanged:: 3.4
       Use ``(',', ': ')`` as default if *indent* is not ``None``.
 
-   *default(obj)* is a function that should return a serializable version of
-   *obj* or raise :exc:`TypeError`.  The default simply raises :exc:`TypeError`.
+   If specified, *default* should be a function that gets called for objects that
+   can't otherwise be serialized.  It should return a JSON encodable version of
+   the object or raise a :exc:`TypeError`.  If not specified, :exc:`TypeError`
+   is raised.
 
-   If *sort_keys* is ``True`` (default: ``False``), then the output of
+   If *sort_keys* is true (default: ``False``), then the output of
    dictionaries will be sorted by key.
 
    To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
@@ -329,13 +332,13 @@ Encoders and Decoders
    (e.g. :class:`float`).
 
    *parse_constant*, if specified, will be called with one of the following
-   strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``, ``'null'``, ``'true'``,
-   ``'false'``.  This can be used to raise an exception if invalid JSON numbers
+   strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
+   This can be used to raise an exception if invalid JSON numbers
    are encountered.
 
-   If *strict* is ``False`` (``True`` is the default), then control characters
+   If *strict* is false (``True`` is the default), then control characters
    will be allowed inside strings.  Control characters in this context are
-   those with character codes in the 0-31 range, including ``'\t'`` (tab),
+   those with character codes in the 0--31 range, including ``'\t'`` (tab),
    ``'\n'``, ``'\r'`` and ``'\0'``.
 
    If the data being deserialized is not a valid JSON document, a
@@ -393,26 +396,27 @@ Encoders and Decoders
    for ``o`` if possible, otherwise it should call the superclass implementation
    (to raise :exc:`TypeError`).
 
-   If *skipkeys* is ``False`` (the default), then it is a :exc:`TypeError` to
-   attempt encoding of keys that are not str, int, float or None.  If
-   *skipkeys* is ``True``, such items are simply skipped.
+   If *skipkeys* is false (the default), then it is a :exc:`TypeError` to
+   attempt encoding of keys that are not :class:`str`, :class:`int`,
+   :class:`float` or ``None``.  If *skipkeys* is true, such items are simply
+   skipped.
 
-   If *ensure_ascii* is ``True`` (the default), the output is guaranteed to
+   If *ensure_ascii* is true (the default), the output is guaranteed to
    have all incoming non-ASCII characters escaped.  If *ensure_ascii* is
-   ``False``, these characters will be output as-is.
+   false, these characters will be output as-is.
 
-   If *check_circular* is ``True`` (the default), then lists, dicts, and custom
+   If *check_circular* is true (the default), then lists, dicts, and custom
    encoded objects will be checked for circular references during encoding to
    prevent an infinite recursion (which would cause an :exc:`OverflowError`).
    Otherwise, no such check takes place.
 
-   If *allow_nan* is ``True`` (the default), then ``NaN``, ``Infinity``, and
+   If *allow_nan* is true (the default), then ``NaN``, ``Infinity``, and
    ``-Infinity`` will be encoded as such.  This behavior is not JSON
    specification compliant, but is consistent with most JavaScript based
    encoders and decoders.  Otherwise, it will be a :exc:`ValueError` to encode
    such floats.
 
-   If *sort_keys* is ``True`` (default ``False``), then the output of dictionaries
+   If *sort_keys* is true (default: ``False``), then the output of dictionaries
    will be sorted by key; this is useful for regression tests to ensure that
    JSON serializations can be compared on a day-to-day basis.
 
@@ -434,9 +438,10 @@ Encoders and Decoders
    .. versionchanged:: 3.4
       Use ``(',', ': ')`` as default if *indent* is not ``None``.
 
-   If specified, *default* is a function that gets called for objects that can't
-   otherwise be serialized.  It should return a JSON encodable version of the
-   object or raise a :exc:`TypeError`.
+   If specified, *default* should be a function that gets called for objects that
+   can't otherwise be serialized.  It should return a JSON encodable version of
+   the object or raise a :exc:`TypeError`.  If not specified, :exc:`TypeError`
+   is raised.
 
 
    .. method:: default(o)
@@ -629,13 +634,19 @@ when serializing instances of "exotic" numerical types such as
 :class:`decimal.Decimal`.
 
 .. highlight:: bash
-.. module:: json.tool
 
 .. _json-commandline:
 
 Command Line Interface
 ----------------------
 
+.. module:: json.tool
+    :synopsis: A command line to validate and pretty-print JSON.
+
+**Source code:** :source:`Lib/json/tool.py`
+
+--------------
+
 The :mod:`json.tool` module provides a simple command line interface to validate
 and pretty-print JSON objects.
 
index ae3de9f..34fcac5 100644 (file)
@@ -51,7 +51,7 @@ The :mod:`linecache` module defines the following functions:
 .. function:: lazycache(filename, module_globals)
 
    Capture enough detail about a non-file-based module to permit getting its
-   lines later via :func:`getline` even if *module_globals* is None in the later
+   lines later via :func:`getline` even if *module_globals* is ``None`` in the later
    call. This avoids doing I/O until a line is actually needed, without having
    to carry the module globals around indefinitely.
 
index e196724..a68a890 100644 (file)
@@ -126,10 +126,10 @@ in :mod:`logging` itself) and defining handlers which are declared either in
    Starts up a socket server on the specified port, and listens for new
    configurations. If no port is specified, the module's default
    :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
-   sent as a file suitable for processing by :func:`fileConfig`. Returns a
-   :class:`~threading.Thread` instance on which you can call
-   :meth:`~threading.Thread.start` to start the server, and which you can
-   :meth:`~threading.Thread.join` when appropriate. To stop the server,
+   sent as a file suitable for processing by :func:`dictConfig` or
+   :func:`fileConfig`. Returns a :class:`~threading.Thread` instance on which
+   you can call :meth:`~threading.Thread.start` to start the server, and which
+   you can :meth:`~threading.Thread.join` when appropriate. To stop the server,
    call :func:`stopListening`.
 
    The ``verify`` argument, if specified, should be a callable which should
@@ -138,13 +138,13 @@ in :mod:`logging` itself) and defining handlers which are declared either in
    across the socket, such that the ``verify`` callable can perform
    signature verification and/or decryption. The ``verify`` callable is called
    with a single argument - the bytes received across the socket - and should
-   return the bytes to be processed, or None to indicate that the bytes should
+   return the bytes to be processed, or ``None`` to indicate that the bytes should
    be discarded. The returned bytes could be the same as the passed in bytes
    (e.g. when only verification is done), or they could be completely different
    (perhaps if decryption were performed).
 
    To send a configuration to the socket, read in the configuration file and
-   send it to the socket as a string of bytes preceded by a four-byte length
+   send it to the socket as a sequence of bytes preceded by a four-byte length
    string packed in binary using ``struct.pack('>L', n)``.
 
    .. note::
@@ -165,9 +165,18 @@ in :mod:`logging` itself) and defining handlers which are declared either in
       ``verify`` argument to :func:`listen` to prevent unrecognised
       configurations from being applied.
 
-   .. versionchanged:: 3.4.
+   .. versionchanged:: 3.4
       The ``verify`` argument was added.
 
+   .. note::
+
+      If you want to send configurations to the listener which don't
+      disable existing loggers, you will need to use a JSON format for
+      the configuration, which will use :func:`dictConfig` for configuration.
+      This method allows you to specify ``disable_existing_loggers`` as
+      ``False`` in the configuration you send.
+
+
 .. function:: stopListening()
 
    Stops the listening server which was created with a call to :func:`listen`.
@@ -243,7 +252,9 @@ otherwise, the context is used to determine what to instantiate.
     handler.
 
   All *other* keys are passed through as keyword arguments to the
-  handler's constructor.  For example, given the snippet::
+  handler's constructor.  For example, given the snippet:
+
+  .. code-block:: yaml
 
       handlers:
         console:
@@ -352,7 +363,9 @@ it unambiguously, and then using the id in the source object's
 configuration to indicate that a connection exists between the source
 and the destination object with that id.
 
-So, for example, consider the following YAML snippet::
+So, for example, consider the following YAML snippet:
+
+.. code-block:: yaml
 
     formatters:
       brief:
@@ -409,7 +422,9 @@ to provide a 'factory' - a callable which is called with a
 configuration dictionary and which returns the instantiated object.
 This is signalled by an absolute import path to the factory being
 made available under the special key ``'()'``.  Here's a concrete
-example::
+example:
+
+.. code-block:: yaml
 
     formatters:
       brief:
@@ -626,7 +641,9 @@ configuration must be specified in a section called ``[logger_root]``.
    :func:`dictConfig`, so it's worth considering transitioning to this newer
    API when it's convenient to do so.
 
-Examples of these sections in the file are given below. ::
+Examples of these sections in the file are given below.
+
+.. code-block:: ini
 
    [loggers]
    keys=root,log02,log03,log04,log05,log06,log07
@@ -638,7 +655,9 @@ Examples of these sections in the file are given below. ::
    keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
 
 The root logger must specify a level and a list of handlers. An example of a
-root logger section is given below. ::
+root logger section is given below.
+
+.. code-block:: ini
 
    [logger_root]
    level=NOTSET
@@ -655,7 +674,9 @@ appear in the ``[handlers]`` section. These names must appear in the
 file.
 
 For loggers other than the root logger, some additional information is required.
-This is illustrated by the following example. ::
+This is illustrated by the following example.
+
+.. code-block:: ini
 
    [logger_parser]
    level=DEBUG
@@ -673,7 +694,8 @@ indicate that messages are **not** propagated to handlers up the hierarchy. The
 say the name used by the application to get the logger.
 
 Sections which specify handler configuration are exemplified by the following.
-::
+
+.. code-block:: ini
 
    [handler_hand01]
    class=StreamHandler
@@ -693,7 +715,9 @@ a corresponding section in the configuration file.
 The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
 package's namespace, is the list of arguments to the constructor for the handler
 class. Refer to the constructors for the relevant handlers, or to the examples
-below, to see how typical entries are constructed. ::
+below, to see how typical entries are constructed.
+
+.. code-block:: ini
 
    [handler_hand02]
    class=FileHandler
@@ -744,7 +768,9 @@ below, to see how typical entries are constructed. ::
    formatter=form09
    args=('localhost:9022', '/log', 'GET')
 
-Sections which specify formatter configuration are typified by the following. ::
+Sections which specify formatter configuration are typified by the following.
+
+.. code-block:: ini
 
    [formatter_form01]
    format=F1 %(asctime)s %(levelname)s %(message)s
@@ -780,5 +806,3 @@ condensed format.
 
    Module :mod:`logging.handlers`
       Useful handlers included with the logging module.
-
-
index 855adab..0c02d3d 100644 (file)
@@ -80,7 +80,7 @@ sends logging output to a disk file.  It inherits the output functionality from
 
    Returns a new instance of the :class:`FileHandler` class. The specified file is
    opened and used as the stream for logging. If *mode* is not specified,
-   :const:`'a'` is used.  If *encoding* is not *None*, it is used to open the file
+   :const:`'a'` is used.  If *encoding* is not ``None``, it is used to open the file
    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.
 
@@ -152,11 +152,11 @@ exclusive locks - and so there is no need for such a handler. Furthermore,
 for this value.
 
 
-.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
+.. class:: WatchedFileHandler(filename, mode='a', encoding=None, delay=False)
 
    Returns a new instance of the :class:`WatchedFileHandler` class. The specified
    file is opened and used as the stream for logging. If *mode* is not specified,
-   :const:`'a'` is used.  If *encoding* is not *None*, it is used to open the file
+   :const:`'a'` is used.  If *encoding* is not ``None``, it is used to open the file
    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.
 
@@ -257,11 +257,11 @@ The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
 module, supports rotation of disk log files.
 
 
-.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
+.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False)
 
    Returns a new instance of the :class:`RotatingFileHandler` class. The specified
    file is opened and used as the stream for logging. If *mode* is not specified,
-   ``'a'`` is used.  If *encoding* is not *None*, it is used to open the file
+   ``'a'`` is used.  If *encoding* is not ``None``, it is used to open the file
    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.
 
index 72da385..6098878 100644 (file)
@@ -296,7 +296,7 @@ is the module's name in the Python package namespace.
 
    Finds the caller's source filename and line number. Returns the filename, line
    number, function name and stack information as a 4-element tuple. The stack
-   information is returned as *None* unless *stack_info* is *True*.
+   information is returned as ``None`` unless *stack_info* is ``True``.
 
 
 .. method:: Logger.handle(record)
@@ -318,7 +318,7 @@ is the module's name in the Python package namespace.
    looking for handlers in this logger and its parents in the logger hierarchy.
    Returns ``True`` if a handler was found, else ``False``. The method stops searching
    up the hierarchy whenever a logger with the 'propagate' attribute set to
-   False is found - that will be the last logger which is checked for the
+   false is found - that will be the last logger which is checked for the
    existence of handlers.
 
    .. versionadded:: 3.2
@@ -561,7 +561,7 @@ The useful mapping keys in a :class:`LogRecord` are given in the section on
          handled by a strptime format string (``'%Y-%m-%d %H:%M:%S'``), and the
          part after the comma is a millisecond value. Because strptime does not
          have a format placeholder for milliseconds, the millisecond value is
-         appended using another format string, ``'%s,%03d'``  and both of these
+         appended using another format string, ``'%s,%03d'`` --- and both of these
          format strings have been hardcoded into this method. With the change,
          these strings are defined as class-level attributes which can be
          overridden at the instance level when desired. The names of the
@@ -672,7 +672,7 @@ wire).
    :param args: Variable data to merge into the *msg* argument to obtain the
                 event description.
    :param exc_info: An exception tuple with the current exception information,
-                    or *None* if no exception information is available.
+                    or ``None`` if no exception information is available.
    :param func: The name of the function or method from which the logging call
                 was invoked.
    :param sinfo: A text string representing stack information from the base of
@@ -754,7 +754,7 @@ the options available to you.
 |                |                         | (as returned by :func:`time.time`).           |
 +----------------+-------------------------+-----------------------------------------------+
 | exc_info       | You shouldn't need to   | Exception tuple (à la ``sys.exc_info``) or,   |
-|                | format this yourself.   | if no exception has occurred, *None*.         |
+|                | format this yourself.   | if no exception has occurred, ``None``.       |
 +----------------+-------------------------+-----------------------------------------------+
 | filename       | ``%(filename)s``        | Filename portion of ``pathname``.             |
 +----------------+-------------------------+-----------------------------------------------+
@@ -1187,7 +1187,7 @@ functions.
       :lno: The line number in the file where the logging call was made.
       :msg: The logging message.
       :args: The arguments for the logging message.
-      :exc_info: An exception tuple, or None.
+      :exc_info: An exception tuple, or ``None``.
       :func: The name of the function or method which invoked the logging
              call.
       :sinfo: A stack traceback such as is provided by
index f99c495..61b3ba3 100644 (file)
@@ -362,10 +362,9 @@ entries in the dictionary representing the filter):
      select automatically based on other filter options.
 
 The delta filter stores the differences between bytes, producing more repetitive
-input for the compressor in certain circumstances. It only supports a single
-The delta filter supports only one option, ``dist``. This indicates the distance
-between bytes to be subtracted. The default is 1, i.e. take the differences
-between adjacent bytes.
+input for the compressor in certain circumstances. It supports one option,
+``dist``. This indicates the distance between bytes to be subtracted. The
+default is 1, i.e. take the differences between adjacent bytes.
 
 The BCJ filters are intended to be applied to machine code. They convert
 relative branches, calls and jumps in the code to use absolute addressing, with
index 8f53833..2f2945f 100644 (file)
@@ -14,7 +14,7 @@ byte by doing ``obj[index] = 97``, or change a subsequence by assigning to a
 slice: ``obj[i1:i2] = b'...'``.  You can also read and write data starting at
 the current file position, and :meth:`seek` through the file to different positions.
 
-A memory-mapped file is created by the :class:`mmap` constructor, which is
+A memory-mapped file is created by the :class:`~mmap.mmap` constructor, which is
 different on Unix and on Windows.  In either case you must provide a file
 descriptor for a file opened for update. If you wish to map an existing Python
 file object, use its :meth:`fileno` method to obtain the correct value for the
@@ -70,7 +70,7 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
    **(Unix version)** Maps *length* bytes from the file specified by the file
    descriptor *fileno*, and returns a mmap object.  If *length* is ``0``, the
    maximum length of the map will be the current size of the file when
-   :class:`mmap` is called.
+   :class:`~mmap.mmap` is called.
 
    *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
    private copy-on-write mapping, so changes to the contents of the mmap
@@ -97,7 +97,7 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
    by the descriptor *fileno* is internally automatically synchronized
    with physical backing store on Mac OS X and OpenVMS.
 
-   This example shows a simple way of using :class:`mmap`::
+   This example shows a simple way of using :class:`~mmap.mmap`::
 
       import mmap
 
@@ -122,7 +122,7 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
           mm.close()
 
 
-   :class:`mmap` can also be used as a context manager in a :keyword:`with`
+   :class:`~mmap.mmap` can also be used as a context manager in a :keyword:`with`
    statement.::
 
       import mmap
@@ -204,13 +204,13 @@ To map anonymous memory, -1 should be passed as the fileno along with the length
    .. method:: read([n])
 
       Return a :class:`bytes` containing up to *n* bytes starting from the
-      current file position. If the argument is omitted, *None* or negative,
+      current file position. If the argument is omitted, ``None`` or negative,
       return all bytes from the current file position to the end of the
       mapping. The file position is updated to point after the bytes that were
       returned.
 
       .. versionchanged:: 3.3
-         Argument can be omitted or *None*.
+         Argument can be omitted or ``None``.
 
    .. method:: read_byte()
 
index b334eeb..bd34ffb 100644 (file)
@@ -1,5 +1,5 @@
-:mod:`msvcrt` -- Useful routines from the MS VC++ runtime
-=========================================================
+:mod:`msvcrt` --- Useful routines from the MS VC++ runtime
+==========================================================
 
 .. module:: msvcrt
    :platform: Windows
index c5c092c..d45bc20 100644 (file)
@@ -496,6 +496,9 @@ The :mod:`multiprocessing` package mostly replicates the API of the
       If the optional argument *timeout* is ``None`` (the default), the method
       blocks until the process whose :meth:`join` method is called terminates.
       If *timeout* is a positive number, it blocks at most *timeout* seconds.
+      Note that the method returns ``None`` if its process terminates or if the
+      method times out.  Check the process's :attr:`exitcode` to determine if
+      it terminated.
 
       A process can be joined many times.
 
@@ -939,7 +942,7 @@ Miscellaneous
    Return a context object which has the same attributes as the
    :mod:`multiprocessing` module.
 
-   If *method* is *None* then the default context is returned.
+   If *method* is ``None`` then the default context is returned.
    Otherwise *method* should be ``'fork'``, ``'spawn'``,
    ``'forkserver'``.  :exc:`ValueError` is raised if the specified
    start method is not available.
@@ -953,10 +956,10 @@ Miscellaneous
    If the start method has not been fixed and *allow_none* is false,
    then the start method is fixed to the default and the name is
    returned.  If the start method has not been fixed and *allow_none*
-   is true then *None* is returned.
+   is true then ``None`` is returned.
 
    The return value can be ``'fork'``, ``'spawn'``, ``'forkserver'``
-   or *None*.  ``'fork'`` is the default on Unix, while ``'spawn'`` is
+   or ``None``.  ``'fork'`` is the default on Unix, while ``'spawn'`` is
    the default on Windows.
 
    .. versionadded:: 3.4
@@ -1010,7 +1013,7 @@ Connection objects are usually created using :func:`Pipe` -- see also
       using :meth:`recv`.
 
       The object must be picklable.  Very large pickles (approximately 32 MB+,
-      though it depends on the OS) may raise a ValueError exception.
+      though it depends on the OS) may raise a :exc:`ValueError` exception.
 
    .. method:: recv()
 
@@ -2025,7 +2028,7 @@ with the :class:`Pool` class.
 
    *maxtasksperchild* is the number of tasks a worker process can complete
    before it will exit and be replaced with a fresh worker process, to enable
-   unused resources to be freed. The default *maxtasksperchild* is None, which
+   unused resources to be freed. The default *maxtasksperchild* is ``None``, which
    means worker processes will live as long as the pool.
 
    *context* can be used to specify the context used for starting
@@ -2295,7 +2298,7 @@ multiple connections at the same time.
    ``None`` then digest authentication is used.
 
    If *authkey* is a byte string then it will be used as the
-   authentication key; otherwise it must be *None*.
+   authentication key; otherwise it must be ``None``.
 
    If *authkey* is ``None`` and *authenticate* is ``True`` then
    ``current_process().authkey`` is used as the authentication key.  If
@@ -2723,12 +2726,7 @@ start method.
 
 More picklability
 
-    Ensure that all arguments to :meth:`Process.__init__` are
-    picklable.  This means, in particular, that bound or unbound
-    methods cannot be used directly as the ``target`` (unless you use
-    the *fork* start method) --- just define a function and use that
-    instead.
-
+    Ensure that all arguments to :meth:`Process.__init__` are picklable.
     Also, if you subclass :class:`~multiprocessing.Process` then make sure that
     instances will be picklable when the :meth:`Process.start
     <multiprocessing.Process.start>` method is called.
index cdc2616..64aa3ac 100644 (file)
 
 --------------
 
-The :class:`netrc` class parses and encapsulates the netrc file format used by
+The :class:`~netrc.netrc` class parses and encapsulates the netrc file format used by
 the Unix :program:`ftp` program and other FTP clients.
 
 
 .. class:: netrc([file])
 
-   A :class:`netrc` instance or subclass instance encapsulates data from  a netrc
+   A :class:`~netrc.netrc` instance or subclass instance encapsulates data from  a netrc
    file.  The initialization argument, if present, specifies the file to parse.  If
    no argument is given, the file :file:`.netrc` in the user's home directory will
    be read.  Parse errors will raise :exc:`NetrcParseError` with diagnostic
@@ -35,7 +35,7 @@ the Unix :program:`ftp` program and other FTP clients.
 
 .. exception:: NetrcParseError
 
-   Exception raised by the :class:`netrc` class when syntactical errors are
+   Exception raised by the :class:`~netrc.netrc` class when syntactical errors are
    encountered in source text.  Instances of this exception provide three
    interesting attributes:  :attr:`msg` is a textual explanation of the error,
    :attr:`filename` is the name of the source file, and :attr:`lineno` gives the
@@ -47,7 +47,7 @@ the Unix :program:`ftp` program and other FTP clients.
 netrc Objects
 -------------
 
-A :class:`netrc` instance has the following methods:
+A :class:`~netrc.netrc` instance has the following methods:
 
 
 .. method:: netrc.authenticators(host)
@@ -63,7 +63,7 @@ A :class:`netrc` instance has the following methods:
    Dump the class data as a string in the format of a netrc file. (This discards
    comments and may reorder the entries.)
 
-Instances of :class:`netrc` have public instance variables:
+Instances of :class:`~netrc.netrc` have public instance variables:
 
 
 .. attribute:: netrc.hosts
index 9790e3a..2c3cd8d 100644 (file)
@@ -75,7 +75,7 @@ The module itself defines the following classes:
     >>> from nntplib import NNTP
     >>> with NNTP('news.gmane.org') as n:
     ...     n.group('gmane.comp.python.committers')
-    ...
+    ... # doctest: +SKIP
     ('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
     >>>
 
@@ -220,7 +220,7 @@ tuples or objects that the method normally returns will be empty.
 .. method:: NNTP.login(user=None, password=None, usenetrc=True)
 
    Send ``AUTHINFO`` commands with the user name and password.  If *user*
-   and *password* are None and *usenetrc* is true, credentials from
+   and *password* are ``None`` and *usenetrc* is true, credentials from
    ``~/.netrc`` will be used if possible.
 
    Unless intentionally delayed, login is normally performed during the
@@ -261,9 +261,9 @@ tuples or objects that the method normally returns will be empty.
 
       >>> from datetime import date, timedelta
       >>> resp, groups = s.newgroups(date.today() - timedelta(days=3))
-      >>> len(groups)
+      >>> len(groups) # doctest: +SKIP
       85
-      >>> groups[0]
+      >>> groups[0] # doctest: +SKIP
       GroupInfo(group='gmane.network.tor.devel', last='4', first='1', flag='m')
 
 
@@ -312,9 +312,9 @@ tuples or objects that the method normally returns will be empty.
    is a dictionary mapping group names to textual descriptions.
 
       >>> resp, descs = s.descriptions('gmane.comp.python.*')
-      >>> len(descs)
+      >>> len(descs) # doctest: +SKIP
       295
-      >>> descs.popitem()
+      >>> descs.popitem() # doctest: +SKIP
       ('gmane.comp.python.bio.general', 'BioPython discussion list (Moderated)')
 
 
index 9a4ba4e..2ef187d 100644 (file)
@@ -678,7 +678,9 @@ automatically adds a ``--version`` option to your parser. If it encounters
 this option on the command line, it expands your ``version`` string (by
 replacing ``%prog``), prints it to stdout, and exits.
 
-For example, if your script is called ``/usr/bin/foo``::
+For example, if your script is called ``/usr/bin/foo``:
+
+.. code-block:: shell-session
 
    $ /usr/bin/foo --version
    foo 1.0
@@ -728,14 +730,18 @@ program's usage message and an error message to standard error and exits with
 error status 2.
 
 Consider the first example above, where the user passes ``4x`` to an option
-that takes an integer::
+that takes an integer:
+
+.. code-block:: shell-session
 
    $ /usr/bin/foo -n 4x
    Usage: foo [options]
 
    foo: error: option -n: invalid integer value: '4x'
 
-Or, where the user fails to pass a value at all::
+Or, where the user fails to pass a value at all:
+
+.. code-block:: shell-session
 
    $ /usr/bin/foo -n
    Usage: foo [options]
@@ -2020,12 +2026,12 @@ Features of note:
 
      values.ensure_value(attr, value)
 
-  If the ``attr`` attribute of ``values`` doesn't exist or is None, then
+  If the ``attr`` attribute of ``values`` doesn't exist or is ``None``, then
   ensure_value() first sets it to ``value``, and then returns 'value. This is
   very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
   of which accumulate data in a variable and expect that variable to be of a
   certain type (a list for the first two, an integer for the latter).  Using
   :meth:`ensure_value` means that scripts using your action don't have to worry
   about setting a default value for the option destinations in question; they
-  can just leave the default as None and :meth:`ensure_value` will take care of
+  can just leave the default as ``None`` and :meth:`ensure_value` will take care of
   getting it right when it's needed.
index 743efb6..5a67f93 100644 (file)
@@ -206,6 +206,9 @@ process and user.
    Return the value of the environment variable *key* if it exists, or
    *default* if it doesn't. *key*, *default* and the result are bytes.
 
+   :func:`getenvb` is only available if :data:`supports_bytes_environ`
+   is True.
+
    Availability: most flavors of Unix.
 
    .. versionadded:: 3.2
@@ -217,7 +220,7 @@ process and user.
    executable, similar to a shell, when launching a process.
    *env*, when specified, should be an environment variable dictionary
    to lookup the PATH in.
-   By default, when *env* is None, :data:`environ` is used.
+   By default, when *env* is ``None``, :data:`environ` is used.
 
    .. versionadded:: 3.2
 
@@ -908,7 +911,7 @@ or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windo
           O_EXCL
           O_TRUNC
 
-   These constants are available on Unix and Windows.
+   The above constants are available on Unix and Windows.
 
 
 .. data:: O_DSYNC
@@ -917,11 +920,9 @@ or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windo
           O_NDELAY
           O_NONBLOCK
           O_NOCTTY
-          O_SHLOCK
-          O_EXLOCK
           O_CLOEXEC
 
-   These constants are only available on Unix.
+   The above constants are only available on Unix.
 
    .. versionchanged:: 3.3
       Add :data:`O_CLOEXEC` constant.
@@ -934,7 +935,7 @@ or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windo
           O_SEQUENTIAL
           O_TEXT
 
-   These constants are only available on Windows.
+   The above constants are only available on Windows.
 
 
 .. data:: O_ASYNC
@@ -944,8 +945,10 @@ or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windo
           O_NOATIME
           O_PATH
           O_TMPFILE
+          O_SHLOCK
+          O_EXLOCK
 
-   These constants are GNU extensions and not present if they are not defined by
+   The above constants are extensions and not present if they are not defined by
    the C library.
 
    .. versionchanged:: 3.4
@@ -1195,7 +1198,11 @@ or `the MSDN <https://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windo
 .. function:: writev(fd, buffers)
 
    Write the contents of *buffers* to file descriptor *fd*. *buffers* must be a
-   sequence of :term:`bytes-like objects <bytes-like object>`.
+   sequence of :term:`bytes-like objects <bytes-like object>`. Buffers are
+   processed in array order. Entire contents of first buffer is written before
+   proceeding to second, and so on. The operating system may set a limit
+   (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
+
    :func:`~os.writev` writes the contents of each object to the file descriptor
    and returns the total number of bytes written.
 
@@ -1712,6 +1719,8 @@ features:
    This function can also support :ref:`paths relative to directory descriptors
    <dir_fd>`.
 
+   Availability: Unix.
+
    .. versionadded:: 3.3
       The *dir_fd* argument.
 
@@ -1896,7 +1905,7 @@ features:
    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 sytems, the type of the :attr:`~DirEntry.name` and
+   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*.
 
@@ -2049,9 +2058,8 @@ features:
 
    Note that there is a nice correspondence between several attributes
    and methods of ``DirEntry`` and of :class:`pathlib.Path`.  In
-   particular, the ``name`` and ``path`` attributes have the same
-   meaning, as do the ``is_dir()``, ``is_file()``, ``is_symlink()``
-   and ``stat()`` methods.
+   particular, the ``name`` attribute has the same meaning, as do the
+   ``is_dir()``, ``is_file()``, ``is_symlink()`` and ``stat()`` methods.
 
    .. versionadded:: 3.5
 
@@ -3613,7 +3621,7 @@ Miscellaneous System Information
 
 .. function:: cpu_count()
 
-   Return the number of CPUs in the system. Returns None if undetermined.
+   Return the number of CPUs in the system. Returns ``None`` if undetermined.
 
    .. versionadded:: 3.4
 
index f803fb6..7b90a1f 100644 (file)
@@ -832,7 +832,7 @@ call fails (for example because the path doesn't exist):
    If *parents* is false (the default), a missing parent raises
    :exc:`FileNotFoundError`.
 
-   If *exist_ok* is false (the default), an :exc:`FileExistsError` is
+   If *exist_ok* is false (the default), :exc:`FileExistsError` is
    raised if the target directory already exists.
 
    If *exist_ok* is true, :exc:`FileExistsError` exceptions will be
@@ -891,8 +891,9 @@ call fails (for example because the path doesn't exist):
 
 .. method:: Path.rename(target)
 
-   Rename this file or directory to the given *target*.  *target* can be
-   either a string or another path object::
+   Rename this file or directory to the given *target*.  On Unix, if
+   *target* exists and is a file, it will be replaced silently if the user
+   has permission.  *target* can be either a string or another path object::
 
       >>> p = Path('foo')
       >>> p.open('w').write('some text')
@@ -920,7 +921,7 @@ call fails (for example because the path doesn't exist):
       >>> p.resolve()
       PosixPath('/home/antoine/pathlib')
 
-   `".."` components are also eliminated (this is the only method to do so)::
+   "``..``" components are also eliminated (this is the only method to do so)::
 
       >>> p = Path('docs/../setup.py')
       >>> p.resolve()
@@ -933,7 +934,7 @@ call fails (for example because the path doesn't exist):
 
 .. method:: Path.rglob(pattern)
 
-   This is like calling :meth:`glob` with "``**``" added in front of the
+   This is like calling :meth:`Path.glob` with "``**``" added in front of the
    given *pattern*:
 
       >>> sorted(Path().rglob("*.py"))
@@ -988,7 +989,7 @@ call fails (for example because the path doesn't exist):
       of :func:`os.symlink`'s.
 
 
-.. method:: Path.touch(mode=0o777, exist_ok=True)
+.. method:: Path.touch(mode=0o666, exist_ok=True)
 
    Create a file at this given path.  If *mode* is given, it is combined
    with the process' ``umask`` value to determine the file mode and access
index 4520a9b..ba9e547 100644 (file)
@@ -158,7 +158,7 @@ access further features, you have to do this yourself:
    By default, Pdb sets a handler for the SIGINT signal (which is sent when the
    user presses :kbd:`Ctrl-C` on the console) when you give a ``continue`` command.
    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* tot true.
+   want Pdb not to touch the SIGINT handler, set *nosigint* to true.
 
    Example call to enable tracing with *skip*::
 
@@ -328,7 +328,7 @@ by the local file.
    return, jump, quit and their abbreviations) terminates the command list (as if
    that command was immediately followed by end). This is because any time you
    resume execution (even with a simple next or step), you may encounter another
-   breakpoint--which could have its own command list, leading to ambiguities about
+   breakpointwhich could have its own command list, leading to ambiguities about
    which list to execute.
 
    If you use the 'silent' command in the command list, the usual message about
@@ -449,7 +449,7 @@ by the local file.
 
 .. pdbcommand:: interact
 
-   Start an interative interpreter (using the :mod:`code` module) whose global
+   Start an interactive interpreter (using the :mod:`code` module) whose global
    namespace contains all the (global and local) names found in the current
    scope.
 
index 4c0a148..480f4a6 100644 (file)
@@ -30,7 +30,9 @@ However, when the pickle file that you want to examine comes from an
 untrusted source, ``-m pickletools`` is a safer option because it does
 not execute pickle bytecode.
 
-For example, with a tuple ``(1, 2)`` pickled in file ``x.pickle``::
+For example, with a tuple ``(1, 2)`` pickled in file ``x.pickle``:
+
+.. code-block:: shell-session
 
     $ python -m pickle x.pickle
     (1, 2)
@@ -90,8 +92,8 @@ Programmatic Interface
    a short description.  The value of *annotate* is used as a hint for
    the column where annotation should start.
 
-  .. versionadded:: 3.2
-     The *annotate* argument.
+   .. versionadded:: 3.2
+      The *annotate* argument.
 
 .. function:: genops(pickle)
 
@@ -106,4 +108,3 @@ Programmatic Interface
    Returns a new equivalent pickle string after eliminating unused ``PUT``
    opcodes. The optimized pickle is shorter, takes less transmission time,
    requires less storage space, and unpickles more efficiently.
-
index 26c5ac0..b9e76f7 100644 (file)
@@ -46,10 +46,10 @@ support.
 
 .. class:: ImpImporter(dirname=None)
 
-   :pep:`302` Importer that wraps Python's "classic" import algorithm.
+   :pep:`302` Finder that wraps Python's "classic" import algorithm.
 
-   If *dirname* is a string, a :pep:`302` importer is created that searches that
-   directory.  If *dirname* is ``None``, a :pep:`302` importer is created that
+   If *dirname* is a string, a :pep:`302` finder is created that searches that
+   directory.  If *dirname* is ``None``, a :pep:`302` finder is created that
    searches the current :data:`sys.path`, plus any modules that are frozen or
    built-in.
 
@@ -63,7 +63,7 @@ support.
 
 .. class:: ImpLoader(fullname, file, filename, etc)
 
-   :pep:`302` Loader that wraps Python's "classic" import algorithm.
+   :term:`Loader` that wraps Python's "classic" import algorithm.
 
    .. deprecated:: 3.3
       This emulation is no longer needed, as the standard import mechanism
@@ -72,7 +72,7 @@ support.
 
 .. function:: find_loader(fullname)
 
-   Retrieve a :pep:`302` module loader for the given *fullname*.
+   Retrieve a module :term:`loader` for the given *fullname*.
 
    This is a backwards compatibility wrapper around
    :func:`importlib.util.find_spec` that converts most failures to
@@ -88,9 +88,9 @@ support.
 
 .. function:: get_importer(path_item)
 
-   Retrieve a :pep:`302` importer for the given *path_item*.
+   Retrieve a :term:`finder` for the given *path_item*.
 
-   The returned importer is cached in :data:`sys.path_importer_cache` if it was
+   The returned finder is cached in :data:`sys.path_importer_cache` if it was
    newly created by a path hook.
 
    The cache (or part of it) can be cleared manually if a rescan of
@@ -103,7 +103,7 @@ support.
 
 .. function:: get_loader(module_or_name)
 
-   Get a :pep:`302` "loader" object for *module_or_name*.
+   Get a :term:`loader` object for *module_or_name*.
 
    If the module or package is accessible via the normal import mechanism, a
    wrapper around the relevant part of that machinery is returned.  Returns
@@ -121,16 +121,16 @@ support.
 
 .. function:: iter_importers(fullname='')
 
-   Yield :pep:`302` importers for the given module name.
+   Yield :term:`finder` objects for the given module name.
 
-   If fullname contains a '.', the importers will be for the package
+   If fullname contains a '.', the finders will be for the package
    containing fullname, otherwise they will be all registered top level
-   importers (i.e. those on both sys.meta_path and sys.path_hooks).
+   finders (i.e. those on both sys.meta_path and sys.path_hooks).
 
    If the named module is in a package, that package is imported as a side
    effect of invoking this function.
 
-   If no module name is specified, all top level importers are produced.
+   If no module name is specified, all top level finders are produced.
 
    .. versionchanged:: 3.3
       Updated to be based directly on :mod:`importlib` rather than relying
@@ -201,7 +201,8 @@ support.
 
    Get a resource from a package.
 
-   This is a wrapper for the :pep:`302` loader :func:`get_data` API.  The
+   This is a wrapper for the :term:`loader`
+   :meth:`get_data <importlib.abc.ResourceLoader.get_data>` API.  The
    *package* argument should be the name of a package, in standard module format
    (``foo.bar``).  The *resource* argument should be in the form of a relative
    filename, using ``/`` as the path separator.  The parent directory name
@@ -216,5 +217,8 @@ support.
       d = os.path.dirname(sys.modules[package].__file__)
       data = open(os.path.join(d, resource), 'rb').read()
 
-   If the package cannot be located or loaded, or it uses a :pep:`302` loader
-   which does not support :func:`get_data`, then ``None`` is returned.
+   If the package cannot be located or loaded, or it uses a :term:`loader`
+   which does not support :meth:`get_data <importlib.abc.ResourceLoader.get_data>`,
+   then ``None`` is returned.  In particular, the :term:`loader` for
+   :term:`namespace packages <namespace package>` does not support
+   :meth:`get_data <importlib.abc.ResourceLoader.get_data>`.
index 65f76b8..0af8fb1 100644 (file)
@@ -30,7 +30,7 @@ byte-code cache files in the directory containing the source code.
 .. function:: compile(file, cfile=None, dfile=None, doraise=False, optimize=-1)
 
    Compile a source file to byte-code and write out the byte-code cache file.
-   The source code is loaded from the file name *file*.  The byte-code is
+   The source code is loaded from the file named *file*.  The byte-code is
    written to *cfile*, which defaults to the :pep:`3147`/:pep:`488` path, ending
    in ``.pyc``.
    For example, if *file* is ``/foo/bar/baz.py`` *cfile* will default to
index 29c9f34..075a8b5 100644 (file)
@@ -86,7 +86,9 @@ The :mod:`xml.parsers.expat` module contains two functions:
    separator.
 
    For example, if *namespace_separator* is set to a space character (``' '``) and
-   the following document is parsed::
+   the following document is parsed:
+
+   .. code-block:: xml
 
       <?xml version="1.0"?>
       <root xmlns    = "http://default-namespace.org/"
@@ -244,7 +246,7 @@ XMLParser Objects
 
 The following attributes contain values relating to the most recent error
 encountered by an :class:`xmlparser` object, and will only have correct values
-once a call to :meth:`Parse` or :meth:`ParseFile` has raised a
+once a call to :meth:`Parse` or :meth:`ParseFile` has raised an
 :exc:`xml.parsers.expat.ExpatError` exception.
 
 
index 1cb0935..924be5a 100644 (file)
@@ -22,6 +22,8 @@ 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.
 
+Internally, the module uses locks to temporarily block competing threads;
+however, it is not designed to handle reentrancy within a thread.
 
 The :mod:`queue` module defines the following classes and exceptions:
 
@@ -101,7 +103,7 @@ provide the public methods described below.
 .. method:: Queue.put(item, block=True, timeout=None)
 
    Put *item* into the queue. If optional args *block* is true and *timeout* is
-   None (the default), block if necessary until a free slot is available. If
+   ``None`` (the default), block if necessary until a free slot is available. If
    *timeout* is a positive number, it blocks at most *timeout* seconds and raises
    the :exc:`Full` exception if no free slot was available within that time.
    Otherwise (*block* is false), put an item on the queue if a free slot is
@@ -117,7 +119,7 @@ provide the public methods described below.
 .. method:: Queue.get(block=True, timeout=None)
 
    Remove and return an item from the queue. If optional args *block* is true and
-   *timeout* is None (the default), block if necessary until an item is available.
+   *timeout* is ``None`` (the default), block if necessary until an item is available.
    If *timeout* is a positive number, it blocks at most *timeout* seconds and
    raises the :exc:`Empty` exception if no item was available within that time.
    Otherwise (*block* is false), return an item if one is immediately available,
index 3c31125..ef2b5f2 100644 (file)
@@ -52,7 +52,7 @@ sending a graphics file.
 
    Like :func:`encode`, except that it accepts a source :class:`bytes` and
    returns the corresponding encoded :class:`bytes`. By default, it sends a
-   False value to *quotetabs* parameter of the :func:`encode` function.
+   ``False`` value to *quotetabs* parameter of the :func:`encode` function.
 
 
 
index df502a0..8ae242c 100644 (file)
@@ -63,8 +63,11 @@ Bookkeeping functions:
    If *a* is an int, it is used directly.
 
    With version 2 (the default), a :class:`str`, :class:`bytes`, or :class:`bytearray`
-   object gets converted to an :class:`int` and all of its bits are used.  With version 1,
-   the :func:`hash` of *a* is used instead.
+   object gets converted to an :class:`int` and all of its bits are used.
+
+   With version 1 (provided for reproducing random sequences from older versions
+   of Python), the algorithm for :class:`str` and :class:`bytes` generates a
+   narrower range of seeds.
 
    .. versionchanged:: 3.2
       Moved to the version 2 scheme which uses all of the bits in a string seed.
@@ -263,7 +266,7 @@ Alternative Generator:
 
    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.
+   Modeling and Computer Simulation Vol. 8, No. 1, January pp.3--30 1998.
 
 
    `Complementary-Multiply-with-Carry recipe
@@ -325,6 +328,9 @@ 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'
 
@@ -334,6 +340,9 @@ with :func:`itertools.accumulate`, and then locate the random value with
 
     >>> 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]
+
     >>> x = random.random() * cumdist[-1]
     >>> choices[bisect.bisect(cumdist, x)]
     'Blue'
index 18d5596..1ca621e 100644 (file)
@@ -79,6 +79,12 @@ how the regular expressions around them are interpreted. Regular
 expression pattern strings may not contain null bytes, but can specify
 the null byte using a ``\number`` notation such as ``'\x00'``.
 
+Repetition qualifiers (``*``, ``+``, ``?``, ``{m,n}``, etc) cannot be
+directly nested. This avoids ambiguity with the non-greedy modifier suffix
+``?``, and with other modifiers in other implementations. To apply a second
+repetition to an inner repetition, parentheses may be used. For example,
+the expression ``(?:a{6})*`` matches any multiple of six ``'a'`` characters.
+
 
 The special characters are:
 
@@ -443,7 +449,7 @@ three digits in length.
    The ``'\u'`` and ``'\U'`` escape sequences have been added.
 
 .. deprecated-removed:: 3.5 3.6
-   Unknown escapes consist of ``'\'`` and ASCII letter now raise a
+   Unknown escapes consisting of ``'\'`` and ASCII letter now raise a
    deprecation warning and will be forbidden in Python 3.6.
 
 
index e17e69c..4d3c099 100644 (file)
@@ -104,7 +104,9 @@ The following functions operate on a history file:
 
    Append the last *nelements* items of history to a file.  The default filename is
    :file:`~/.history`.  The file must already exist.  This calls
-   :c:func:`append_history` in the underlying library.
+   :c:func:`append_history` in the underlying library.  This function
+   only exists if Python was compiled for a version of the library
+   that supports it.
 
    .. versionadded:: 3.5
 
@@ -185,7 +187,8 @@ Startup hooks
    be used as the new hook function; if omitted or ``None``, any
    function already installed is removed.  The hook is called
    with no arguments after the first prompt has been printed and just before
-   readline starts reading input characters.
+   readline starts reading input characters.  This function only exists
+   if Python was compiled for a version of the library that supports it.
 
 
 Completion
index b213793..bdfe5f6 100644 (file)
@@ -125,8 +125,7 @@ platform.
 
 .. data:: RLIMIT_FSIZE
 
-   The maximum size of a file which the process may create.  This only affects the
-   stack of the main thread in a multi-threaded process.
+   The maximum size of a file which the process may create.
 
 
 .. data:: RLIMIT_DATA
@@ -136,7 +135,8 @@ platform.
 
 .. data:: RLIMIT_STACK
 
-   The maximum size (in bytes) of the call stack for the current process.
+   The maximum size (in bytes) of the call stack for the current process.  This only
+   affects the stack of the main thread in a multi-threaded process.
 
 
 .. data:: RLIMIT_RSS
index 6cec9f7..a81386a 100644 (file)
@@ -57,9 +57,7 @@ The module defines the following:
 
    (Only supported on Linux 2.5.44 and newer.) Return an edge polling object,
    which can be used as Edge or Level Triggered interface for I/O
-   events. *sizehint* is deprecated and completely ignored. *flags* can be set
-   to :const:`EPOLL_CLOEXEC`, which causes the epoll descriptor to be closed
-   automatically when :func:`os.execve` is called.
+   events. *sizehint* and *flags* are deprecated and completely ignored.
 
    See the :ref:`epoll-objects` section below for the methods supported by
    epolling objects.
@@ -77,6 +75,10 @@ The module defines the following:
       Support for the :keyword:`with` statement was added.
       The new file descriptor is now non-inheritable.
 
+   .. deprecated:: 3.4
+      The *flags* parameter.  ``select.EPOLL_CLOEXEC`` is used by default now.
+      Use :func:`os.set_inheritable` to make the file descriptor inheritable.
+
 
 .. function:: poll()
 
@@ -457,7 +459,7 @@ Kqueue Objects
 
    Low level interface to kevent
 
-   - changelist must be an iterable of kevent object or None
+   - changelist must be an iterable of kevent object or ``None``
    - max_events must be 0 or a positive integer
    - timeout in seconds (floats possible)
 
index 44b27f3..1624d88 100644 (file)
@@ -1,5 +1,5 @@
-:mod:`selectors` -- High-level I/O multiplexing
-===============================================
+:mod:`selectors` --- High-level I/O multiplexing
+================================================
 
 .. module:: selectors
    :synopsis: High-level I/O multiplexing.
index 1ec158e..f08c581 100644 (file)
@@ -31,7 +31,7 @@ lots of shared  sub-objects.  The keys are ordinary strings.
    Because of Python semantics, a shelf cannot know when a mutable
    persistent-dictionary entry is modified.  By default modified objects are
    written *only* when assigned to the shelf (see :ref:`shelve-example`).  If the
-   optional *writeback* parameter is set to *True*, all entries accessed are also
+   optional *writeback* parameter is set to ``True``, all entries accessed are also
    cached in memory, and written back on :meth:`~Shelf.sync` and
    :meth:`~Shelf.close`; this can make it handier to mutate mutable entries in
    the persistent dictionary, but, if many entries are accessed, it can consume
@@ -108,7 +108,7 @@ Restrictions
    A subclass of :class:`collections.abc.MutableMapping` which stores pickled
    values in the *dict* object.
 
-   By default, version 0 pickles are used to serialize values.  The version of the
+   By default, version 3 pickles are used to serialize values.  The version of the
    pickle protocol can be specified with the *protocol* parameter. See the
    :mod:`pickle` documentation for a discussion of the pickle protocols.
 
index e9ba4e6..b020bb3 100644 (file)
@@ -107,7 +107,7 @@ Directory and files operations
    If *follow_symlinks* is false, and *src* and *dst* both
    refer to symbolic links, :func:`copystat` will operate on
    the symbolic links themselves rather than the files the
-   symbolic links refer to--reading the information from the
+   symbolic links refer toreading the information from the
    *src* symbolic link, and writing the information to the
    *dst* symbolic link.
 
@@ -458,6 +458,10 @@ Archiving operations
 
 .. versionadded:: 3.2
 
+.. versionchanged:: 3.5
+    Added support for the *xztar* format.
+
+
 High-level utilities to create and read compressed and archived files are also
 provided.  They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
 
@@ -467,8 +471,9 @@ provided.  They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
 
    *base_name* is the name of the file to create, including the path, minus
    any format-specific extension. *format* is the archive format: one of
-   "zip", "tar", "bztar" (if the :mod:`bz2` module is available), "xztar"
-   (if the :mod:`lzma` module is available) or "gztar".
+   "zip" (if the :mod:`zlib` module is available), "tar", "gztar" (if the
+   :mod:`zlib` module is available), "bztar" (if the :mod:`bz2` module is
+   available), or "xztar" (if the :mod:`lzma` module is available).
 
    *root_dir* is a directory that will be the root directory of the
    archive; for example, we typically chdir into *root_dir* before creating the
@@ -491,9 +496,6 @@ provided.  They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
 
    The *verbose* argument is unused and deprecated.
 
-   .. versionchanged:: 3.5
-      Added support for the *xztar* format.
-
 
 .. function:: get_archive_formats()
 
@@ -502,11 +504,11 @@ provided.  They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
 
    By default :mod:`shutil` provides these formats:
 
-   - *gztar*: gzip'ed tar-file
-   - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
-   - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available.)
-   - *tar*: uncompressed tar file
-   - *zip*: ZIP file
+   - *zip*: ZIP file (if the :mod:`zlib` module is available).
+   - *tar*: uncompressed tar file.
+   - *gztar*: gzip'ed tar-file (if the :mod:`zlib` module is available).
+   - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available).
+   - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available).
 
    You can register new formats or provide your own archiver for any existing
    formats, by using :func:`register_archive_format`.
@@ -541,11 +543,12 @@ provided.  They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
    *extract_dir* is the name of the target directory where the archive is
    unpacked. If not provided, the current working directory is used.
 
-   *format* is the archive format: one of "zip", "tar", or "gztar". Or any
-   other format registered with :func:`register_unpack_format`. If not
-   provided, :func:`unpack_archive` will use the archive file name extension
-   and see if an unpacker was registered for that extension. In case none is
-   found, a :exc:`ValueError` is raised.
+   *format* is the archive format: one of "zip", "tar", "gztar", "bztar", or
+   "xztar".  Or any other format registered with
+   :func:`register_unpack_format`.  If not provided, :func:`unpack_archive`
+   will use the archive file name extension and see if an unpacker was
+   registered for that extension.  In case none is found,
+   a :exc:`ValueError` is raised.
 
 
 .. function:: register_unpack_format(name, extensions, function[, extra_args[, description]])
@@ -578,11 +581,12 @@ provided.  They rely on the :mod:`zipfile` and :mod:`tarfile` modules.
 
    By default :mod:`shutil` provides these formats:
 
-   - *gztar*: gzip'ed tar-file
-   - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available.)
-   - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available.)
-   - *tar*: uncompressed tar file
-   - *zip*: ZIP file
+   - *zip*: ZIP file (unpacking compressed files works only if the corresponding
+     module is available).
+   - *tar*: uncompressed tar file.
+   - *gztar*: gzip'ed tar-file (if the :mod:`zlib` module is available).
+   - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available).
+   - *xztar*: xz'ed tar-file (if the :mod:`lzma` module is available).
 
    You can register new formats or provide your own unpacker for any existing
    formats, by using :func:`register_unpack_format`.
@@ -603,7 +607,9 @@ found in the :file:`.ssh` directory of the user::
     >>> make_archive(archive_name, 'gztar', root_dir)
     '/Users/tarek/myarchive.tar.gz'
 
-The resulting archive contains::
+The resulting archive contains:
+
+.. code-block:: shell-session
 
     $ tar -tzvf /Users/tarek/myarchive.tar.gz
     drwx------ tarek/staff       0 2010-02-01 16:23:40 ./
@@ -619,8 +625,6 @@ The resulting archive contains::
 Querying the size of the output terminal
 ----------------------------------------
 
-.. versionadded:: 3.3
-
 .. function:: get_terminal_size(fallback=(columns, lines))
 
    Get the size of the terminal window.
@@ -644,6 +648,8 @@ Querying the size of the output terminal
    See also: The Single UNIX Specification, Version 2,
    `Other Environment Variables`_.
 
+   .. versionadded:: 3.3
+
 .. _`Other Environment Variables`:
    http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html#tag_002_003
 
index 61252ce..039b666 100644 (file)
@@ -350,8 +350,9 @@ The :mod:`signal` module defines the following functions:
    attribute descriptions in the :mod:`inspect` module).
 
    On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
-   :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, or
-   :const:`SIGTERM`. A :exc:`ValueError` will be raised in any other case.
+   :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`,
+   :const:`SIGTERM`, or :const:`SIGBREAK`.
+   A :exc:`ValueError` will be raised in any other case.
    Note that not all systems define the same set of signal names; an
    :exc:`AttributeError` will be raised if a signal name is not defined as
    ``SIG*`` module level constant.
index 977f9a8..a096de0 100644 (file)
@@ -32,9 +32,10 @@ SMTPServer Objects
                       map=None, enable_SMTPUTF8=False, decode_data=True)
 
    Create a new :class:`SMTPServer` object, which binds to local address
-   *localaddr*.  It will treat *remoteaddr* as an upstream SMTP relayer.  It
-   inherits from :class:`asyncore.dispatcher`, and so will insert itself into
-   :mod:`asyncore`'s event loop on instantiation.
+   *localaddr*.  It will treat *remoteaddr* as an upstream SMTP relayer.  Both
+   *localaddr* and *remoteaddr* should be a :ref:`(host, port) <host_port>`
+   tuple.  The object inherits from :class:`asyncore.dispatcher`, and so will
+   insert itself into :mod:`asyncore`'s event loop on instantiation.
 
    *data_size_limit* specifies the maximum number of bytes that will be
    accepted in a ``DATA`` command.  A value of ``None`` or ``0`` means no
@@ -44,7 +45,7 @@ SMTPServer Objects
    dictionary is a suitable value).  If not specified the :mod:`asyncore`
    global socket map is used.
 
-   *enable_SMTPUTF8* determins whether the ``SMTPUTF8`` extension (as defined
+   *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).
    When ``True``, ``SMTPUTF8`` is accepted as a parameter to the ``MAIL``
@@ -161,7 +162,7 @@ SMTPChannel Objects
    accepted in a ``DATA`` command.  A value of ``None`` or ``0`` means no
    limit.
 
-   *enable_SMTPUTF8* determins whether the ``SMTPUTF8`` extension (as defined
+   *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.
index bdf3805..8b98ccf 100644 (file)
@@ -341,10 +341,10 @@ An :class:`SMTP` instance has the following methods:
    :rfc:`4954` "initial response" bytes which will be encoded and sent with
    the ``AUTH`` command as below.  If the ``authobject()`` does not support an
    initial response (e.g. because it requires a challenge), it should return
-   None when called with ``challenge=None``.  If *initial_response_ok* is
-   false, then ``authobject()`` will not be called first with None.
+   ``None`` when called with ``challenge=None``.  If *initial_response_ok* is
+   false, then ``authobject()`` will not be called first with ``None``.
 
-   If the initial response check returns None, or if *initial_response_ok* is
+   If the initial response check returns ``None``, or if *initial_response_ok* is
    false, ``authobject()`` will be called to process the server's challenge
    response; the *challenge* argument it is passed will be a ``bytes``.  It
    should return ``bytes`` *data* that will be base64 encoded and sent to the
@@ -374,8 +374,9 @@ An :class:`SMTP` instance has the following methods:
    If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
    module's :func:`ssl` function.
 
-   Optional *context* parameter is a :class:`ssl.SSLContext` object; This is an alternative to
-   using a keyfile and a certfile and if specified both *keyfile* and *certfile* should be None.
+   Optional *context* parameter is a :class:`ssl.SSLContext` object; This is
+   an alternative to using a keyfile and a certfile and if specified both
+   *keyfile* and *certfile* should be ``None``.
 
    If there has been no previous ``EHLO`` or ``HELO`` command this session,
    this method tries ESMTP ``EHLO`` first.
@@ -439,7 +440,7 @@ An :class:`SMTP` instance has the following methods:
    and the accompanying error message sent by the server.
 
    If ``SMTPUTF8`` is included in *mail_options*, and the server supports it,
-   *from_addr* and *to_addr* may contain non-ASCII characters.
+   *from_addr* and *to_addrs* may contain non-ASCII characters.
 
    This method may raise the following exceptions:
 
@@ -486,7 +487,7 @@ An :class:`SMTP` instance has the following methods:
    those arguments with addresses extracted from the headers of *msg* as
    specified in :rfc:`5322`\: *from_addr* is set to the :mailheader:`Sender`
    field if it is present, and otherwise to the :mailheader:`From` field.
-   *to_adresses* combines the values (if any) of the :mailheader:`To`,
+   *to_addrs* combines the values (if any) of the :mailheader:`To`,
    :mailheader:`Cc`, and :mailheader:`Bcc` fields from *msg*.  If exactly one
    set of :mailheader:`Resent-*` headers appear in the message, the regular
    headers are ignored and the :mailheader:`Resent-*` headers are used instead.
index 48311c5..530000b 100644 (file)
@@ -63,6 +63,8 @@ created.  Socket addresses are represented as follows:
    .. versionchanged:: 3.5
       Writable :term:`bytes-like object` is now accepted.
 
+.. _host_port:
+
 - A pair ``(host, port)`` is used for the :const:`AF_INET` address family,
   where *host* is a string representing either a hostname in Internet domain
   notation like ``'daring.cwi.nl'`` or an IPv4 address like ``'100.50.200.5'``,
@@ -1211,7 +1213,7 @@ to sockets.
    much data, if any, was successfully sent.
 
    .. versionchanged:: 3.5
-      The socket timeout is no more reset each time data is sent successfuly.
+      The socket timeout is no more reset each time data is sent successfully.
       The socket timeout is now the maximum total duration to send all data.
 
    .. versionchanged:: 3.5
@@ -1365,7 +1367,7 @@ Note that there are no methods :meth:`read` or :meth:`write`; use
 :meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead.
 
 Socket objects also have these (read-only) attributes that correspond to the
-values given to the :class:`socket` constructor.
+values given to the :class:`~socket.socket` constructor.
 
 
 .. attribute:: socket.family
index 98d2c46..087f4e0 100644 (file)
@@ -479,7 +479,9 @@ This is the client side::
 
 The output of the example should look something like this:
 
-Server::
+Server:
+
+.. code-block:: shell-session
 
    $ python TCPServer.py
    127.0.0.1 wrote:
@@ -487,7 +489,9 @@ Server::
    127.0.0.1 wrote:
    b'python is nice'
 
-Client::
+Client:
+
+.. code-block:: shell-session
 
    $ python TCPClient.py hello world with TCP
    Sent:     hello world with TCP
@@ -599,7 +603,9 @@ An example for the :class:`ThreadingMixIn` class::
        server.server_close()
 
 
-The output of the example should look something like this::
+The output of the example should look something like this:
+
+.. code-block:: shell-session
 
    $ python ThreadedTCPServer.py
    Server loop running in thread: Thread-1
index 3bba935..84a4783 100644 (file)
@@ -183,7 +183,7 @@ Module functions and constants
    parameter is 5.0 (five seconds).
 
    For the *isolation_level* parameter, please see the
-   :attr:`Connection.isolation_level` property of :class:`Connection` objects.
+   :attr:`~Connection.isolation_level` property of :class:`Connection` objects.
 
    SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
    you want to use other types you must add support for them yourself. The
@@ -285,11 +285,11 @@ Connection Objects
 
       .. versionadded:: 3.2
 
-   .. method:: cursor([cursorClass])
+   .. method:: cursor(factory=Cursor)
 
-      The cursor method accepts a single optional parameter *cursorClass*. If
-      supplied, this must be a custom cursor class that extends
-      :class:`sqlite3.Cursor`.
+      The cursor method accepts a single optional parameter *factory*. If
+      supplied, this must be a callable returning an instance of :class:`Cursor`
+      or its subclasses.
 
    .. method:: commit()
 
@@ -309,25 +309,26 @@ Connection Objects
       call :meth:`commit`. If you just close your database connection without
       calling :meth:`commit` first, your changes will be lost!
 
-   .. method:: execute(sql, [parameters])
+   .. method:: execute(sql[, parameters])
 
-      This is a nonstandard shortcut that creates an intermediate cursor object by
-      calling the cursor method, then calls the cursor's :meth:`execute
-      <Cursor.execute>` method with the parameters given.
+      This is a nonstandard shortcut that creates a cursor object by calling
+      the :meth:`~Connection.cursor` method, calls the cursor's
+      :meth:`~Cursor.execute` method with the *parameters* given, and returns
+      the cursor.
 
+   .. method:: executemany(sql[, parameters])
 
-   .. method:: executemany(sql, [parameters])
-
-      This is a nonstandard shortcut that creates an intermediate cursor object by
-      calling the cursor method, then calls the cursor's :meth:`executemany
-      <Cursor.executemany>` method with the parameters given.
+      This is a nonstandard shortcut that creates a cursor object by
+      calling the :meth:`~Connection.cursor` method, calls the cursor's
+      :meth:`~Cursor.executemany` method with the *parameters* given, and
+      returns the cursor.
 
    .. method:: executescript(sql_script)
 
-      This is a nonstandard shortcut that creates an intermediate cursor object by
-      calling the cursor method, then calls the cursor's :meth:`executescript
-      <Cursor.executescript>` method with the parameters given.
-
+      This is a nonstandard shortcut that creates a cursor object by
+      calling the :meth:`~Connection.cursor` method, calls the cursor's
+      :meth:`~Cursor.executescript` method with the given *sql_script*, and
+      returns the cursor.
 
    .. method:: create_function(name, num_params, func)
 
@@ -338,7 +339,7 @@ Connection Objects
       called as the SQL function.
 
       The function can return any of the types supported by SQLite: bytes, str, int,
-      float and None.
+      float and ``None``.
 
       Example:
 
@@ -355,7 +356,7 @@ Connection Objects
       final result of the aggregate.
 
       The ``finalize`` method can return any of the types supported by SQLite:
-      bytes, str, int, float and None.
+      bytes, str, int, float and ``None``.
 
       Example:
 
@@ -377,7 +378,7 @@ Connection Objects
 
       .. literalinclude:: ../includes/sqlite3/collation_reverse.py
 
-      To remove a collation, call ``create_collation`` with None as callable::
+      To remove a collation, call ``create_collation`` with ``None`` as callable::
 
          con.create_collation("reverse", None)
 
@@ -488,10 +489,6 @@ Connection Objects
       :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
       return bytestrings instead, you can set it to :class:`bytes`.
 
-      For efficiency reasons, there's also a way to return :class:`str` objects
-      only for non-ASCII data, and :class:`bytes` otherwise. To activate it, set
-      this attribute to :const:`sqlite3.OptimizedUnicode`.
-
       You can also set it to any other callable that accepts a single bytestring
       parameter and returns the resulting object.
 
@@ -533,7 +530,7 @@ Cursor Objects
 
    A :class:`Cursor` instance has the following attributes and methods.
 
-   .. method:: execute(sql, [parameters])
+   .. method:: execute(sql[, parameters])
 
       Executes an SQL statement. The SQL statement may be parameterized (i. e.
       placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
@@ -545,7 +542,7 @@ Cursor Objects
       .. literalinclude:: ../includes/sqlite3/execute_1.py
 
       :meth:`execute` will only execute a single SQL statement. If you try to execute
-      more than one statement with it, it will raise a Warning. Use
+      more than one statement with it, it will raise a :exc:`.Warning`. Use
       :meth:`executescript` if you want to execute multiple SQL statements with one
       call.
 
@@ -553,8 +550,8 @@ Cursor Objects
    .. method:: executemany(sql, seq_of_parameters)
 
       Executes an SQL command against all parameter sequences or mappings found in
-      the sequence *sql*.  The :mod:`sqlite3` module also allows using an
-      :term:`iterator` yielding parameters instead of a sequence.
+      the sequence *seq_of_parameters*.  The :mod:`sqlite3` module also allows
+      using an :term:`iterator` yielding parameters instead of a sequence.
 
       .. literalinclude:: ../includes/sqlite3/executemany_1.py
 
@@ -569,7 +566,7 @@ Cursor Objects
       at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
       gets as a parameter.
 
-      *sql_script* can be an instance of :class:`str` or :class:`bytes`.
+      *sql_script* can be an instance of :class:`str`.
 
       Example:
 
@@ -608,7 +605,7 @@ Cursor Objects
 
       Close the cursor now (rather than whenever ``__del__`` is called).
 
-      The cursor will be unusable from this point forward; a ``ProgrammingError``
+      The cursor will be unusable from this point forward; a :exc:`ProgrammingError`
       exception will be raised if any operation is attempted with the cursor.
 
    .. attribute:: rowcount
@@ -722,6 +719,36 @@ Now we plug :class:`Row` in::
    35.14
 
 
+.. _sqlite3-exceptions:
+
+Exceptions
+----------
+
+.. exception:: Warning
+
+   A subclass of :exc:`Exception`.
+
+.. exception:: Error
+
+   The base class of the other exceptions in this module.  It is a subclass
+   of :exc:`Exception`.
+
+.. exception:: DatabaseError
+
+   Exception raised for errors that are related to the database.
+
+.. exception:: IntegrityError
+
+   Exception raised when the relational integrity of the database is affected,
+   e.g. a foreign key check fails.  It is a subclass of :exc:`DatabaseError`.
+
+.. exception:: ProgrammingError
+
+   Exception raised for programming errors, e.g. table not found or already
+   exists, syntax error in the SQL statement, wrong number of parameters
+   specified, etc.  It is a subclass of :exc:`DatabaseError`.
+
+
 .. _sqlite3-types:
 
 SQLite and Python types
@@ -907,7 +934,7 @@ You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
 (or none at all) via the *isolation_level* parameter to the :func:`connect`
 call, or via the :attr:`isolation_level` property of connections.
 
-If you want **autocommit mode**, then set :attr:`isolation_level` to None.
+If you want **autocommit mode**, then set :attr:`isolation_level` to ``None``.
 
 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",
index 5792d0d..a2f0083 100644 (file)
@@ -178,7 +178,7 @@ instead.
    use.  Typically, the server chooses a particular protocol version, and the
    client must adapt to the server's choice.  Most of the versions are not
    interoperable with the other versions.  If not specified, the default is
-   :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
+   :data:`PROTOCOL_TLS`; it provides the most compatibility with other
    versions.
 
    Here's a table showing which versions in a client (down the side) can connect
@@ -187,11 +187,11 @@ instead.
      .. table::
 
        ========================  =========  =========  ==========  =========  ===========  ===========
-        *client* / **server**    **SSLv2**  **SSLv3**  **SSLv23**  **TLSv1**  **TLSv1.1**  **TLSv1.2**
+        *client* / **server**    **SSLv2**  **SSLv3**  **TLS**     **TLSv1**  **TLSv1.1**  **TLSv1.2**
        ------------------------  ---------  ---------  ----------  ---------  -----------  -----------
         *SSLv2*                    yes        no         yes         no         no         no
         *SSLv3*                    no         yes        yes         no         no         no
-        *SSLv23*                   no         yes        yes         yes        yes        yes
+        *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
@@ -244,7 +244,7 @@ purposes.
    :const:`None`, this function can choose to trust the system's default
    CA certificates instead.
 
-   The settings are: :data:`PROTOCOL_SSLv23`, :data:`OP_NO_SSLv2`, and
+   The settings are: :data:`PROTOCOL_TLS`, :data:`OP_NO_SSLv2`, and
    :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and
    without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH`
    as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED`
@@ -279,6 +279,12 @@ purposes.
 
      RC4 was dropped from the default cipher string.
 
+   .. versionchanged:: 3.5.3
+
+     ChaCha20/Poly1305 was added to the default cipher string.
+
+     3DES was dropped from the default cipher string.
+
 
 Random generation
 ^^^^^^^^^^^^^^^^^
@@ -316,6 +322,11 @@ Random generation
 
    .. versionadded:: 3.3
 
+   .. deprecated:: 3.5.3
+
+      OpenSSL has deprecated :func:`ssl.RAND_pseudo_bytes`, use
+      :func:`ssl.RAND_bytes` instead.
+
 .. function:: RAND_status()
 
    Return ``True`` if the SSL pseudo-random number generator has been seeded
@@ -334,7 +345,7 @@ Random generation
    See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
    of entropy-gathering daemons.
 
-   Availability: not available with LibreSSL.
+   Availability: not available with LibreSSL and OpenSSL > 1.1.0
 
 .. function:: RAND_add(bytes, entropy)
 
@@ -409,7 +420,7 @@ Certificate handling
       previously. Return an integer (no fractions of a second in the
       input format)
 
-.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None)
+.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None)
 
    Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
    *port-number*) pair, fetches the server's certificate, and returns it as a
@@ -425,7 +436,7 @@ Certificate handling
 
    .. versionchanged:: 3.5
       The default *ssl_version* is changed from :data:`PROTOCOL_SSLv3` to
-      :data:`PROTOCOL_SSLv23` for maximum compatibility with modern servers.
+      :data:`PROTOCOL_TLS` for maximum compatibility with modern servers.
 
 .. function:: DER_cert_to_PEM_cert(DER_cert_bytes)
 
@@ -444,13 +455,16 @@ Certificate handling
    :meth:`SSLContext.set_default_verify_paths`. The return value is a
    :term:`named tuple` ``DefaultVerifyPaths``:
 
-   * :attr:`cafile` - resolved path to cafile or None if the file doesn't exist,
-   * :attr:`capath` - resolved path to capath or None if the directory doesn't exist,
+   * :attr:`cafile` - resolved path to cafile or ``None`` if the file doesn't exist,
+   * :attr:`capath` - resolved path to capath or ``None`` if the directory doesn't exist,
    * :attr:`openssl_cafile_env` - OpenSSL's environment key that points to a cafile,
    * :attr:`openssl_cafile` - hard coded path to a cafile,
    * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath,
    * :attr:`openssl_capath` - hard coded path to a capath directory
 
+   Availability: LibreSSL ignores the environment vars
+   :attr:`openssl_cafile_env` and :attr:`openssl_capath_env`
+
    .. versionadded:: 3.4
 
 .. function:: enum_certificates(store_name)
@@ -568,11 +582,21 @@ Constants
 
    .. versionadded:: 3.4.4
 
-.. data:: PROTOCOL_SSLv23
+.. 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
+
+.. data:: PROTOCOL_SSLv23
+
+   Alias for data:`PROTOCOL_TLS`.
+
+   .. deprecated:: 3.5.3
+
+      Use data:`PROTOCOL_TLS` instead.
+
 .. data:: PROTOCOL_SSLv2
 
    Selects SSL version 2 as the channel encryption protocol.
@@ -584,6 +608,10 @@ Constants
 
       SSL version 2 is insecure.  Its use is highly discouraged.
 
+   .. deprecated:: 3.5.3
+
+      OpenSSL has removed support for SSLv2.
+
 .. data:: PROTOCOL_SSLv3
 
    Selects SSL version 3 as the channel encryption protocol.
@@ -595,10 +623,20 @@ Constants
 
       SSL version 3 is insecure.  Its use is highly discouraged.
 
+   .. deprecated:: 3.5.3
+
+      OpenSSL has deprecated all version specific protocols. Use the default
+      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
+
 .. data:: PROTOCOL_TLSv1
 
    Selects TLS version 1.0 as the channel encryption protocol.
 
+   .. deprecated:: 3.5.3
+
+      OpenSSL has deprecated all version specific protocols. Use the default
+      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
+
 .. data:: PROTOCOL_TLSv1_1
 
    Selects TLS version 1.1 as the channel encryption protocol.
@@ -606,6 +644,11 @@ Constants
 
    .. versionadded:: 3.4
 
+   .. deprecated:: 3.5.3
+
+      OpenSSL has deprecated all version specific protocols. Use the default
+      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
+
 .. data:: PROTOCOL_TLSv1_2
 
    Selects TLS version 1.2 as the channel encryption protocol. This is the
@@ -614,6 +657,11 @@ Constants
 
    .. versionadded:: 3.4
 
+   .. deprecated:: 3.5.3
+
+      OpenSSL has deprecated all version specific protocols. Use the default
+      protocol data:`PROTOCOL_TLS` with flags like data:`OP_NO_SSLv3` instead.
+
 .. data:: OP_ALL
 
    Enables workarounds for various bugs present in other SSL implementations.
@@ -625,23 +673,32 @@ Constants
 .. data:: OP_NO_SSLv2
 
    Prevents an SSLv2 connection.  This option is only applicable in
-   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
+   conjunction with :const:`PROTOCOL_TLS`.  It prevents the peers from
    choosing SSLv2 as the protocol version.
 
    .. versionadded:: 3.2
 
+   .. deprecated:: 3.5.3
+
+      SSLv2 is deprecated
+
+
 .. data:: OP_NO_SSLv3
 
    Prevents an SSLv3 connection.  This option is only applicable in
-   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
+   conjunction with :const:`PROTOCOL_TLS`.  It prevents the peers from
    choosing SSLv3 as the protocol version.
 
    .. versionadded:: 3.2
 
+   .. deprecated:: 3.5.3
+
+      SSLv3 is deprecated
+
 .. data:: OP_NO_TLSv1
 
    Prevents a TLSv1 connection.  This option is only applicable in
-   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
+   conjunction with :const:`PROTOCOL_TLS`.  It prevents the peers from
    choosing TLSv1 as the protocol version.
 
    .. versionadded:: 3.2
@@ -649,7 +706,7 @@ Constants
 .. data:: OP_NO_TLSv1_1
 
    Prevents a TLSv1.1 connection. This option is only applicable in conjunction
-   with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.1 as
+   with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.1 as
    the protocol version. Available only with openssl version 1.0.1+.
 
    .. versionadded:: 3.4
@@ -657,7 +714,7 @@ Constants
 .. data:: OP_NO_TLSv1_2
 
    Prevents a TLSv1.2 connection. This option is only applicable in conjunction
-   with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.2 as
+   with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.2 as
    the protocol version. Available only with openssl version 1.0.1+.
 
    .. versionadded:: 3.4
@@ -1081,17 +1138,21 @@ such as SSL configuration options, certificate(s) and private key(s).
 It also manages a cache of SSL sessions for server-side sockets, in order
 to speed up repeated connections from the same clients.
 
-.. class:: SSLContext(protocol)
+.. class:: SSLContext(protocol=PROTOCOL_TLS)
 
-   Create a new SSL context.  You must pass *protocol* which must be one
+   Create a new SSL context.  You may pass *protocol* which must be one
    of the ``PROTOCOL_*`` constants defined in this module.
-   :data:`PROTOCOL_SSLv23` is currently recommended for maximum
-   interoperability.
+   :data:`PROTOCOL_TLS` is currently recommended for maximum
+   interoperability and default value.
 
    .. seealso::
       :func:`create_default_context` lets the :mod:`ssl` module choose
       security settings for a given purpose.
 
+   .. versionchanged:: 3.5.3
+
+      :data:`PROTOCOL_TLS` is the default value.
+
 
 :class:`SSLContext` objects have the following methods and attributes:
 
@@ -1232,6 +1293,9 @@ to speed up repeated connections from the same clients.
    This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is
    False.
 
+   OpenSSL 1.1.0+ will abort the handshake and raise :exc:`SSLError` when
+   both sides support ALPN but cannot agree on a protocol.
+
    .. versionadded:: 3.5
 
 .. method:: SSLContext.set_npn_protocols(protocols)
@@ -1323,7 +1387,7 @@ to speed up repeated connections from the same clients.
    This setting doesn't apply to client sockets.  You can also use the
    :data:`OP_SINGLE_ECDH_USE` option to further improve security.
 
-   This method is not available if :data:`HAS_ECDH` is False.
+   This method is not available if :data:`HAS_ECDH` is ``False``.
 
    .. versionadded:: 3.3
 
@@ -1598,7 +1662,7 @@ If you prefer to tune security settings yourself, you might create
 a context from scratch (but beware that you might not get the settings
 right)::
 
-   >>> context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+   >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS)
    >>> context.verify_mode = ssl.CERT_REQUIRED
    >>> context.check_hostname = True
    >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")
@@ -1999,15 +2063,17 @@ 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_SSLv23` as the protocol version and then
+recommended to use :const:`PROTOCOL_TLS` as the protocol version and then
 disable SSLv2 and SSLv3 explicitly using the :data:`SSLContext.options`
 attribute::
 
-   context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+   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 and later (if
+The SSL context created above will only allow TLSv1.2 and later (if
 supported by your system) connections.
 
 Cipher selection
index ea3d7da..7685621 100644 (file)
@@ -191,9 +191,9 @@ However, for reading convenience, most of the examples show sorted sequences.
       52.5
 
    In the following example, the data are rounded, so that each value represents
-   the midpoint of data classes, e.g. 1 is the midpoint of the class 0.5-1.5, 2
-   is the midpoint of 1.5-2.5, 3 is the midpoint of 2.5-3.5, etc.  With the data
-   given, the middle value falls somewhere in the class 3.5-4.5, and
+   the midpoint of data classes, e.g. 1 is the midpoint of the class 0.5--1.5, 2
+   is the midpoint of 1.5--2.5, 3 is the midpoint of 2.5--3.5, etc.  With the data
+   given, the middle value falls somewhere in the class 3.5--4.5, and
    interpolation is used to estimate it:
 
    .. doctest::
index e8a488e..71cb7f2 100644 (file)
@@ -485,7 +485,7 @@ class`. In addition, it provides a few more methods:
         >>> (-1024).to_bytes(10, byteorder='big', signed=True)
         b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
         >>> x = 1000
-        >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')
+        >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
         b'\xe8\x03'
 
     The integer is represented using *length* bytes.  An :exc:`OverflowError`
@@ -692,16 +692,16 @@ number, :class:`float`, or :class:`complex`::
            m, n = m // P, n // P
 
        if n % P == 0:
-           hash_ = sys.hash_info.inf
+           hash_value = sys.hash_info.inf
        else:
            # Fermat's Little Theorem: pow(n, P-1, P) is 1, so
            # pow(n, P-2, P) gives the inverse of n modulo P.
-           hash_ = (abs(m) % P) * pow(n, P - 2, P) % P
+           hash_value = (abs(m) % P) * pow(n, P - 2, P) % P
        if m < 0:
-           hash_ = -hash_
-       if hash_ == -1:
-           hash_ = -2
-       return hash_
+           hash_value = -hash_value
+       if hash_value == -1:
+           hash_value = -2
+       return hash_value
 
    def hash_float(x):
        """Compute the hash of a float x."""
@@ -716,13 +716,13 @@ number, :class:`float`, or :class:`complex`::
    def hash_complex(z):
        """Compute the hash of a complex number z."""
 
-       hash_ = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
+       hash_value = hash_float(z.real) + sys.hash_info.imag * hash_float(z.imag)
        # do a signed reduction modulo 2**sys.hash_info.width
        M = 2**(sys.hash_info.width - 1)
-       hash_ = (hash_ & (M - 1)) - (hash & M)
-       if hash_ == -1:
-           hash_ == -2
-       return hash_
+       hash_value = (hash_value & (M - 1)) - (hash_value & M)
+       if hash_value == -1:
+           hash_value = -2
+       return hash_value
 
 .. _typeiter:
 
@@ -927,7 +927,7 @@ Notes:
    :ref:`faq-multidimensional-list`.
 
 (3)
-   If *i* or *j* is negative, the index is relative to the end of the string:
+   If *i* or *j* is negative, the index is relative to the end of sequence *s*:
    ``len(s) + i`` or ``len(s) + j`` is substituted.  But note that ``-0`` is
    still ``0``.
 
@@ -942,8 +942,10 @@ Notes:
    The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
    items with index  ``x = i + n*k`` such that ``0 <= n < (j-i)/k``.  In other words,
    the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
-   *j* is reached (but never including *j*).  If *i* or *j* is greater than
-   ``len(s)``, use ``len(s)``.  If *i* or *j* are omitted or ``None``, they become
+   *j* is reached (but never including *j*).  When *k* is positive,
+   *i* and *j* are reduced to ``len(s)`` if they are greater.
+   When *k* is negative, *i* and *j* are reduced to ``len(s) - 1`` if
+   they are greater.  If *i* or *j* are omitted or ``None``, they become
    "end" values (which end depends on the sign of *k*).  Note, *k* cannot be zero.
    If *k* is ``None``, it is treated like ``1``.
 
@@ -1639,18 +1641,20 @@ expression support in the :mod:`re` module).
 
    Return true if all characters in the string are decimal
    characters and there is at least one character, false
-   otherwise. Decimal characters are those from general category "Nd". This category
-   includes digit characters, and all characters
-   that can be used to form decimal-radix numbers, e.g. U+0660,
-   ARABIC-INDIC DIGIT ZERO.
+   otherwise. Decimal characters are those that can be used to form
+   numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT
+   ZERO.  Formally a decimal character is a character in the Unicode
+   General Category "Nd".
 
 
 .. method:: str.isdigit()
 
    Return true if all characters in the string are digits and there is at least one
    character, false otherwise.  Digits include decimal characters and digits that need
-   special handling, such as the compatibility superscript digits.  Formally, a digit
-   is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
+   special handling, such as the compatibility superscript digits.
+   This covers digits which cannot be used to form numbers in base 10,
+   like the Kharosthi numbers.  Formally, a digit is a character that has the
+   property value Numeric_Type=Digit or Numeric_Type=Decimal.
 
 
 .. method:: str.isidentifier()
@@ -1751,13 +1755,13 @@ expression support in the :mod:`re` module).
 
    If there is only one argument, it must be a dictionary mapping Unicode
    ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
-   strings (of arbitrary lengths) or None.  Character keys will then be
+   strings (of arbitrary lengths) or ``None``.  Character keys will then be
    converted to ordinals.
 
    If there are two arguments, they must be strings of equal length, and in the
    resulting dictionary, each character in x will be mapped to the character at
    the same position in y.  If there is a third argument, it must be a string,
-   whose characters will be mapped to None in the result.
+   whose characters will be mapped to ``None`` in the result.
 
 
 .. method:: str.partition(sep)
@@ -2152,7 +2156,7 @@ The conversion types are:
 +------------+-----------------------------------------------------+-------+
 | ``'o'``    | Signed octal value.                                 | \(1)  |
 +------------+-----------------------------------------------------+-------+
-| ``'u'``    | Obsolete type -- it is identical to ``'d'``.        | \(7)  |
+| ``'u'``    | Obsolete type -- it is identical to ``'d'``.        | \(6)  |
 +------------+-----------------------------------------------------+-------+
 | ``'x'``    | Signed hexadecimal (lowercase).                     | \(2)  |
 +------------+-----------------------------------------------------+-------+
@@ -2193,15 +2197,12 @@ The conversion types are:
 Notes:
 
 (1)
-   The alternate form causes a leading zero (``'0'``) to be inserted between
-   left-hand padding and the formatting of the number if the leading character
-   of the result is not already a zero.
+   The alternate form causes a leading octal specifier (``'0o'``) to be
+   inserted before the first digit.
 
 (2)
    The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
-   the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
-   and the formatting of the number if the leading character of the result is not
-   already a zero.
+   the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit.
 
 (3)
    The alternate form causes the result to always contain a decimal point, even if
@@ -2220,8 +2221,7 @@ Notes:
 (5)
    If precision is ``N``, the output is truncated to ``N`` characters.
 
-
-(7)
+(6)
    See :pep:`237`.
 
 Since Python strings have an explicit length, ``%s`` conversions do not assume
@@ -3294,15 +3294,12 @@ The conversion types are:
 Notes:
 
 (1)
-   The alternate form causes a leading zero (``'0'``) to be inserted between
-   left-hand padding and the formatting of the number if the leading character
-   of the result is not already a zero.
+   The alternate form causes a leading octal specifier (``'0o'``) to be
+   inserted before the first digit.
 
 (2)
    The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
-   the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
-   and the formatting of the number if the leading character of the result is not
-   already a zero.
+   the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit.
 
 (3)
    The alternate form causes the result to always contain a decimal point, even if
@@ -3751,7 +3748,7 @@ copying.
       memory as an N-dimensional array.
 
       .. versionchanged:: 3.3
-         An empty tuple instead of None when ndim = 0.
+         An empty tuple instead of ``None`` when ndim = 0.
 
    .. attribute:: strides
 
@@ -3759,7 +3756,7 @@ copying.
       access each element for each dimension of the array.
 
       .. versionchanged:: 3.3
-         An empty tuple instead of None when ndim = 0.
+         An empty tuple instead of ``None`` when ndim = 0.
 
    .. attribute:: suboffsets
 
@@ -3866,17 +3863,17 @@ The constructors for both classes work the same:
       Test whether the set is a proper superset of *other*, that is, ``set >=
       other and set != other``.
 
-   .. method:: union(other, ...)
+   .. method:: union(*others)
                set | other | ...
 
       Return a new set with elements from the set and all others.
 
-   .. method:: intersection(other, ...)
+   .. method:: intersection(*others)
                set & other & ...
 
       Return a new set with elements common to the set and all others.
 
-   .. method:: difference(other, ...)
+   .. method:: difference(*others)
                set - other - ...
 
       Return a new set with elements in the set that are not in the others.
@@ -3926,17 +3923,17 @@ The constructors for both classes work the same:
    The following table lists operations available for :class:`set` that do not
    apply to immutable instances of :class:`frozenset`:
 
-   .. method:: update(other, ...)
+   .. method:: update(*others)
                set |= other | ...
 
       Update the set, adding elements from all others.
 
-   .. method:: intersection_update(other, ...)
+   .. method:: intersection_update(*others)
                set &= other & ...
 
       Update the set, keeping only elements found in it and all others.
 
-   .. method:: difference_update(other, ...)
+   .. method:: difference_update(*others)
                set -= other | ...
 
       Update the set, removing elements found in others.
@@ -4360,9 +4357,10 @@ an (external) *definition* for a module named *foo* somewhere.)
 A special attribute of every module is :attr:`~object.__dict__`. This is the
 dictionary containing the module's symbol table. Modifying this dictionary will
 actually change the module's symbol table, but direct assignment to the
-:attr:`__dict__` attribute is not possible (you can write
+:attr:`~object.__dict__` attribute is not possible (you can write
 ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but you can't write
-``m.__dict__ = {}``).  Modifying :attr:`__dict__` directly is not recommended.
+``m.__dict__ = {}``).  Modifying :attr:`~object.__dict__` directly is
+not recommended.
 
 Modules built into the interpreter are written like this: ``<module 'sys'
 (built-in)>``.  If loaded from a file, they are written as ``<module 'os' from
@@ -4575,14 +4573,16 @@ types, where they are relevant.  Some of these are not reported by the
    The tuple of base classes of a class object.
 
 
-.. attribute:: class.__name__
+.. attribute:: definition.__name__
 
-   The name of the class or type.
+   The name of the class, function, method, descriptor, or
+   generator instance.
 
 
-.. attribute:: class.__qualname__
+.. attribute:: definition.__qualname__
 
-   The :term:`qualified name` of the class or type.
+   The :term:`qualified name` of the class, function, method, descriptor,
+   or generator instance.
 
    .. versionadded:: 3.3
 
index d5d2430..05418a9 100644 (file)
@@ -431,7 +431,7 @@ The available integer presentation types are:
 
 In addition to the above presentation types, integers can be formatted
 with the floating point presentation types listed below (except
-``'n'`` and None). When doing so, :func:`float` is used to convert the
+``'n'`` and ``None``). When doing so, :func:`float` is used to convert the
 integer to a floating point number before formatting.
 
 The available presentation types for floating point and decimal values are:
index f469107..c1b28f8 100644 (file)
@@ -64,7 +64,7 @@ compatibility with older versions, see the :ref:`call-function-trio` section.
    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
+   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.
@@ -104,17 +104,17 @@ 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
+      :func:`run` was called with ``universal_newlines=True``. ``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
-      None.
+      ``None``.
 
    .. 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
+      :func:`run` was called with ``universal_newlines=True``. ``None`` if stderr
       was not captured.
 
    .. method:: check_returncode()
@@ -347,8 +347,8 @@ functions.
    manner described in :ref:`converting-argument-sequence`.  This is because
    the underlying ``CreateProcess()`` operates on strings.
 
-   The *shell* argument (which defaults to *False*) specifies whether to use
-   the shell as the program to execute.  If *shell* is *True*, it is
+   The *shell* argument (which defaults to ``False``) specifies whether to use
+   the shell as the program to execute.  If *shell* is ``True``, it is
    recommended to pass *args* as a string rather than as a sequence.
 
    On POSIX with ``shell=True``, the shell defaults to :file:`/bin/sh`.  If
@@ -950,20 +950,23 @@ been imported from the :mod:`subprocess` module.
 Replacing /bin/sh shell backquote
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-::
+.. code-block:: bash
 
    output=`mycmd myarg`
-   # becomes
-   output = check_output(["mycmd", "myarg"])
 
+becomes::
+
+   output = check_output(["mycmd", "myarg"])
 
 Replacing shell pipeline
 ^^^^^^^^^^^^^^^^^^^^^^^^
 
-::
+.. code-block:: bash
 
    output=`dmesg | grep hda`
-   # becomes
+
+becomes::
+
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
@@ -973,10 +976,14 @@ The p1.stdout.close() call after starting the p2 is important in order for p1
 to receive a SIGPIPE if p2 exits before p1.
 
 Alternatively, for trusted input, the shell's own pipeline support may still
-be used directly::
+be used directly:
+
+.. code-block:: bash
 
    output=`dmesg | grep hda`
-   # becomes
+
+becomes::
+
    output=check_output("dmesg | grep hda", shell=True)
 
 
index d0fd0a3..1ecc7a7 100644 (file)
@@ -158,7 +158,7 @@ AU_read objects, as returned by :func:`.open` above, have the following methods:
 
 .. method:: AU_read.readframes(n)
 
-   Reads and returns at most *n* frames of audio, as a string of bytes.  The data
+   Reads and returns at most *n* frames of audio, as a :class:`bytes` object.  The data
    will be returned in linear format.  If the original data is in u-LAW format, it
    will be converted.
 
index 9f70a13..d28ea5d 100644 (file)
@@ -256,7 +256,7 @@ always available.
    (defaulting to zero), or another type of object.  If it is an integer, zero
    is considered "successful termination" and any nonzero value is considered
    "abnormal termination" by shells and the like.  Most systems require it to be
-   in the range 0-127, and produce undefined results otherwise.  Some systems
+   in the range 0--127, and produce undefined results otherwise.  Some systems
    have a convention for assigning specific meanings to specific exit codes, but
    these are generally underdeveloped; Unix programs generally use 2 for command
    line syntax errors and 1 for all other kind of errors.  If another type of
@@ -1192,7 +1192,7 @@ always available.
    .. note::
        Under some conditions ``stdin``, ``stdout`` and ``stderr`` as well as the
        original values ``__stdin__``, ``__stdout__`` and ``__stderr__`` can be
-       None. It is usually the case for Windows GUI apps that aren't connected
+       ``None``. It is usually the case for Windows GUI apps that aren't connected
        to a console and Python apps started with :program:`pythonw`.
 
 
@@ -1282,7 +1282,9 @@ always available.
 
    A dictionary of the various implementation-specific flags passed through
    the :option:`-X` command-line option.  Option names are either mapped to
-   their values, if given explicitly, or to :const:`True`.  Example::
+   their values, if given explicitly, or to :const:`True`.  Example:
+
+   .. code-block:: shell-session
 
       $ ./python -Xa=b -Xc
       Python 3.2a3+ (py3k, Oct 16 2010, 20:14:50)
index 0b0df9b..02aaab3 100644 (file)
@@ -152,7 +152,7 @@ identifier.  Python currently uses eight paths:
    If *vars* is provided, it must be a dictionary of variables that will
    update the dictionary used to expand the paths.
 
-   If *expand* is set to False, the paths will not be expanded.
+   If *expand* is set to false, the paths will not be expanded.
 
    If *scheme* is not an existing scheme, :func:`get_paths` will raise a
    :exc:`KeyError`.
@@ -204,7 +204,9 @@ Other functions
 
 .. function:: is_python_build()
 
-   Return ``True`` if the current Python installation was built from source.
+   Return ``True`` if the running Python interpreter was built from source and
+   is being run from its built location, and not from a location resulting from
+   e.g. running ``make install`` or installing via a binary installer.
 
 
 .. function:: parse_config_h(fp[, vars])
@@ -229,7 +231,9 @@ Other functions
 Using :mod:`sysconfig` as a script
 ----------------------------------
 
-You can use :mod:`sysconfig` as a script with Python's *-m* option::
+You can use :mod:`sysconfig` as a script with Python's *-m* option:
+
+.. code-block:: shell-session
 
     $ python -m sysconfig
     Platform: "macosx-10.4-i386"
index 32d69bf..d8f8097 100644 (file)
@@ -64,19 +64,19 @@ Some facts and figures:
    | ``'x'`` or       | Create a tarfile exclusively without        |
    | ``'x:'``         | compression.                                |
    |                  | Raise an :exc:`FileExistsError` exception   |
-   |                  | if it is already exists.                    |
+   |                  | if it already exists.                       |
    +------------------+---------------------------------------------+
    | ``'x:gz'``       | Create a tarfile with gzip compression.     |
    |                  | Raise an :exc:`FileExistsError` exception   |
-   |                  | if it is already exists.                    |
+   |                  | if it already exists.                       |
    +------------------+---------------------------------------------+
    | ``'x:bz2'``      | Create a tarfile with bzip2 compression.    |
    |                  | Raise an :exc:`FileExistsError` exception   |
-   |                  | if it is already exists.                    |
+   |                  | if it already exists.                       |
    +------------------+---------------------------------------------+
    | ``'x:xz'``       | Create a tarfile with lzma compression.     |
    |                  | Raise an :exc:`FileExistsError` exception   |
-   |                  | if it is already exists.                    |
+   |                  | if it already exists.                       |
    +------------------+---------------------------------------------+
    | ``'a' or 'a:'``  | Open for appending with no compression. The |
    |                  | file is created if it does not exist.       |
@@ -148,8 +148,8 @@ Some facts and figures:
 
 .. class:: TarFile
 
-   Class for reading and writing tar archives. Do not use this class directly,
-   better use :func:`tarfile.open` instead. See :ref:`tarfile-objects`.
+   Class for reading and writing tar archives. Do not use this class directly:
+   use :func:`tarfile.open` instead. See :ref:`tarfile-objects`.
 
 
 .. function:: is_tarfile(name)
@@ -271,7 +271,7 @@ be finalized; only the internally used file object will be closed. See the
 
    *mode* is either ``'r'`` to read from an existing archive, ``'a'`` to append
    data to an existing file, ``'w'`` to create a new file overwriting an existing
-   one or ``'x'`` to create a new file only if it's not exists.
+   one, or ``'x'`` to create a new file only if it does not already exist.
 
    If *fileobj* is given, it is used for reading or writing data. If it can be
    determined, *mode* is overridden by *fileobj*'s mode. *fileobj* will be used
@@ -388,7 +388,7 @@ be finalized; only the internally used file object will be closed. See the
       dots ``".."``.
 
    .. versionchanged:: 3.5
-      Added the *numeric_only* parameter.
+      Added the *numeric_owner* parameter.
 
 
 .. method:: TarFile.extract(member, path="", set_attrs=True, *, numeric_owner=False)
@@ -416,7 +416,7 @@ be finalized; only the internally used file object will be closed. See the
       Added the *set_attrs* parameter.
 
    .. versionchanged:: 3.5
-      Added the *numeric_only* parameter.
+      Added the *numeric_owner* parameter.
 
 .. method:: TarFile.extractfile(member)
 
@@ -644,40 +644,51 @@ A :class:`TarInfo` object also provides some convenient query methods:
 
 
 .. _tarfile-commandline:
+.. program:: tarfile
 
-Command Line Interface
+Command-Line Interface
 ----------------------
 
 .. versionadded:: 3.4
 
-The :mod:`tarfile` module provides a simple command line interface to interact
+The :mod:`tarfile` module provides a simple command-line interface to interact
 with tar archives.
 
 If you want to create a new tar archive, specify its name after the :option:`-c`
-option and then list the filename(s) that should be included::
+option and then list the filename(s) that should be included:
+
+.. code-block:: shell-session
 
     $ python -m tarfile -c monty.tar  spam.txt eggs.txt
 
-Passing a directory is also acceptable::
+Passing a directory is also acceptable:
+
+.. code-block:: shell-session
 
     $ python -m tarfile -c monty.tar life-of-brian_1979/
 
 If you want to extract a tar archive into the current directory, use
-the :option:`-e` option::
+the :option:`-e` option:
+
+.. code-block:: shell-session
 
     $ python -m tarfile -e monty.tar
 
 You can also extract a tar archive into a different directory by passing the
-directory's name::
+directory's name:
+
+.. code-block:: shell-session
 
     $ python -m tarfile -e monty.tar  other-dir/
 
-For a list of the files in a tar archive, use the :option:`-l` option::
+For a list of the files in a tar archive, use the :option:`-l` option:
+
+.. code-block:: shell-session
 
     $ python -m tarfile -l monty.tar
 
 
-Command line options
+Command-line options
 ~~~~~~~~~~~~~~~~~~~~
 
 .. cmdoption:: -l <tarfile>
@@ -685,8 +696,8 @@ Command line options
 
    List files in a tarfile.
 
-.. cmdoption:: -c <tarfile> <source1> <sourceN>
-               --create <tarfile> <source1> <sourceN>
+.. cmdoption:: -c <tarfile> <source1> ... <sourceN>
+               --create <tarfile> <source1> ... <sourceN>
 
    Create tarfile from source files.
 
@@ -702,7 +713,7 @@ Command line options
 
 .. cmdoption:: -v, --verbose
 
-   Verbose output
+   Verbose output.
 
 .. _tar-examples:
 
index 2ea9c27..59577f0 100644 (file)
@@ -398,7 +398,7 @@ The :mod:`test.support` module defines the following functions:
    A context manager that creates a temporary directory at *path* and
    yields the directory.
 
-   If *path* is None, the temporary directory is created using
+   If *path* is ``None``, the temporary directory is created using
    :func:`tempfile.mkdtemp`.  If *quiet* is ``False``, the context manager
    raises an exception on error.  Otherwise, if *path* is specified and
    cannot be created, only a warning is issued.
@@ -421,7 +421,7 @@ The :mod:`test.support` module defines the following functions:
 
    The context manager creates a temporary directory in the current
    directory with name *name* before temporarily changing the current
-   working directory.  If *name* is None, the temporary directory is
+   working directory.  If *name* is ``None``, the temporary directory is
    created using :func:`tempfile.mkdtemp`.
 
    If *quiet* is ``False`` and it is not possible to create or change
index 3066496..2792dfd 100644 (file)
@@ -256,7 +256,7 @@ since it is impossible to detect the termination of alien threads.
 
       Wait until the thread terminates. This blocks the calling thread until
       the thread whose :meth:`~Thread.join` method is called terminates -- either
-      normally or through an unhandled exception --, or until the optional
+      normally or through an unhandled exception -- or until the optional
       timeout occurs.
 
       When the *timeout* argument is present and not ``None``, it should be a
@@ -615,7 +615,7 @@ item to the buffer only needs to wake up one consumer thread.
 
    .. method:: wait_for(predicate, timeout=None)
 
-      Wait until a condition evaluates to True.  *predicate* should be a
+      Wait until a condition evaluates to true.  *predicate* should be a
       callable which result will be interpreted as a boolean value.
       A *timeout* may be provided giving the maximum time to wait.
 
@@ -714,7 +714,7 @@ Semaphores also support the :ref:`context management protocol <with-locks>`.
       without an argument would block, return false immediately; otherwise,
       do the same thing as when called without arguments, and return true.
 
-      When invoked with a *timeout* other than None, it will block for at
+      When invoked with a *timeout* other than ``None``, it will block for at
       most *timeout* seconds.  If acquire does not complete successfully in
       that interval, return false.  Return true otherwise.
 
@@ -854,8 +854,8 @@ For example::
 
    Create a timer that will run *function* with arguments *args* and  keyword
    arguments *kwargs*, after *interval* seconds have passed.
-   If *args* is None (the default) then an empty list will be used.
-   If *kwargs* is None (the default) then an empty dict will be used.
+   If *args* is ``None`` (the default) then an empty list will be used.
+   If *kwargs* is ``None`` (the default) then an empty dict will be used.
 
    .. versionchanged:: 3.3
       changed from a factory function to a class.
index 130aafe..3e1faed 100644 (file)
@@ -199,19 +199,19 @@ A Simple Hello World Program
 
     class Application(tk.Frame):
         def __init__(self, master=None):
-            tk.Frame.__init__(self, master)
+            super().__init__(master)
             self.pack()
-            self.createWidgets()
+            self.create_widgets()
 
-        def createWidgets(self):
+        def create_widgets(self):
             self.hi_there = tk.Button(self)
             self.hi_there["text"] = "Hello World\n(click me)"
             self.hi_there["command"] = self.say_hi
             self.hi_there.pack(side="top")
 
-            self.QUIT = tk.Button(self, text="QUIT", fg="red",
+            self.quit = tk.Button(self, text="QUIT", fg="red",
                                   command=root.destroy)
-            self.QUIT.pack(side="bottom")
+            self.quit.pack(side="bottom")
 
         def say_hi(self):
             print("hi there, everyone!")
@@ -536,7 +536,7 @@ For example::
 
    class App(Frame):
        def __init__(self, master=None):
-           Frame.__init__(self, master)
+           super().__init__(master)
            self.pack()
 
            self.entrythingy = Entry()
@@ -581,13 +581,13 @@ part of the implementation, and not an interface to Tk functionality.
 
 Here are some examples of typical usage::
 
-   from tkinter import *
-   class App(Frame):
+   import tkinter as tk
+
+   class App(tk.Frame):
        def __init__(self, master=None):
-           Frame.__init__(self, master)
+           super().__init__(master)
            self.pack()
 
-
    # create the application
    myapp = App()
 
@@ -708,13 +708,13 @@ add
 
 For example::
 
-   def turnRed(self, event):
+   def turn_red(self, event):
        event.widget["activeforeground"] = "red"
 
-   self.button.bind("<Enter>", self.turnRed)
+   self.button.bind("<Enter>", self.turn_red)
 
 Notice how the widget field of the event is being accessed in the
-:meth:`turnRed` callback.  This field contains the widget that caught the X
+``turn_red()`` callback.  This field contains the widget that caught the X
 event.  The following table lists the other event fields you can access, and how
 they are denoted in Tk, which can be useful when referring to the Tk man pages.
 
index dbb5bd2..3dad182 100644 (file)
@@ -1404,7 +1404,7 @@ option. If you don't know the class name of a widget, use the method
 Layouts
 ^^^^^^^
 
-A layout can be just None, if it takes no options, or a dict of
+A layout can be just ``None``, if it takes no options, or a dict of
 options specifying how to arrange the element. The layout mechanism
 uses a simplified version of the pack geometry manager: given an
 initial cavity, each element is allocated a parcel. Valid
index 116efca..effb711 100644 (file)
@@ -108,10 +108,3 @@ The token constants are:
       Added :data:`AWAIT` and :data:`ASYNC` tokens. Starting with
       Python 3.7, "async" and "await" will be tokenized as :data:`NAME`
       tokens, and :data:`AWAIT` and :data:`ASYNC` will be removed.
-
-.. seealso::
-
-   Module :mod:`parser`
-      The second example for the :mod:`parser` module shows how to use the
-      :mod:`symbol` module.
-
index 6ec9ada..3c1d9bb 100644 (file)
@@ -361,7 +361,7 @@ exception and traceback:
        traceback.print_exception(exc_type, exc_value, exc_traceback,
                                  limit=2, file=sys.stdout)
        print("*** print_exc:")
-       traceback.print_exc()
+       traceback.print_exc(limit=2, file=sys.stdout)
        print("*** format_exc, first and last line:")
        formatted_lines = traceback.format_exc().splitlines()
        print(formatted_lines[0])
@@ -407,9 +407,9 @@ The output for the example would look similar to this:
     '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n',
     'IndexError: tuple index out of range\n']
    *** extract_tb:
-   [('<doctest...>', 10, '<module>', 'lumberjack()'),
-    ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
-    ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
+   [<FrameSummary file <doctest...>, line 10 in <module>>,
+    <FrameSummary file <doctest...>, line 4 in lumberjack>,
+    <FrameSummary file <doctest...>, line 7 in bright_side_of_death>]
    *** format_tb:
    ['  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
     '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
index 3a0b1e0..2c8ad0e 100644 (file)
@@ -66,7 +66,7 @@ Example of output of the Python test suite::
     <string>:5: size=49.7 KiB, count=148, average=344 B
     /usr/lib/python3.4/sysconfig.py:411: size=48.0 KiB, count=1, average=48.0 KiB
 
-We can see that Python loaded ``4.8 MiB`` data (bytecode and constants) from
+We can see that Python loaded ``4855 KiB`` data (bytecode and constants) from
 modules and that the :mod:`collections` module allocated ``244 KiB`` to build
 :class:`~collections.namedtuple` types.
 
@@ -106,8 +106,8 @@ Example of output before/after running some tests of the Python test suite::
     /usr/lib/python3.4/urllib/parse.py:476: size=71.8 KiB (+71.8 KiB), count=969 (+969), average=76 B
     /usr/lib/python3.4/contextlib.py:38: size=67.2 KiB (+67.2 KiB), count=126 (+126), average=546 B
 
-We can see that Python has loaded ``8.2 MiB`` of module data (bytecode and
-constants), and that this is ``4.4 MiB`` more than had been loaded before the
+We can see that Python has loaded ``8173 KiB`` of module data (bytecode and
+constants), and that this is ``4428 KiB`` more than had been loaded before the
 tests, when the previous snapshot was taken. Similarly, the :mod:`linecache`
 module has cached ``940 KiB`` of Python source code to format tracebacks, all
 of it since the previous snapshot.
@@ -176,7 +176,7 @@ Example of output of the Python test suite (traceback limited to 25 frames)::
         "__main__", fname, loader, pkg_name)
 
 We can see that the most memory was allocated in the :mod:`importlib` module to
-load data (bytecode and constants) from modules: ``870 KiB``. The traceback is
+load data (bytecode and constants) from modules: ``870.1 KiB``. The traceback is
 where the :mod:`importlib` loaded data most recently: on the ``import pdb``
 line of the :mod:`doctest` module. The traceback may change if a new module is
 loaded.
@@ -192,12 +192,12 @@ ignoring ``<frozen importlib._bootstrap>`` and ``<unknown>`` files::
     import os
     import tracemalloc
 
-    def display_top(snapshot, group_by='lineno', limit=10):
+    def display_top(snapshot, key_type='lineno', limit=10):
         snapshot = snapshot.filter_traces((
             tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
             tracemalloc.Filter(False, "<unknown>"),
         ))
-        top_stats = snapshot.statistics(group_by)
+        top_stats = snapshot.statistics(key_type)
 
         print("Top %s lines" % limit)
         for index, stat in enumerate(top_stats[:limit], 1):
@@ -438,12 +438,12 @@ Snapshot
 
    The :func:`take_snapshot` function creates a snapshot instance.
 
-   .. method:: compare_to(old_snapshot: Snapshot, group_by: str, cumulative: bool=False)
+   .. method:: compare_to(old_snapshot: Snapshot, key_type: str, cumulative: bool=False)
 
       Compute the differences with an old snapshot. Get statistics as a sorted
-      list of :class:`StatisticDiff` instances grouped by *group_by*.
+      list of :class:`StatisticDiff` instances grouped by *key_type*.
 
-      See the :meth:`Snapshot.statistics` method for *group_by* and *cumulative*
+      See the :meth:`Snapshot.statistics` method for *key_type* and *cumulative*
       parameters.
 
       The result is sorted from the biggest to the smallest by: absolute value
@@ -478,13 +478,13 @@ Snapshot
       See also :meth:`dump`.
 
 
-   .. method:: statistics(group_by: str, cumulative: bool=False)
+   .. method:: statistics(key_type: str, cumulative: bool=False)
 
       Get statistics as a sorted list of :class:`Statistic` instances grouped
-      by *group_by*:
+      by *key_type*:
 
       =====================  ========================
-      group_by               description
+      key_type               description
       =====================  ========================
       ``'filename'``         filename
       ``'lineno'``           filename and line number
@@ -493,7 +493,7 @@ Snapshot
 
       If *cumulative* is ``True``, cumulate size and count of memory blocks of
       all frames of the traceback of a trace, not only the most recent frame.
-      The cumulative mode can only be used with *group_by* equals to
+      The cumulative mode can only be used with *key_type* equals to
       ``'filename'`` and ``'lineno'``.
 
       The result is sorted from the biggest to the smallest by:
index e4a82ea..1986972 100644 (file)
@@ -549,7 +549,7 @@ Turtle motion
 
    :param n: an integer (or ``None``)
 
-   Delete all or first/last *n* of turtle's stamps.  If *n* is None, delete
+   Delete all or first/last *n* of turtle's stamps.  If *n* is ``None``, delete
    all stamps, if *n* > 0 delete first *n* stamps, else if *n* < 0 delete
    last *n* stamps.
 
@@ -1799,7 +1799,7 @@ Input methods
    Pop up a dialog window for input of a string. Parameter title is
    the title of the dialog window, propmt is a text mostly describing
    what information to input.
-   Return the string input. If the dialog is canceled, return None. ::
+   Return the string input. If the dialog is canceled, return ``None``. ::
 
       >>> screen.textinput("NIM", "Name of first player:")
 
@@ -1819,7 +1819,7 @@ Input methods
    The number input must be in the range minval .. maxval if these are
    given. If not, a hint is issued and the dialog remains open for
    correction.
-   Return the number input. If the dialog is canceled,  return None. ::
+   Return the number input. If the dialog is canceled,  return ``None``. ::
 
       >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
 
@@ -1984,10 +1984,10 @@ Methods specific to Screen, not inherited from TurtleScreen
    :param height: if an integer, the height in pixels, if a float, a fraction of
                   the screen; default is 75% of screen
    :param startx: if positive, starting position in pixels from the left
-                  edge of the screen, if negative from the right edge, if None,
+                  edge of the screen, if negative from the right edge, if ``None``,
                   center window horizontally
    :param starty: if positive, starting position in pixels from the top
-                  edge of the screen, if negative from the bottom edge, if None,
+                  edge of the screen, if negative from the bottom edge, if ``None``,
                   center window vertically
 
    .. doctest::
index 731e2ec..923cbb8 100644 (file)
@@ -11,8 +11,8 @@
 --------------
 
 This module supports type hints as specified by :pep:`484`.  The most
-fundamental support consists of the type :class:`Any`, :class:`Union`,
-:class:`Tuple`, :class:`Callable`, :class:`TypeVar`, and
+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`.
 
@@ -29,10 +29,110 @@ arguments.
 Type aliases
 ------------
 
-A type alias is defined by assigning the type to the alias::
+A type alias is defined by assigning the type to the alias. In this example,
+``Vector`` and ``List[float]`` will be treated as interchangeable synonyms::
 
+   from typing import List
    Vector = List[float]
 
+   def scale(scalar: float, vector: Vector) -> Vector:
+       return [scalar * num for num in vector]
+
+   # typechecks; a list of floats qualifies as a Vector.
+   new_vector = scale(2.0, [1.0, -4.2, 5.4])
+
+Type aliases are useful for simplifying complex type signatures. For example::
+
+   from typing import Dict, Tuple, List
+
+   ConnectionOptions = Dict[str, str]
+   Address = Tuple[str, int]
+   Server = Tuple[Address, ConnectionOptions]
+
+   def broadcast_message(message: str, servers: List[Server]) -> None:
+       ...
+
+   # The static type checker will treat the previous type signature as
+   # being exactly equivalent to this one.
+   def broadcast_message(
+           message: str,
+           servers: List[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
+       ...
+
+Note that ``None`` as a type hint is a special case and is replaced by
+``type(None)``.
+
+.. _distinct:
+
+NewType
+-------
+
+Use the :func:`NewType` helper function to create distinct types::
+
+   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. This is useful in helping catch logical errors::
+
+   def get_user_name(user_id: UserId) -> str:
+       ...
+
+   # typechecks
+   user_a = get_user_name(UserId(42351))
+
+   # does not typecheck; an int is not a UserId
+   user_b = get_user_name(-1)
+
+You may still perform all ``int`` operations on a variable of type ``UserId``,
+but the result will always be of type ``int``. This lets you pass in a
+``UserId`` wherever an ``int`` might be expected, but will prevent you from
+accidentally creating a ``UserId`` in an invalid way::
+
+   # 'output' is of type 'int', not 'UserId'
+   output = UserId(23413) + UserId(54341)
+
+Note that these checks are enforced only by the static type checker. At runtime
+the statement ``Derived = NewType('Derived', Base)`` will make ``Derived`` a
+function that immediately returns whatever parameter you pass it. That means
+the expression ``Derived(some_value)`` does not create a new class or introduce
+any overhead beyond that of a regular function call.
+
+More precisely, the expression ``some_value is Derived(some_value)`` is always
+true at runtime.
+
+This also means that it is not possible to create a subtype of ``Derived``
+since it is an identity function at runtime, not an actual type. Similarly, it
+is not possible to create another :func:`NewType` based on a ``Derived`` type::
+
+   from typing import NewType
+
+   UserId = NewType('UserId', int)
+
+   # Fails at runtime and does not typecheck
+   class AdminUserId(UserId): pass
+
+   # Also does not typecheck
+   ProUserId = NewType('ProUserId', UserId)
+
+See :pep:`484` for more details.
+
+.. note::
+
+   Recall that the use of a type alias declares two types to be *equivalent* to
+   one another. Doing ``Alias = Original`` will make the static type checker
+   treat ``Alias`` as being *exactly equivalent* to ``Original`` in all cases.
+   This is useful when you want to simplify complex type signatures.
+
+   In contrast, ``NewType`` declares one type to be a *subtype* of another.
+   Doing ``Derived = NewType('Derived', Original)`` will make the static type
+   checker treat ``Derived`` as a *subclass* of ``Original``, which means a
+   value of type ``Original`` cannot be used in places where a value of type
+   ``Derived`` is expected. This is useful when you want to prevent logic
+   errors with minimal runtime cost.
+
 Callable
 --------
 
@@ -53,7 +153,6 @@ For example::
 It is possible to declare the return type of a callable without specifying
 the call signature by substituting a literal ellipsis
 for the list of arguments in the type hint: ``Callable[..., ReturnType]``.
-``None`` as a type hint is a special case and is replaced by ``type(None)``.
 
 Generics
 --------
@@ -109,7 +208,7 @@ A user-defined class can be defined as a generic class.
            return self.value
 
        def log(self, message: str) -> None:
-           self.logger.info('{}: {}'.format(self.name, message))
+           self.logger.info('%s: %s', self.name, message)
 
 ``Generic[T]`` as a base class defines that the class ``LoggedVar`` takes a
 single type parameter ``T`` . This also makes ``T`` valid as a type within the
@@ -167,48 +266,119 @@ When inheriting from generic classes, some type variables could be fixed::
 
 In this case ``MyDict`` has a single parameter, ``T``.
 
-Subclassing a generic class without specifying type parameters assumes
-:class:`Any` for each position. In the following example, ``MyIterable`` is
+Using a generic class without specifying type parameters assumes
+:data:`Any` for each position. In the following example, ``MyIterable`` is
 not generic but implicitly inherits from ``Iterable[Any]``::
 
    from typing import Iterable
 
    class MyIterable(Iterable): # Same as Iterable[Any]
 
+User defined generic type aliases are also supported. Examples::
+
+   from typing import TypeVar, Iterable, Tuple, Union
+   S = TypeVar('S')
+   Response = Union[Iterable[S], int]
+
+   # Return type here is same as Union[Iterable[str], int]
+   def response(query: str) -> Response[str]:
+       ...
+
+   T = TypeVar('T', int, float, complex)
+   Vec = Iterable[Tuple[T, T]]
+
+   def inproduct(v: Vec[T]) -> T: # Same as Iterable[Tuple[T, T]]
+       return sum(x*y for x, y in v)
+
 The metaclass used by :class:`Generic` is a subclass of :class:`abc.ABCMeta`.
 A generic class can be an ABC by including abstract methods or properties,
 and generic classes can also have ABCs as base classes without a metaclass
-conflict.  Generic metaclasses are not supported.
+conflict. Generic metaclasses are not supported. The outcome of parameterizing
+generics is cached, and most types in the typing module are hashable and
+comparable for equality.
 
 
-The :class:`Any` type
+The :data:`Any` type
 ---------------------
 
-A special kind of type is :class:`Any`. Every type is a subtype of
-:class:`Any`. This is also true for the builtin type object. However, to the
-static type checker these are completely different.
+A special kind of type is :data:`Any`. A static type checker will treat
+every type as being compatible with :data:`Any` and :data:`Any` as being
+compatible with every type.
 
-When the type of a value is :class:`object`, the type checker will reject
-almost all operations on it, and assigning it to a variable (or using it as a
-return value) of a more specialized type is a type error. On the other hand,
-when a value has type :class:`Any`, the type checker will allow all operations
-on it, and a value of type :class:`Any` can be assigned to a variable (or used
-as a return value) of a more constrained type.
+This means that it is possible to perform any operation or method call on a
+value of type on :data:`Any` and assign it to any variable::
 
+   from typing import Any
 
-Classes, functions, and decorators
-----------------------------------
+   a = None    # type: Any
+   a = []      # OK
+   a = 2       # OK
 
-The module defines the following classes, functions and decorators:
+   s = ''      # type: str
+   s = a       # OK
 
-.. class:: Any
+   def foo(item: Any) -> int:
+       # Typechecks; 'item' could be any type,
+       # and that type might have a 'bar' method
+       item.bar()
+       ...
 
-   Special type indicating an unconstrained type.
+Notice that no typechecking is performed when assigning a value of type
+:data:`Any` to a more precise type. For example, the static type checker did
+not report an error when assigning ``a`` to ``s`` even though ``s`` was
+declared to be of type :class:`str` and receives an :class:`int` value at
+runtime!
+
+Furthermore, all functions without a return type or parameter types will
+implicitly default to using :data:`Any`::
+
+   def legacy_parser(text):
+       ...
+       return data
+
+   # A static type checker will treat the above
+   # as having the same signature as:
+   def legacy_parser(text: Any) -> Any:
+       ...
+       return data
+
+This behavior allows :data:`Any` to be used as an *escape hatch* when you
+need to mix dynamically and statically typed code.
+
+Contrast the behavior of :data:`Any` with the behavior of :class:`object`.
+Similar to :data:`Any`, every type is a subtype of :class:`object`. However,
+unlike :data:`Any`, the reverse is not true: :class:`object` is *not* a
+subtype of every other type.
+
+That means when the type of a value is :class:`object`, a type checker will
+reject almost all operations on it, and assigning it to a variable (or using
+it as a return value) of a more specialized type is a type error. For example::
+
+   def hash_a(item: object) -> int:
+       # Fails; an object does not have a 'magic' method.
+       item.magic()
+       ...
+
+   def hash_b(item: Any) -> int:
+       # Typechecks
+       item.magic()
+       ...
+
+   # Typechecks, since ints and strs are subclasses of object
+   hash_a(42)
+   hash_a("foo")
+
+   # Typechecks, since Any is compatible with all types
+   hash_b(42)
+   hash_b("foo")
+
+Use :class:`object` to indicate that a value could be any type in a typesafe
+manner. Use :data:`Any` to indicate that a value is dynamically typed.
+
+Classes, functions, and decorators
+----------------------------------
 
-   * Any object is an instance of :class:`Any`.
-   * Any class is a subclass of :class:`Any`.
-   * As a special case, :class:`Any` and :class:`object` are subclasses of
-     each other.
+The module defines the following classes, functions and decorators:
 
 .. class:: TypeVar
 
@@ -248,79 +418,6 @@ The module defines the following classes, functions and decorators:
     for the type variable must be a subclass of the boundary type,
     see :pep:`484`.
 
-.. class:: Union
-
-   Union type; ``Union[X, Y]`` means either X or Y.
-
-   To define a union, use e.g. ``Union[int, str]``.  Details:
-
-   * The arguments must be types and there must be at least one.
-
-   * Unions of unions are flattened, e.g.::
-
-       Union[Union[int, str], float] == Union[int, str, float]
-
-   * Unions of a single argument vanish, e.g.::
-
-       Union[int] == int  # The constructor actually returns int
-
-   * Redundant arguments are skipped, e.g.::
-
-       Union[int, str, int] == Union[int, str]
-
-   * When comparing unions, the argument order is ignored, e.g.::
-
-       Union[int, str] == Union[str, int]
-
-   * If :class:`Any` is present it is the sole survivor, e.g.::
-
-       Union[int, Any] == Any
-
-   * You cannot subclass or instantiate a union.
-
-   * You cannot write ``Union[X][Y]``.
-
-   * You can use ``Optional[X]`` as a shorthand for ``Union[X, None]``.
-
-.. class:: Optional
-
-   Optional type.
-
-   ``Optional[X]`` is equivalent to ``Union[X, type(None)]``.
-
-   Note that this is not the same concept as an optional argument,
-   which is one that has a default.  An optional argument with a
-   default needn't use the ``Optional`` qualifier on its type
-   annotation (although it is inferred if the default is ``None``).
-   A mandatory argument may still have an ``Optional`` type if an
-   explicit value of ``None`` is allowed.
-
-.. class:: Tuple
-
-  Tuple type; ``Tuple[X, Y]`` is the type of a tuple of two items
-  with the first item of type X and the second of type Y.
-
-  Example: ``Tuple[T1, T2]`` is a tuple of two elements corresponding
-  to type variables T1 and T2.  ``Tuple[int, float, str]`` is a tuple
-  of an int, a float and a string.
-
-  To specify a variable-length tuple of homogeneous type,
-  use literal ellipsis, e.g. ``Tuple[int, ...]``.
-
-.. class:: Callable
-
-   Callable type; ``Callable[[int], str]`` is a function of (int) -> str.
-
-   The subscription syntax must always be used with exactly two
-   values: the argument list and the return type.  The argument list
-   must be a list of types; the return type must be a single type.
-
-   There is no syntax to indicate optional or keyword arguments,
-   such function types are rarely used as callback types.
-   ``Callable[..., ReturnType]`` could be used to type hint a callable
-   taking any number of arguments and returning ``ReturnType``.
-   A plain :class:`Callable` is equivalent to ``Callable[..., Any]``.
-
 .. class:: Generic
 
    Abstract base class for generic types.
@@ -345,13 +442,56 @@ The module defines the following classes, functions and decorators:
           except KeyError:
               return default
 
+.. class:: Type(Generic[CT_co])
+
+   A variable annotated with ``C`` may accept a value of type ``C``. In
+   contrast, a variable annotated with ``Type[C]`` may accept values that are
+   classes themselves -- specifically, it will accept the *class object* of
+   ``C``. For example::
+
+      a = 3         # Has type 'int'
+      b = int       # Has type 'Type[int]'
+      c = type(a)   # Also has type 'Type[int]'
+
+   Note that ``Type[C]`` is covariant::
+
+      class User: ...
+      class BasicUser(User): ...
+      class ProUser(User): ...
+      class TeamUser(User): ...
+
+      # Accepts User, BasicUser, ProUser, TeamUser, ...
+      def make_new_user(user_class: Type[User]) -> User:
+          # ...
+          return user_class()
+
+   The fact that ``Type[C]`` is covariant implies that all subclasses of
+   ``C`` should implement the same constructor signature and class method
+   signatures as ``C``. The type checker should flag violations of this,
+   but should also allow constructor calls in subclasses that match the
+   constructor calls in the indicated base class. How the type checker is
+   required to handle this particular case may change in future revisions of
+   :pep:`484`.
+
+   The only legal parameters for :class:`Type` are classes, unions of classes, and
+   :data:`Any`. For example::
+
+      def new_non_team_user(user_class: Type[Union[BaseUser, ProUser]]): ...
+
+   ``Type[Any]`` is equivalent to ``Type`` which in turn is equivalent
+   to ``type``, which is the root of Python's metaclass hierarchy.
+
 .. class:: Iterable(Generic[T_co])
 
-    A generic version of the :class:`collections.abc.Iterable`.
+    A generic version of :class:`collections.abc.Iterable`.
 
 .. class:: Iterator(Iterable[T_co])
 
-    A generic version of the :class:`collections.abc.Iterator`.
+    A generic version of :class:`collections.abc.Iterator`.
+
+.. class:: Reversible(Iterable[T_co])
+
+    A generic version of :class:`collections.abc.Reversible`.
 
 .. class:: SupportsInt
 
@@ -371,15 +511,18 @@ The module defines the following classes, functions and decorators:
     An ABC with one abstract method ``__round__``
     that is covariant in its return type.
 
-.. class:: Reversible
-
-    An ABC with one abstract method ``__reversed__`` returning
-    an ``Iterator[T_co]``.
-
 .. class:: Container(Generic[T_co])
 
     A generic version of :class:`collections.abc.Container`.
 
+.. class:: Hashable
+
+   An alias to :class:`collections.abc.Hashable`
+
+.. class:: Sized
+
+   An alias to :class:`collections.abc.Sized`
+
 .. class:: AbstractSet(Sized, Iterable[T_co], Container[T_co])
 
     A generic version of :class:`collections.abc.Set`.
@@ -428,13 +571,17 @@ The module defines the following classes, functions and decorators:
       def vec2(x: T, y: T) -> List[T]:
           return [x, y]
 
-      def slice__to_4(vector: Sequence[T]) -> List[T]:
-          return vector[0:4]
+      def keep_positives(vector: Sequence[T]) -> List[T]:
+          return [item for item in vector if item > 0]
 
 .. class:: Set(set, MutableSet[T])
 
    A generic version of :class:`builtins.set <set>`.
 
+.. class:: FrozenSet(frozenset, AbstractSet[T_co])
+
+   A generic version of :class:`builtins.frozenset <frozenset>`.
+
 .. class:: MappingView(Sized, Iterable[T_co])
 
    A generic version of :class:`collections.abc.MappingView`.
@@ -451,6 +598,31 @@ The module defines the following classes, functions and decorators:
 
    A generic version of :class:`collections.abc.ValuesView`.
 
+.. class:: Awaitable(Generic[T_co])
+
+   A generic version of :class:`collections.abc.Awaitable`.
+
+.. class:: Coroutine(Awaitable[V_co], Generic[T_co T_contra, V_co])
+
+   A generic version of :class:`collections.abc.Coroutine`.
+   The variance and order of type variables
+   correspond to those of :class:`Generator`, for example::
+
+      from typing import List, Coroutine
+      c = None # type: Coroutine[List[str], str, int]
+      ...
+      x = c.send('hi') # type: List[str]
+      async def bar() -> None:
+          x = await c # type: int
+
+.. class:: AsyncIterable(Generic[T_co])
+
+   A generic version of :class:`collections.abc.AsyncIterable`.
+
+.. class:: AsyncIterator(AsyncIterable[T_co])
+
+  A generic version of :class:`collections.abc.AsyncIterator`.
+
 .. class:: Dict(dict, MutableMapping[KT, VT])
 
    A generic version of :class:`dict`.
@@ -459,8 +631,53 @@ The module defines the following classes, functions and decorators:
       def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
           return word_list[word]
 
+.. class:: DefaultDict(collections.defaultdict, MutableMapping[KT, VT])
+
+   A generic version of :class:`collections.defaultdict`
+
 .. class:: Generator(Iterator[T_co], Generic[T_co, T_contra, V_co])
 
+   A generator can be annotated by the generic type
+   ``Generator[YieldType, SendType, ReturnType]``. For example::
+
+      def echo_round() -> Generator[int, float, str]:
+          sent = yield 0
+          while sent >= 0:
+              sent = yield round(sent)
+          return 'Done'
+
+   Note that unlike many other generics in the typing module, the ``SendType``
+   of :class:`Generator` behaves contravariantly, not covariantly or
+   invariantly.
+
+   If your generator will only yield values, set the ``SendType`` and
+   ``ReturnType`` to ``None``::
+
+      def infinite_stream(start: int) -> Generator[int, None, None]:
+          while True:
+              yield start
+              start += 1
+
+   Alternatively, annotate your generator as having a return type of
+   either ``Iterable[YieldType]`` or ``Iterator[YieldType]``::
+
+      def infinite_stream(start: int) -> Iterator[int]:
+          while True:
+              yield start
+              start += 1
+
+.. class:: Text
+
+   ``Text`` is an alias for ``str``. It is provided to supply a forward
+   compatible path for Python 2 code: in Python 2, ``Text`` is an alias for
+   ``unicode``.
+
+   Use ``Text`` to indicate that a value must contain a unicode string in
+   a manner that is compatible with both Python 2 and Python 3::
+
+       def add_unicode_checkmark(text: Text) -> Text:
+           return text + u' \u2713'
+
 .. class:: io
 
    Wrapper namespace for I/O stream types.
@@ -498,6 +715,15 @@ The module defines the following classes, functions and decorators:
    are in the _fields attribute, which is part of the namedtuple
    API.)
 
+.. function:: NewType(typ)
+
+   A helper function to indicate a distinct types to a typechecker,
+   see :ref:`distinct`. At runtime it returns a function that returns
+   its argument. Usage::
+
+      UserId = NewType('UserId', int)
+      first_user = UserId(1)
+
 .. function:: cast(typ, val)
 
    Cast a value to a type.
@@ -507,13 +733,46 @@ The module defines the following classes, functions and decorators:
    runtime we intentionally don't check anything (we want this
    to be as fast as possible).
 
-.. function:: get_type_hints(obj)
-
-   Return type hints for a function or method object.
-
-   This is often the same as ``obj.__annotations__``, but it handles
-   forward references encoded as string literals, and if necessary
-   adds ``Optional[t]`` if a default value equal to None is set.
+.. function:: get_type_hints(obj[, globals[, locals]])
+
+   Return a dictionary containing type hints for a function, method, module
+   or class object.
+
+   This is often the same as ``obj.__annotations__``. In addition,
+   forward references encoded as string literals are handled by evaluating
+   them in ``globals`` and ``locals`` namespaces. If necessary,
+   ``Optional[t]`` is added for function and method annotations if a default
+   value equal to ``None`` is set. For a class ``C``, return
+   a dictionary constructed by merging all the ``__annotations__`` along
+   ``C.__mro__`` in reverse order.
+
+.. decorator:: overload
+
+   The ``@overload`` decorator allows describing functions and methods
+   that support multiple different combinations of argument types. A series
+   of ``@overload``-decorated definitions must be followed by exactly one
+   non-``@overload``-decorated definition (for the same function/method).
+   The ``@overload``-decorated definitions are for the benefit of the
+   type checker only, since they will be overwritten by the
+   non-``@overload``-decorated definition, while the latter is used at
+   runtime but should be ignored by a type checker.  At runtime, calling
+   a ``@overload``-decorated function directly will raise
+   ``NotImplementedError``. An example of overload that gives a more
+   precise type than can be expressed using a union or a type variable::
+
+      @overload
+      def process(response: None) -> None:
+          ...
+      @overload
+      def process(response: int) -> Tuple[int, str]:
+          ...
+      @overload
+      def process(response: bytes) -> str:
+          ...
+      def process(response):
+          <actual implementation>
+
+   See :pep:`484` for details and comparison with other typing semantics.
 
 .. decorator:: no_type_check(arg)
 
@@ -531,3 +790,139 @@ The module defines the following classes, functions and decorators:
 
    This wraps the decorator with something that wraps the decorated
    function in :func:`no_type_check`.
+
+.. data:: Any
+
+   Special type indicating an unconstrained type.
+
+   * Every type is compatible with :data:`Any`.
+   * :data:`Any` is compatible with every type.
+
+.. data:: Union
+
+   Union type; ``Union[X, Y]`` means either X or Y.
+
+   To define a union, use e.g. ``Union[int, str]``.  Details:
+
+   * The arguments must be types and there must be at least one.
+
+   * Unions of unions are flattened, e.g.::
+
+       Union[Union[int, str], float] == Union[int, str, float]
+
+   * Unions of a single argument vanish, e.g.::
+
+       Union[int] == int  # The constructor actually returns int
+
+   * Redundant arguments are skipped, e.g.::
+
+       Union[int, str, int] == Union[int, str]
+
+   * When comparing unions, the argument order is ignored, e.g.::
+
+       Union[int, str] == Union[str, int]
+
+   * When a class and its subclass are present, the former is skipped, e.g.::
+
+       Union[int, object] == object
+
+   * You cannot subclass or instantiate a union.
+
+   * You cannot write ``Union[X][Y]``.
+
+   * You can use ``Optional[X]`` as a shorthand for ``Union[X, None]``.
+
+.. data:: Optional
+
+   Optional type.
+
+   ``Optional[X]`` is equivalent to ``Union[X, None]``.
+
+   Note that this is not the same concept as an optional argument,
+   which is one that has a default.  An optional argument with a
+   default needn't use the ``Optional`` qualifier on its type
+   annotation (although it is inferred if the default is ``None``).
+   A mandatory argument may still have an ``Optional`` type if an
+   explicit value of ``None`` is allowed.
+
+.. data:: Tuple
+
+   Tuple type; ``Tuple[X, Y]`` is the type of a tuple of two items
+   with the first item of type X and the second of type Y.
+
+   Example: ``Tuple[T1, T2]`` is a tuple of two elements corresponding
+   to type variables T1 and T2.  ``Tuple[int, float, str]`` is a tuple
+   of an int, a float and a string.
+
+   To specify a variable-length tuple of homogeneous type,
+   use literal ellipsis, e.g. ``Tuple[int, ...]``. A plain :data:`Tuple`
+   is equivalent to ``Tuple[Any, ...]``, and in turn to :class:`tuple`.
+
+.. data:: Callable
+
+   Callable type; ``Callable[[int], str]`` is a function of (int) -> str.
+
+   The subscription syntax must always be used with exactly two
+   values: the argument list and the return type.  The argument list
+   must be a list of types or an ellipsis; the return type must be
+   a single type.
+
+   There is no syntax to indicate optional or keyword arguments;
+   such function types are rarely used as callback types.
+   ``Callable[..., ReturnType]`` (literal ellipsis) can be used to
+   type hint a callable taking any number of arguments and returning
+   ``ReturnType``.  A plain :data:`Callable` is equivalent to
+   ``Callable[..., Any]``, and in turn to
+   :class:`collections.abc.Callable`.
+
+.. data:: ClassVar
+
+   Special type construct 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. Usage::
+
+      class Starship:
+          stats = {}  # type: ClassVar[Dict[str, int]] # class variable
+          damage = 10 # type: int                      # instance variable
+
+   :data:`ClassVar` accepts only types and cannot be further subscribed.
+
+   :data:`ClassVar` is not a class itself, and should not
+   be used with :func:`isinstance` or :func:`issubclass`.
+   Note that :data:`ClassVar` does not change Python runtime behavior;
+   it can be used by 3rd party type checkers, so that the following
+   code might flagged as an error by those::
+
+      enterprise_d = Starship(3000)
+      enterprise_d.stats = {} # Error, setting class variable on instance
+      Starship.stats = {}     # This is OK
+
+   .. versionadded:: 3.5.3
+
+.. data:: AnyStr
+
+   ``AnyStr`` is a type variable defined as
+   ``AnyStr = TypeVar('AnyStr', str, bytes)``.
+
+   It is meant to be used for functions that may accept any kind of string
+   without allowing different kinds of strings to mix. For example::
+
+      def concat(a: AnyStr, b: AnyStr) -> AnyStr:
+          return a + b
+
+      concat(u"foo", u"bar")  # Ok, output has type 'unicode'
+      concat(b"foo", b"bar")  # Ok, output has type 'bytes'
+      concat(u"foo", b"bar")  # Error, cannot mix unicode and bytes
+
+.. data:: TYPE_CHECKING
+
+   A special constant that is assumed to be ``True`` by 3rd party static
+   type checkers. It is ``False`` at runtime. Usage::
+
+      if TYPE_CHECKING:
+          import expensive_mod
+
+      def fun():
+          local_var: expensive_mod.some_type = other_fun()
index 5c9177a..ef30c01 100644 (file)
@@ -244,7 +244,7 @@ the *new_callable* argument to :func:`patch`.
 
       .. versionadded:: 3.5
 
-    * *wraps*: Item for the mock object to wrap. If *wraps* is not None then
+    * *wraps*: Item for the mock object to wrap. If *wraps* is not ``None`` then
       calling the Mock will pass the call through to the wrapped object
       (returning the real result). Attribute access on the mock will return a
       Mock object that wraps the corresponding attribute of the wrapped
@@ -324,7 +324,7 @@ the *new_callable* argument to :func:`patch`.
             >>> calls = [call(4), call(2), call(3)]
             >>> mock.assert_has_calls(calls, any_order=True)
 
-    .. method:: assert_not_called(*args, **kwargs)
+    .. method:: assert_not_called()
 
         Assert the mock was never called.
 
index 0fc02c4..ac1224c 100644 (file)
@@ -352,7 +352,7 @@ call for every single test we run::
 
    import unittest
 
-   class SimpleWidgetTestCase(unittest.TestCase):
+   class WidgetTestCase(unittest.TestCase):
        def setUp(self):
            self.widget = Widget('The widget')
 
@@ -379,7 +379,7 @@ after the test method has been run::
 
    import unittest
 
-   class SimpleWidgetTestCase(unittest.TestCase):
+   class WidgetTestCase(unittest.TestCase):
        def setUp(self):
            self.widget = Widget('The widget')
 
@@ -868,7 +868,7 @@ Test cases
    .. method:: assertIsNone(expr, msg=None)
                assertIsNotNone(expr, msg=None)
 
-      Test that *expr* is (or is not) None.
+      Test that *expr* is (or is not) ``None``.
 
       .. versionadded:: 3.1
 
@@ -1316,19 +1316,17 @@ Test cases
 
    .. attribute:: longMessage
 
-      If set to ``True`` then any explicit failure message you pass in to the
-      :ref:`assert methods <assert-methods>` will be appended to the end of the
-      normal failure message.  The normal messages contain useful information
-      about the objects involved, for example the message from assertEqual
-      shows you the repr of the two unequal objects. Setting this attribute
-      to ``True`` allows you to have a custom error message in addition to the
-      normal one.
+      This class attribute determines what happens when a custom failure message
+      is passed as the msg argument to an assertXYY call that fails.
+      ``True`` is the default value. In this case, the custom message is appended
+      to the end of the standard failure message.
+      When set to ``False``, the custom message replaces the standard message.
 
-      This attribute defaults to ``True``. If set to False then a custom message
-      passed to an assert method will silence the normal message.
+      The class setting can be overridden in individual test methods by assigning
+      an instance attribute, self.longMessage, to ``True`` or ``False`` before
+      calling the assert methods.
 
-      The class setting can be overridden in individual tests by assigning an
-      instance attribute to ``True`` or ``False`` before calling the assert methods.
+      The class setting gets reset before each test call.
 
       .. versionadded:: 3.1
 
@@ -1342,7 +1340,7 @@ Test cases
       methods that delegate to it), :meth:`assertDictEqual` and
       :meth:`assertMultiLineEqual`.
 
-      Setting ``maxDiff`` to None means that there is no maximum length of
+      Setting ``maxDiff`` to ``None`` means that there is no maximum length of
       diffs.
 
       .. versionadded:: 3.2
@@ -1974,7 +1972,8 @@ Loading and running tests
    methods <deprecated-aliases>` are also special-cased and, when the warning
    filters are ``'default'`` or ``'always'``, they will appear only once
    per-module, in order to avoid too many warning messages.  This behavior can
-   be overridden using the :option:`-Wd` or :option:`-Wa` options and leaving
+   be overridden using Python's :option:`!-Wd` or :option:`!-Wa` options
+   (see :ref:`Warning control <using-on-warnings>`) and leaving
    *warnings* to ``None``.
 
    .. versionchanged:: 3.2
@@ -2053,9 +2052,10 @@ Loading and running tests
    The *failfast*, *catchbreak* and *buffer* parameters have the same
    effect as the same-name `command-line options`_.
 
-   The *warning* argument specifies the :ref:`warning filter <warning-filter>`
+   The *warnings* argument specifies the :ref:`warning filter <warning-filter>`
    that should be used while running the tests.  If it's not specified, it will
-   remain ``None`` if a :option:`-W` option is passed to :program:`python`,
+   remain ``None`` if a :option:`!-W` option is passed to :program:`python`
+   (see :ref:`Warning control <using-on-warnings>`),
    otherwise it will be set to ``'default'``.
 
    Calling ``main`` actually returns an instance of the ``TestProgram`` class.
index c6de230..499b211 100644 (file)
@@ -25,7 +25,7 @@ Resource Locators. It supports the following URL schemes: ``file``, ``ftp``,
 ``gopher``, ``hdl``, ``http``, ``https``, ``imap``, ``mailto``, ``mms``,
 ``news``, ``nntp``, ``prospero``, ``rsync``, ``rtsp``, ``rtspu``, ``sftp``,
 ``shttp``, ``sip``, ``sips``, ``snews``, ``svn``, ``svn+ssh``, ``telnet``,
-``wais``.
+``wais``, ``ws``, ``wss``.
 
 The :mod:`urllib.parse` module defines functions that fall into two broad
 categories: URL parsing and URL quoting. These are covered in detail in
@@ -543,7 +543,7 @@ task isn't already covered by the URL parsing functions above.
    When a sequence of two-element tuples is used as the *query*
    argument, the first element of each tuple is a key and the second is a
    value. The value element in itself can be a sequence and in that case, if
-   the optional parameter *doseq* is evaluates to *True*, individual
+   the optional parameter *doseq* is evaluates to ``True``, individual
    ``key=value`` pairs separated by ``'&'`` are generated for each element of
    the value sequence for the key.  The order of parameters in the encoded
    string will match the order of parameter tuples in the sequence.
index 1338906..618c69d 100644 (file)
@@ -18,7 +18,7 @@ authentication, redirections, cookies and more.
 
 .. seealso::
 
-    The `Requests package <https://requests.readthedocs.org/>`_
+    The `Requests package <http://docs.python-requests.org/>`_
     is recommended for a higher-level HTTP client interface.
 
 
@@ -173,6 +173,16 @@ The :mod:`urllib.request` module defines the following functions:
    If both lowercase and uppercase environment variables exist (and disagree),
    lowercase is preferred.
 
+    .. note::
+
+       If the environment variable ``REQUEST_METHOD`` is set, which usually
+       indicates your script is running in a CGI environment, the environment
+       variable ``HTTP_PROXY`` (uppercase ``_PROXY``) will be ignored. This is
+       because that variable can be injected by a client using the "Proxy:" HTTP
+       header. If you need to use an HTTP proxy in a CGI environment, either use
+       ``ProxyHandler`` explicitly, or make sure the variable name is in
+       lowercase (or at least the ``_proxy`` suffix).
+
 
 The following classes are provided:
 
@@ -280,6 +290,11 @@ The following classes are provided:
    list of hostname suffixes, optionally with ``:port`` appended, for example
    ``cern.ch,ncsa.uiuc.edu,some.host:8080``.
 
+    .. note::
+
+       ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set;
+       see the documentation on :func:`~urllib.request.getproxies`.
+
 
 .. class:: HTTPPasswordMgr()
 
@@ -461,7 +476,7 @@ request.
 
 .. attribute:: Request.data
 
-   The entity body for the request, or None if not specified.
+   The entity body for the request, or ``None`` if not specified.
 
    .. versionchanged:: 3.4
       Changing value of :attr:`Request.data` now deletes "Content-Length"
@@ -1138,7 +1153,7 @@ the returned bytes object to string once it determines or guesses
 the appropriate encoding.
 
 The following W3C document, https://www.w3.org/International/O-charset\ , lists
-the various ways in which a (X)HTML or a XML document could have specified its
+the various ways in which an (X)HTML or an XML document could have specified its
 encoding information.
 
 As the python.org website uses *utf-8* encoding as specified in its meta tag, we
index 53cbd6c..91dbca2 100644 (file)
@@ -45,6 +45,13 @@ random UUID.
    variant and version number set according to RFC 4122, overriding bits in the
    given *hex*, *bytes*, *bytes_le*, *fields*, or *int*.
 
+   Comparison of UUID objects are made by way of comparing their
+   :attr:`UUID.int` attributes.  Comparison with a non-UUID object
+   raises a :exc:`TypeError`.
+
+   ``str(uuid)`` returns a string in the form
+   ``12345678-1234-5678-1234-567812345678`` where the 32 hexadecimal digits
+   represent the UUID.
 
 :class:`UUID` instances have these read-only attributes:
 
index af4a6d1..0327737 100644 (file)
@@ -23,6 +23,12 @@ independent set of installed Python packages in its site directories.
 
 See :pep:`405` for more information about Python virtual environments.
 
+.. note::
+   The ``pyvenv`` script has been deprecated as of Python 3.6 in favor of using
+   ``python3 -m venv`` to help prevent any potential confusion as to which
+   Python interpreter a virtual environment will be based on.
+
+
 Creating virtual environments
 -----------------------------
 
index 5212131..cec55f1 100644 (file)
@@ -141,14 +141,15 @@ the disposition of the match.  Each entry is a tuple of the form (*action*,
   |               | warnings, regardless of location             |
   +---------------+----------------------------------------------+
 
-* *message* is a string containing a regular expression that the warning message
-  must match (the match is compiled to always be case-insensitive).
+* *message* is a string containing a regular expression that the start of
+  the warning message must match.  The expression is compiled to always be
+  case-insensitive.
 
 * *category* is a class (a subclass of :exc:`Warning`) of which the warning
   category must be a subclass in order to match.
 
 * *module* is a string containing a regular expression that the module name must
-  match (the match is compiled to be case-sensitive).
+  match.  The expression is compiled to be case-sensitive.
 
 * *lineno* is an integer that the line number where the warning occurred must
   match, or ``0`` to match all line numbers.
@@ -266,13 +267,13 @@ Updating Code For New Versions of Python
 Warnings that are only of interest to the developer are ignored by default. As
 such you should make sure to test your code with typically ignored warnings
 made visible. You can do this from the command-line by passing :option:`-Wd <-W>`
-to the interpreter (this is shorthand for :option:`-W default`).  This enables
+to the interpreter (this is shorthand for :option:`!-W default`).  This enables
 default handling for all warnings, including those that are ignored by default.
 To change what action is taken for encountered warnings you simply change what
-argument is passed to :option:`-W`, e.g. :option:`-W error`. See the
+argument is passed to :option:`-W`, e.g. :option:`!-W error`. See the
 :option:`-W` flag for more details on what is possible.
 
-To programmatically do the same as :option:`-Wd`, use::
+To programmatically do the same as :option:`!-Wd`, use::
 
   warnings.simplefilter('default')
 
index 7144379..a9b3205 100644 (file)
@@ -112,7 +112,7 @@ Wave_read objects, as returned by :func:`.open`, have the following methods:
 
 .. method:: Wave_read.readframes(n)
 
-   Reads and returns at most *n* frames of audio, as a string of bytes.
+   Reads and returns at most *n* frames of audio, as a :class:`bytes` object.
 
 
 .. method:: Wave_read.rewind()
index 0470bd1..e289b97 100644 (file)
@@ -414,7 +414,7 @@ the referent is accessed::
 Example
 -------
 
-This simple example shows how an application can use objects IDs to retrieve
+This simple example shows how an application can use object IDs to retrieve
 objects that it has seen before.  The IDs of the objects can then be used in
 other data structures without forcing the objects to remain alive, but the
 objects can still be retrieved by ID if they do.
index 52d591a..767ea31 100644 (file)
@@ -1,4 +1,4 @@
-:mod:`winreg` -- Windows registry access
+:mod:`winreg` --- Windows registry access
 =========================================
 
 .. module:: winreg
index e1042e7..2e9e814 100644 (file)
@@ -94,7 +94,7 @@ document: the one that holds all others.  Here is an example program::
 
 When you are finished with a DOM tree, you may optionally call the
 :meth:`unlink` method to encourage early cleanup of the now-unneeded
-objects.  :meth:`unlink` is a :mod:`xml.dom.minidom`\ -specific
+objects.  :meth:`unlink` is an :mod:`xml.dom.minidom`\ -specific
 extension to the DOM API that renders the node and its descendants are
 essentially useless.  Otherwise, Python's garbage collector will
 eventually take care of the objects in the tree.
index c3339ed..b502554 100644 (file)
@@ -74,7 +74,7 @@ and switch to DOM-related processing.
 .. function:: parse(stream_or_string, parser=None, bufsize=None)
 
    Return a :class:`DOMEventStream` from the given input. *stream_or_string* may be
-   either a file name, or a file-like object. *parser*, if given, must be a
+   either a file name, or a file-like object. *parser*, if given, must be an
    :class:`~xml.sax.xmlreader.XMLReader` object. This function will change the
    document handler of the
    parser and activate namespace support; other parser configuration (like
index b037ff6..de334af 100644 (file)
@@ -404,7 +404,7 @@ NodeList Objects
 ^^^^^^^^^^^^^^^^
 
 A :class:`NodeList` represents a sequence of nodes.  These objects are used in
-two ways in the DOM Core recommendation:  the :class:`Element` objects provides
+two ways in the DOM Core recommendation:  an :class:`Element` object provides
 one as its list of child nodes, and the :meth:`getElementsByTagName` and
 :meth:`getElementsByTagNameNS` methods of :class:`Node` return objects with this
 interface to represent query results.
index 99d7e8b..b54eace 100644 (file)
@@ -928,7 +928,7 @@ ElementTree Objects
       *method* is either ``"xml"``, ``"html"`` or ``"text"`` (default is
       ``"xml"``).
       The keyword-only *short_empty_elements* parameter controls the formatting
-      of elements that contain no content.  If *True* (the default), they are
+      of elements that contain no content.  If ``True`` (the default), they are
       emitted as a single self-closed tag, otherwise they are emitted as a pair
       of start/end tags.
 
index 3c2fc89..d833b7f 100644 (file)
@@ -60,15 +60,15 @@ circumvent firewalls.
 The following table gives an overview of the known attacks and whether
 the various modules are vulnerable to them.
 
-=========================  ========  =========  =========  ========  =========
-kind                       sax       etree      minidom    pulldom   xmlrpc
-=========================  ========  =========  =========  ========  =========
-billion laughs             **Yes**   **Yes**    **Yes**    **Yes**   **Yes**
-quadratic blowup           **Yes**   **Yes**    **Yes**    **Yes**   **Yes**
-external entity expansion  **Yes**   No    (1)  No    (2)  **Yes**   No    (3)
-`DTD`_ retrieval           **Yes**   No         No         **Yes**   No
-decompression bomb         No        No         No         No        **Yes**
-=========================  ========  =========  =========  ========  =========
+=========================  ==============   ===============   ==============   ==============   ==============
+kind                       sax              etree             minidom          pulldom          xmlrpc
+=========================  ==============   ===============   ==============   ==============   ==============
+billion laughs             **Vulnerable**   **Vulnerable**    **Vulnerable**   **Vulnerable**   **Vulnerable**
+quadratic blowup           **Vulnerable**   **Vulnerable**    **Vulnerable**   **Vulnerable**   **Vulnerable**
+external entity expansion  **Vulnerable**   Safe    (1)       Safe    (2)      **Vulnerable**   Safe    (3)
+`DTD`_ retrieval           **Vulnerable**   Safe              Safe             **Vulnerable**   Safe
+decompression bomb         Safe             Safe              Safe             Safe             **Vulnerable**
+=========================  ==============   ===============   ==============   ==============   ==============
 
 1. :mod:`xml.etree.ElementTree` doesn't expand external entities and raises a
    :exc:`ParserError` when an entity occurs.
index c368fc2..1b6e431 100644 (file)
@@ -308,7 +308,7 @@ InputSource Objects
    Get the byte stream for this input source.
 
    The getEncoding method will return the character encoding for this byte stream,
-   or None if unknown.
+   or ``None`` if unknown.
 
 
 .. method:: InputSource.setCharacterStream(charfile)
index 538b798..e46fefd 100644 (file)
@@ -63,8 +63,8 @@ or as base classes.
    should be a file-like object which will default to *sys.stdout*. *encoding* is
    the encoding of the output stream which defaults to ``'iso-8859-1'``.
    *short_empty_elements* controls the formatting of elements that contain no
-   content:  if *False* (the default) they are emitted as a pair of start/end
-   tags, if set to *True* they are emitted as a single self-closed tag.
+   content:  if ``False`` (the default) they are emitted as a pair of start/end
+   tags, if set to ``True`` they are emitted as a single self-closed tag.
 
    .. versionadded:: 3.2
       The *short_empty_elements* parameter.
index e7916d2..dad7a02 100644 (file)
@@ -555,33 +555,27 @@ Example of Client Usage
            print("ERROR", v)
 
 To access an XML-RPC server through a HTTP proxy, you need to define a custom
-transport.  The following example shows how:
+transport.  The following example shows how::
 
-.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html
-
-::
-
-   import xmlrpc.client, http.client
+   import http.client
+   import xmlrpc.client
 
    class ProxiedTransport(xmlrpc.client.Transport):
-       def set_proxy(self, proxy):
-           self.proxy = proxy
 
-       def make_connection(self, host):
-           self.realhost = host
-           h = http.client.HTTPConnection(self.proxy)
-           return h
-
-       def send_request(self, connection, handler, request_body, debug):
-           connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))
+       def set_proxy(self, host, port=None, headers=None):
+           self.proxy = host, port
+           self.proxy_headers = headers
 
-       def send_host(self, connection, host):
-           connection.putheader('Host', self.realhost)
-
-   p = ProxiedTransport()
-   p.set_proxy('proxy-server:8080')
-   server = xmlrpc.client.ServerProxy('http://time.xmlrpc.com/RPC2', transport=p)
-   print(server.currentTime.getCurrentTime())
+       def make_connection(self, host):
+           connection = http.client.HTTPConnection(*self.proxy)
+           connection.set_tunnel(host, headers=self.proxy_headers)
+           self._connection = host, connection
+           return connection
+
+   transport = ProxiedTransport()
+   transport.set_proxy('proxy-server', 8080)
+   server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport)
+   print(server.examples.getStateName(41))
 
 
 Example of Client and Server Usage
index ad1e812..1c77e84 100644 (file)
@@ -293,7 +293,7 @@ requests sent to Python CGI scripts.
 
 .. method:: CGIXMLRPCRequestHandler.handle_request(request_text=None)
 
-   Handle a XML-RPC request. If *request_text* is given, it  should be the POST
+   Handle an XML-RPC request. If *request_text* is given, it should be the POST
    data provided by the HTTP server,  otherwise the contents of stdin will be used.
 
 Example::
index 7c7767f..9dee9a5 100644 (file)
@@ -121,7 +121,7 @@ The module defines two convenience functions:
      the archive will be written to that file.
    * If it is an open file object, the archive will be written to that
      file object, which must be open for writing in bytes mode.
-   * If the target is omitted (or None), the source must be a directory
+   * If the target is omitted (or ``None``), the source must be a directory
      and the target will be a file with the same name as the source, with
      a ``.pyz`` extension added.
 
index b421ea5..d144ae3 100644 (file)
@@ -142,8 +142,8 @@ ZipFile Objects
    file, then additional files are added to it.  If *file* does not refer to a
    ZIP file, then a new ZIP archive is appended to the file.  This is meant for
    adding a ZIP archive to another file (such as :file:`python.exe`).  If
-   *mode* is ``a`` and the file does not exist at all, it is created.
-   If *mode* is ``r`` or ``a``, the file should be seekable.
+   *mode* is ``'a'`` and the file does not exist at all, it is created.
+   If *mode* is ``'r'`` or ``'a'``, the file should be seekable.
    *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
@@ -152,7 +152,7 @@ ZipFile Objects
    (:mod:`zlib`, :mod:`bz2` or :mod:`lzma`) is not available, :exc:`RuntimeError`
    is also 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`
+   extensions when the zipfile is larger than 4 GiB. If it is  false :mod:`zipfile`
    will raise an exception when the ZIP file would require ZIP64 extensions.
 
    If the file is created with mode ``'w'``, ``'x'`` or ``'a'`` and then
@@ -250,7 +250,7 @@ ZipFile Objects
 .. method:: ZipFile.extract(member, path=None, pwd=None)
 
    Extract a member from the archive to the current working directory; *member*
-   must be its full name or a :class:`ZipInfo` object).  Its file information is
+   must be its full name or a :class:`ZipInfo` object.  Its file information is
    extracted as accurately as possible.  *path* specifies a different directory
    to extract to.  *member* can be a filename or a :class:`ZipInfo` object.
    *pwd* is the password used for encrypted files.
@@ -343,9 +343,9 @@ 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.
 
-.. method:: ZipFile.writestr(zinfo_or_arcname, bytes[, compress_type])
+.. method:: ZipFile.writestr(zinfo_or_arcname, data[, compress_type])
 
-   Write the string *bytes* to the archive; *zinfo_or_arcname* is either the file
+   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.
@@ -574,4 +574,61 @@ Instances have the following attributes:
 
    Size of the uncompressed file.
 
+
+.. _zipfile-commandline:
+.. program:: zipfile
+
+Command-Line Interface
+----------------------
+
+The :mod:`zipfile` module provides a simple command-line interface to interact
+with ZIP archives.
+
+If you want to create a new ZIP archive, specify its name after the :option:`-c`
+option and then list the filename(s) that should be included:
+
+.. code-block:: shell-session
+
+    $ python -m zipfile -c monty.zip spam.txt eggs.txt
+
+Passing a directory is also acceptable:
+
+.. code-block:: shell-session
+
+    $ python -m zipfile -c monty.zip life-of-brian_1979/
+
+If you want to extract a ZIP archive into the specified directory, use
+the :option:`-e` option:
+
+.. code-block:: shell-session
+
+    $ python -m zipfile -e monty.zip target-dir/
+
+For a list of the files in a ZIP archive, use the :option:`-l` option:
+
+.. code-block:: shell-session
+
+    $ python -m zipfile -l monty.zip
+
+
+Command-line options
+~~~~~~~~~~~~~~~~~~~~
+
+.. cmdoption:: -l <zipfile>
+
+   List files in a zipfile.
+
+.. cmdoption:: -c <zipfile> <source1> ... <sourceN>
+
+   Create zipfile from source files.
+
+.. cmdoption:: -e <zipfile> <output_dir>
+
+   Extract zipfile into target directory.
+
+.. cmdoption:: -t <zipfile>
+
+   Test whether the zipfile is valid or not.
+
+
 .. _PKZIP Application Note: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
index 0a0f175..46b8c24 100644 (file)
@@ -147,7 +147,9 @@ Examples
 --------
 
 Here is an example that imports a module from a ZIP archive - note that the
-:mod:`zipimport` module is not explicitly used. ::
+:mod:`zipimport` module is not explicitly used.
+
+.. code-block:: shell-session
 
    $ unzip -l example.zip
    Archive:  example.zip
index 8843116..49d29ce 100644 (file)
@@ -87,7 +87,7 @@ PSF LICENSE AGREEMENT FOR PYTHON |release|
       analyze, test, perform and/or display publicly, prepare derivative works,
       distribute, and otherwise use Python |release| alone or in any derivative
       version, provided, however, that PSF's License Agreement and PSF's notice of
-      copyright, i.e., "Copyright © 2001-2016 Python Software Foundation; All Rights
+      copyright, i.e., "Copyright © 2001-2017 Python Software Foundation; All Rights
       Reserved" are retained in Python |release| alone or in any derivative version
       prepared by Licensee.
 
index 2469422..88b94ea 100644 (file)
@@ -503,11 +503,13 @@ are applied in nested fashion. For example, the following code ::
    @f2
    def func(): pass
 
-is equivalent to ::
+is roughly equivalent to ::
 
    def func(): pass
    func = f1(arg)(f2(func))
 
+except that the original function is not temporarily bound to the name ``func``.
+
 .. index::
    triple: default; parameter; value
    single: argument; function definition
@@ -638,14 +640,13 @@ Classes can also be decorated: just like when decorating functions, ::
    @f2
    class Foo: pass
 
-is equivalent to ::
+is roughly equivalent to ::
 
    class Foo: pass
    Foo = f1(arg)(f2(Foo))
 
 The evaluation rules for the decorator expressions are the same as for function
-decorators.  The result must be a class object, which is then bound to the class
-name.
+decorators.  The result is then bound to the class name.
 
 **Programmer's note:** Variables defined in the class definition are class
 attributes; they are shared by instances.  Instance attributes can be set in a
index 71d695f..2f5625b 100644 (file)
@@ -454,6 +454,19 @@ Callable types
 
       .. tabularcolumns:: |l|L|l|
 
+      .. index::
+         single: __doc__ (function attribute)
+         single: __name__ (function attribute)
+         single: __module__ (function attribute)
+         single: __dict__ (function attribute)
+         single: __defaults__ (function attribute)
+         single: __closure__ (function attribute)
+         single: __code__ (function attribute)
+         single: __globals__ (function attribute)
+         single: __annotations__ (function attribute)
+         single: __kwdefaults__ (function attribute)
+         pair: global; namespace
+
       +-------------------------+-------------------------------+-----------+
       | Attribute               | Meaning                       |           |
       +=========================+===============================+===========+
@@ -462,10 +475,11 @@ Callable types
       |                         | unavailable; not inherited by |           |
       |                         | subclasses                    |           |
       +-------------------------+-------------------------------+-----------+
-      | :attr:`__name__`        | The function's name           | Writable  |
+      | :attr:`~definition.\    | The function's name           | Writable  |
+      | __name__`               |                               |           |
       +-------------------------+-------------------------------+-----------+
-      | :attr:`__qualname__`    | The function's                | Writable  |
-      |                         | :term:`qualified name`        |           |
+      | :attr:`~definition.\    | The function's                | Writable  |
+      | __qualname__`           | :term:`qualified name`        |           |
       |                         |                               |           |
       |                         | .. versionadded:: 3.3         |           |
       +-------------------------+-------------------------------+-----------+
@@ -489,7 +503,7 @@ Callable types
       |                         | module in which the function  |           |
       |                         | was defined.                  |           |
       +-------------------------+-------------------------------+-----------+
-      | :attr:`__dict__`        | The namespace supporting      | Writable  |
+      | :attr:`~object.__dict__`| The namespace supporting      | Writable  |
       |                         | arbitrary function            |           |
       |                         | attributes.                   |           |
       +-------------------------+-------------------------------+-----------+
@@ -519,19 +533,6 @@ Callable types
       Additional information about a function's definition can be retrieved from its
       code object; see the description of internal types below.
 
-      .. index::
-         single: __doc__ (function attribute)
-         single: __name__ (function attribute)
-         single: __module__ (function attribute)
-         single: __dict__ (function attribute)
-         single: __defaults__ (function attribute)
-         single: __closure__ (function attribute)
-         single: __code__ (function attribute)
-         single: __globals__ (function attribute)
-         single: __annotations__ (function attribute)
-         single: __kwdefaults__ (function attribute)
-         pair: global; namespace
-
    Instance methods
       .. index::
          object: method
@@ -550,7 +551,7 @@ Callable types
 
       Special read-only attributes: :attr:`__self__` is the class instance object,
       :attr:`__func__` is the function object; :attr:`__doc__` is the method's
-      documentation (same as ``__func__.__doc__``); :attr:`__name__` is the
+      documentation (same as ``__func__.__doc__``); :attr:`~definition.__name__` is the
       method name (same as ``__func__.__name__``); :attr:`__module__` is the
       name of the module the method was defined in, or ``None`` if unavailable.
 
@@ -637,7 +638,7 @@ Callable types
       standard built-in module). The number and type of the arguments are
       determined by the C function. Special read-only attributes:
       :attr:`__doc__` is the function's documentation string, or ``None`` if
-      unavailable; :attr:`__name__` is the function's name; :attr:`__self__` is
+      unavailable; :attr:`~definition.__name__` is the function's name; :attr:`__self__` is
       set to ``None`` (but see the next item); :attr:`__module__` is the name of
       the module the function was defined in or ``None`` if unavailable.
 
@@ -687,7 +688,7 @@ Modules
 
    .. index:: single: __dict__ (module attribute)
 
-   Special read-only attribute: :attr:`__dict__` is the module's namespace as a
+   Special read-only attribute: :attr:`~object.__dict__` is the module's namespace as a
    dictionary object.
 
    .. impl-detail::
@@ -743,7 +744,7 @@ Custom classes
    method object, it is transformed into the object wrapped by the static method
    object. See section :ref:`descriptors` for another way in which attributes
    retrieved from a class may differ from those actually contained in its
-   :attr:`__dict__`.
+   :attr:`~object.__dict__`.
 
    .. index:: triple: class; attribute; assignment
 
@@ -761,12 +762,12 @@ Custom classes
       single: __bases__ (class attribute)
       single: __doc__ (class attribute)
 
-   Special attributes: :attr:`__name__` is the class name; :attr:`__module__` is
-   the module name in which the class was defined; :attr:`__dict__` is the
+   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
+   tuple (possibly 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.
 
 Class instances
    .. index::
@@ -785,7 +786,7 @@ Class instances
    class method objects are also transformed; see above under "Classes".  See
    section :ref:`descriptors` for another way in which attributes of a class
    retrieved via its instances may differ from the objects actually stored in
-   the class's :attr:`__dict__`.  If no class attribute is found, and the
+   the class's :attr:`~object.__dict__`.  If no class attribute is found, and the
    object's class has a :meth:`__getattr__` method, that is called to satisfy
    the lookup.
 
@@ -1116,7 +1117,7 @@ Basic customization
    instance; for example: ``BaseClass.__init__(self, [args...])``.
 
    Because :meth:`__new__` and :meth:`__init__` work together in constructing
-   objects (:meth:`__new__` to create it, and :meth:`__init__` to customise it),
+   objects (:meth:`__new__` to create it, and :meth:`__init__` to customize it),
    no non-``None`` value may be returned by :meth:`__init__`; doing so will
    cause a :exc:`TypeError` to be raised at runtime.
 
@@ -1304,11 +1305,14 @@ Basic customization
 
    Called by built-in function :func:`hash` and for operations on members of
    hashed collections including :class:`set`, :class:`frozenset`, and
-   :class:`dict`.  :meth:`__hash__` should return an integer.  The only
-   required property is that objects which compare equal have the same hash
-   value; it is advised to somehow mix together (e.g. using exclusive or) the
-   hash values for the components of the object that also play a part in
-   comparison of objects.
+   :class:`dict`.  :meth:`__hash__` should return an integer. The only required
+   property is that objects which compare equal have the same hash value; it is
+   advised to mix together the hash values of the components of the object that
+   also play a part in comparison of objects by packing them into a tuple and
+   hashing the tuple. Example::
+
+       def __hash__(self):
+           return hash((self.name, self.nick, self.color))
 
    .. note::
 
@@ -1466,7 +1470,7 @@ method (a so-called *descriptor* class) appears in an *owner* class (the
 descriptor must be in either the owner's class dictionary or in the class
 dictionary for one of its parents).  In the examples below, "the attribute"
 refers to the attribute whose name is the key of the property in the owner
-class' :attr:`__dict__`.
+class' :attr:`~object.__dict__`.
 
 
 .. method:: object.__get__(self, instance, owner)
@@ -1636,7 +1640,7 @@ 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)``.
 
-The class creation process can be customised by passing the ``metaclass``
+The class creation process can be customized by passing the ``metaclass``
 keyword argument in the class definition line, or by inheriting from an
 existing class that included such an argument. In the following example,
 both ``MyClass`` and ``MySubclass`` are instances of ``Meta``::
index f508eaa..9792399 100644 (file)
@@ -667,7 +667,7 @@ series of :term:`arguments <argument>`:
    starred_and_keywords: ("*" `expression` | `keyword_item`)
                 : ("," "*" `expression` | "," `keyword_item`)*
    keywords_arguments: (`keyword_item` | "**" `expression`)
-                : ("," `keyword_item` | "**" `expression`)*
+                : ("," `keyword_item` | "," "**" `expression`)*
    keyword_item: `identifier` "=" `expression`
 
 An optional trailing comma may be present after the positional and keyword arguments
@@ -1315,8 +1315,9 @@ Identity comparisons
 --------------------
 
 The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
-is y`` is true if and only if *x* and *y* are the same object.  ``x is not y``
-yields the inverse truth value. [#]_
+is y`` is true if and only if *x* and *y* are the same object.  Object identity
+is determined using the :meth:`id` function.  ``x is not y`` yields the inverse
+truth value. [#]_
 
 
 .. _booleans:
@@ -1406,7 +1407,9 @@ Lambdas
 
 Lambda expressions (sometimes called lambda forms) are used to create anonymous
 functions. The expression ``lambda arguments: expression`` yields a function
-object.  The unnamed object behaves like a function object defined with ::
+object.  The unnamed object behaves like a function object defined with:
+
+.. code-block:: none
 
    def <lambda>(arguments):
        return expression
index 2144c1f..64302b8 100644 (file)
@@ -774,7 +774,7 @@ hooks <path entry hook>` in this list is called with a single argument, the
 path entry to be searched.  This callable may either return a :term:`path
 entry finder` that can handle the path entry, or it may raise
 :exc:`ImportError`.  An :exc:`ImportError` is used by the path based finder to
-signal that the hook cannot find a :term:`path entry finder`.
+signal that the hook cannot find a :term:`path entry finder`
 for that :term:`path entry`.  The
 exception is ignored and :term:`import path` iteration continues.  The hook
 should expect either a string or bytes object; the encoding of bytes objects
@@ -828,7 +828,7 @@ portion.
 
    Older path entry finders may implement one of these two deprecated methods
    instead of ``find_spec()``.  The methods are still respected for the
-   sake of backward compatibility.  Howevever, if ``find_spec()`` is
+   sake of backward compatibility.  However, if ``find_spec()`` is
    implemented on the path entry finder, the legacy methods are ignored.
 
    :meth:`~importlib.abc.PathEntryFinder.find_loader` takes one argument, the
index 71964d7..37f25f1 100644 (file)
@@ -689,7 +689,10 @@ Operators
 
 .. index:: single: operators
 
-The following tokens are operators::
+The following tokens are operators:
+
+.. code-block:: none
+
 
    +       -       *       **      /       //      %      @
    <<      >>      &       |       ^       ~
@@ -703,7 +706,9 @@ Delimiters
 
 .. index:: single: delimiters
 
-The following tokens serve as delimiters in the grammar::
+The following tokens serve as delimiters in the grammar:
+
+.. code-block:: none
 
    (       )       [       ]       {       }
    ,       :       .       ;       @       =       ->
@@ -716,12 +721,16 @@ of the list, the augmented assignment operators, serve lexically as delimiters,
 but also perform an operation.
 
 The following printing ASCII characters have special meaning as part of other
-tokens or are otherwise significant to the lexical analyzer::
+tokens or are otherwise significant to the lexical analyzer:
+
+.. code-block:: none
 
    '       "       #       \
 
 The following printing ASCII characters are not used in Python.  Their
-occurrence outside string literals and comments is an unconditional error::
+occurrence outside string literals and comments is an unconditional error:
+
+.. code-block:: none
 
    $       ?       `
 
index d3ed849..0a70e57 100644 (file)
@@ -270,5 +270,5 @@ class SuspiciousVisitor(nodes.GenericNodeVisitor):
         # ignore comments -- too much false positives.
         # (although doing this could miss some errors;
         # there were two sections "commented-out" by mistake
-        # in the Python docs that would not be catched)
+        # in the Python docs that would not be caught)
         raise nodes.SkipNode
index e24043f..1d5c18e 100644 (file)
@@ -22,6 +22,16 @@ div.related:first-child {
     border-bottom: 1px solid #ccc;
 }
 
+.inline-search {
+    display: inline;
+}
+form.inline-search input {
+    display: inline;
+}
+form.inline-search input[type="submit"] {
+    width: 30px;
+}
+
 div.sphinxsidebar {
     background-color: #eeeeee;
     border-radius: 5px;
@@ -45,6 +55,7 @@ div.sphinxsidebar a:hover {
     color: #0095C4;
 }
 
+form.inline-search input,
 div.sphinxsidebar input {
     font-family: 'Lucida Grande',Arial,sans-serif;
     border: 1px solid #999999;
index 7289a4d..8b36a61 100644 (file)
@@ -2,13 +2,12 @@
   'use strict';
 
   var all_versions = {
-    '3.6': 'dev (3.6)',
+    '3.7': 'dev (3.7)',
+    '3.6': '3.6',
     '3.5': '3.5',
     '3.4': '3.4',
     '3.3': '3.3',
-    '3.2': '3.2',
     '2.7': '2.7',
-    '2.6': '2.6'
   };
 
   function build_select(current_version, current_release) {
diff --git a/Doc/tools/templates/customsourcelink.html b/Doc/tools/templates/customsourcelink.html
new file mode 100644 (file)
index 0000000..243d810
--- /dev/null
@@ -0,0 +1,10 @@
+{%- if show_source and has_source and sourcename %}
+  <div role="note" aria-label="source link">
+    <h3>{{ _('This Page') }}</h3>
+    <ul class="this-page-menu">
+      <li><a href="{{ pathto('bugs') }}">{% trans %}Report a Bug{% endtrans %}</a></li>
+      <li><a href="{{ pathto('_sources/' + sourcename, true)|e }}"
+            rel="nofollow">{{ _('Show Source') }}</a></li>
+    </ul>
+  </div>
+{%- endif %}
index bb449ef..b7bcd74 100644 (file)
@@ -3,7 +3,8 @@
 <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.4/">{% trans %}Python 3.4 (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.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>
 
index 1887b85..5c180e7 100644 (file)
           {%- endif %}
         </li>
 {% endblock %}
+{%- macro searchbox() %}
+{# modified from sphinx/themes/basic/searchbox.html #}
+    {%- if builder != "htmlhelp" %}
+    <div class="inline-search" style="display: none" role="search">
+        <form class="inline-search" action="{{ pathto('search') }}" method="get">
+          <input placeholder="{{ _('Quick search') }}" type="text" name="q" />
+          <input type="submit" value="{{ _('Go') }}" />
+          <input type="hidden" name="check_keywords" value="yes" />
+          <input type="hidden" name="area" value="default" />
+        </form>
+    </div>
+    <script type="text/javascript">$('.inline-search').show(0);</script>
+    {%- endif %}
+{%- endmacro %}
 {% block relbar1 %} {% if builder != 'qthelp' %} {{ relbar() }} {% endif %} {% endblock %}
 {% block relbar2 %} {% if builder != 'qthelp' %} {{ relbar() }} {% endif %} {% endblock %}
+{% block relbaritems %}
+    {%- if pagename != "search" and builder != "singlehtml" and builder != "htmlhelp" %}
+    <li class="right">
+        {{ searchbox() }}
+        {{ reldelim2 }}
+    </li>
+    {%- endif %}
+{% endblock %}
 {% block extrahead %}
     <link rel="shortcut icon" type="image/png" href="{{ pathto('_static/py.png', 1) }}" />
+    {% if builder != "htmlhelp" %}
     {% if not embedded %}<script type="text/javascript" src="{{ pathto('_static/copybutton.js', 1) }}"></script>{% endif %}
     {% if versionswitcher is defined and not embedded %}<script type="text/javascript" src="{{ pathto('_static/version_switch.js', 1) }}"></script>{% endif %}
     {% if pagename == 'whatsnew/changelog' and not embedded %}
@@ -75,6 +98,7 @@
       });
     </script>
     {% endif %}
+    {% endif %}
 {{ super() }}
 {% endblock %}
 {% block footer %}
     {% trans sphinx_version=sphinx_version|e %}Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> {{ sphinx_version }}.{% endtrans %}
     </div>
 {% endblock %}
-{% block sidebarsourcelink %}
-{%- if show_source and has_source and sourcename %}
-<h3>{{ _('This Page') }}</h3>
-<ul class="this-page-menu">
-  <li><a href="{{ pathto('bugs') }}">{% trans %}Report a Bug{% endtrans %}</a></li>
-  <li><a href="{{ pathto('_sources/' + sourcename, true)|e }}"
-         rel="nofollow">{% trans %}Show Source{% endtrans %}</a></li>
-</ul>
-{%- endif %}
-{% endblock %}
index 2489d75..e134d5d 100644 (file)
@@ -374,11 +374,11 @@ Surely Python raises an exception when a function that requires an argument is
 called without any --- even if the argument isn't actually used...
 
 Actually, you may have guessed the answer: the special thing about methods is
-that the object is passed as the first argument of the function.  In our
+that the instance object is passed as the first argument of the function.  In our
 example, the call ``x.f()`` is exactly equivalent to ``MyClass.f(x)``.  In
 general, calling a method with a list of *n* arguments is equivalent to calling
 the corresponding function with an argument list that is created by inserting
-the method's object before the first argument.
+the method's instance object before the first argument.
 
 If you still don't understand how methods work, a look at the implementation can
 perhaps clarify matters.  When an instance attribute is referenced that isn't a
@@ -744,55 +744,6 @@ object with the method :meth:`m`, and ``m.__func__`` is the function object
 corresponding to the method.
 
 
-.. _tut-exceptionclasses:
-
-Exceptions Are Classes Too
-==========================
-
-User-defined exceptions are identified by classes as well.  Using this mechanism
-it is possible to create extensible hierarchies of exceptions.
-
-There are two new valid (semantic) forms for the :keyword:`raise` statement::
-
-   raise Class
-
-   raise Instance
-
-In the first form, ``Class`` must be an instance of :class:`type` or of a
-class derived from it.  The first form is a shorthand for::
-
-   raise Class()
-
-A class in an :keyword:`except` clause is compatible with an exception if it is
-the same class or a base class thereof (but not the other way around --- an
-except clause listing a derived class is not compatible with a base class).  For
-example, the following code will print B, C, D in that order::
-
-   class B(Exception):
-       pass
-   class C(B):
-       pass
-   class D(C):
-       pass
-
-   for cls in [B, C, D]:
-       try:
-           raise cls()
-       except D:
-           print("D")
-       except C:
-           print("C")
-       except B:
-           print("B")
-
-Note that if the except clauses were reversed (with ``except B`` first), it
-would have printed B, B, B --- the first matching except clause is triggered.
-
-When an error message is printed for an unhandled exception, the exception's
-class name is printed, then a colon and a space, and finally the instance
-converted to a string using the built-in function :func:`str`.
-
-
 .. _tut-iterators:
 
 Iterators
@@ -951,8 +902,7 @@ Examples::
 .. rubric:: Footnotes
 
 .. [#] Except for one thing.  Module objects have a secret read-only attribute called
-   :attr:`__dict__` which returns the dictionary used to implement the module's
-   namespace; the name :attr:`__dict__` is an attribute but not a global name.
+   :attr:`~object.__dict__` which returns the dictionary used to implement the module's
+   namespace; the name :attr:`~object.__dict__` is an attribute but not a global name.
    Obviously, using this violates the abstraction of namespace implementation, and
    should be restricted to things like post-mortem debuggers.
-
index ddc0855..12989b2 100644 (file)
@@ -501,7 +501,9 @@ It could be called like this::
               client="John Cleese",
               sketch="Cheese Shop Sketch")
 
-and of course it would print::
+and of course it would print:
+
+.. code-block:: none
 
    -- Do you have any Limburger ?
    -- I'm sorry, we're all out of Limburger
index 4195c7e..759588f 100644 (file)
@@ -18,7 +18,7 @@ Syntax errors, also known as parsing errors, are perhaps the most common kind of
 complaint you get while you are still learning Python::
 
    >>> while True print('Hello world')
-     File "<stdin>", line 1, in ?
+     File "<stdin>", line 1
        while True print('Hello world')
                       ^
    SyntaxError: invalid syntax
@@ -44,15 +44,15 @@ programs, however, and result in error messages as shown here::
 
    >>> 10 * (1/0)
    Traceback (most recent call last):
-     File "<stdin>", line 1, in ?
+     File "<stdin>", line 1, in <module>
    ZeroDivisionError: division by zero
    >>> 4 + spam*3
    Traceback (most recent call last):
-     File "<stdin>", line 1, in ?
+     File "<stdin>", line 1, in <module>
    NameError: name 'spam' is not defined
    >>> '2' + 2
    Traceback (most recent call last):
-     File "<stdin>", line 1, in ?
+     File "<stdin>", line 1, in <module>
    TypeError: Can't convert 'int' object to str implicitly
 
 The last line of the error message indicates what happened. Exceptions come in
@@ -120,6 +120,33 @@ name multiple exceptions as a parenthesized tuple, for example::
    ... except (RuntimeError, TypeError, NameError):
    ...     pass
 
+A class in an :keyword:`except` clause is compatible with an exception if it is
+the same class or a base class thereof (but not the other way around --- an
+except clause listing a derived class is not compatible with a base class).  For
+example, the following code will print B, C, D in that order::
+
+   class B(Exception):
+       pass
+
+   class C(B):
+       pass
+
+   class D(C):
+       pass
+
+   for cls in [B, C, D]:
+       try:
+           raise cls()
+       except D:
+           print("D")
+       except C:
+           print("C")
+       except B:
+           print("B")
+
+Note that if the except clauses were reversed (with ``except B`` first), it
+would have printed B, B, B --- the first matching except clause is triggered.
+
 The last except clause may omit the exception name(s), to serve as a wildcard.
 Use this with extreme caution, since it is easy to mask a real programming error
 in this way!  It can also be used to print an error message and then re-raise
@@ -201,7 +228,7 @@ indirectly) in the try clause. For example::
    ... except ZeroDivisionError as err:
    ...     print('Handling run-time error:', err)
    ...
-   Handling run-time error: int division or modulo by zero
+   Handling run-time error: division by zero
 
 
 .. _tut-raising:
@@ -214,12 +241,15 @@ exception to occur. For example::
 
    >>> raise NameError('HiThere')
    Traceback (most recent call last):
-     File "<stdin>", line 1, in ?
+     File "<stdin>", line 1, in <module>
    NameError: HiThere
 
 The sole argument to :keyword:`raise` indicates the exception to be raised.
 This must be either an exception instance or an exception class (a class that
-derives from :class:`Exception`).
+derives from :class:`Exception`).  If an exception class is passed, it will
+be implicitly instantiated by calling its constructor with no arguments::
+
+   raise ValueError  # shorthand for 'raise ValueError()'
 
 If you need to determine whether an exception was raised but don't intend to
 handle it, a simpler form of the :keyword:`raise` statement allows you to
@@ -233,7 +263,7 @@ re-raise the exception::
    ...
    An exception flew by!
    Traceback (most recent call last):
-     File "<stdin>", line 2, in ?
+     File "<stdin>", line 2, in <module>
    NameError: HiThere
 
 
@@ -244,29 +274,7 @@ User-defined Exceptions
 
 Programs may name their own exceptions by creating a new exception class (see
 :ref:`tut-classes` for more about Python classes).  Exceptions should typically
-be derived from the :exc:`Exception` class, either directly or indirectly.  For
-example::
-
-   >>> class MyError(Exception):
-   ...     def __init__(self, value):
-   ...         self.value = value
-   ...     def __str__(self):
-   ...         return repr(self.value)
-   ...
-   >>> try:
-   ...     raise MyError(2*2)
-   ... except MyError as e:
-   ...     print('My exception occurred, value:', e.value)
-   ...
-   My exception occurred, value: 4
-   >>> raise MyError('oops!')
-   Traceback (most recent call last):
-     File "<stdin>", line 1, in ?
-   __main__.MyError: 'oops!'
-
-In this example, the default :meth:`__init__` of :class:`Exception` has been
-overridden.  The new behavior simply creates the *value* attribute.  This
-replaces the default behavior of creating the *args* attribute.
+be derived from the :exc:`Exception` class, either directly or indirectly.
 
 Exception classes can be defined which do anything any other class can do, but
 are usually kept simple, often only offering a number of attributes that allow
@@ -330,7 +338,7 @@ example::
    ...
    Goodbye, world!
    Traceback (most recent call last):
-     File "<stdin>", line 2, in ?
+     File "<stdin>", line 2, in <module>
    KeyboardInterrupt
 
 A *finally clause* is always executed before leaving the :keyword:`try`
@@ -362,7 +370,7 @@ complicated example::
    >>> divide("2", "1")
    executing finally clause
    Traceback (most recent call last):
-     File "<stdin>", line 1, in ?
+     File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in divide
    TypeError: unsupported operand type(s) for /: 'str' and 'str'
 
index d440e53..0c0eb52 100644 (file)
@@ -1,3 +1,7 @@
+.. testsetup::
+
+    import math
+
 .. _tut-fp-issues:
 
 **************************************************
index e966085..e8d8e2b 100644 (file)
@@ -94,7 +94,9 @@ mode*.  In this mode it prompts for the next command with the *primary prompt*,
 usually three greater-than signs (``>>>``); for continuation lines it prompts
 with the *secondary prompt*, by default three dots (``...``). The interpreter
 prints a welcome message stating its version number and a copyright notice
-before printing the first prompt::
+before printing the first prompt:
+
+.. code-block:: shell-session
 
    $ python3.5
    Python 3.5 (default, Sep 16 2015, 09:25:04)
index 261a3f3..1e3d5c0 100644 (file)
@@ -140,7 +140,9 @@ the end of your module::
 
 you can make the file usable as a script as well as an importable module,
 because the code that parses the command line only runs if the module is
-executed as the "main" file::
+executed as the "main" file:
+
+.. code-block:: shell-session
 
    $ python fibo.py 50
    1 1 2 3 5 8 13 21 34
@@ -499,7 +501,7 @@ when the ``from...import`` statement is executed.  (This also works when
 ``__all__`` is defined.)
 
 Although certain modules are designed to export only names that follow certain
-patterns when you use ``import *``, it is still considered bad practise in
+patterns when you use ``import *``, it is still considered bad practice in
 production code.
 
 Remember, there is nothing wrong with using ``from Package import
index 3714384..f733ffc 100644 (file)
@@ -1,8 +1,8 @@
 .. _tut-brieftourtwo:
 
-*********************************************
-Brief Tour of the Standard Library -- Part II
-*********************************************
+**********************************************
+Brief Tour of the Standard Library --- Part II
+**********************************************
 
 This second tour covers more advanced modules that support professional
 programming needs.  These modules rarely occur in small scripts.
index ec744a3..6117796 100644 (file)
@@ -192,7 +192,7 @@ Miscellaneous options
 
    Issue a warning when comparing :class:`bytes` or :class:`bytearray` with
    :class:`str` or :class:`bytes` with :class:`int`.  Issue an error when the
-   option is given twice (:option:`-bb`).
+   option is given twice (:option:`!-bb`).
 
    .. versionchanged:: 3.5
       Affects comparisons of :class:`bytes` with :class:`int`.
@@ -239,9 +239,7 @@ Miscellaneous options
 
 .. cmdoption:: -O
 
-   Turn on basic optimizations.  This changes the filename extension for
-   compiled (:term:`bytecode`) files from ``.pyc`` to ``.pyo``.  See also
-   :envvar:`PYTHONOPTIMIZE`.
+   Turn on basic optimizations.  See also :envvar:`PYTHONOPTIMIZE`.
 
 
 .. cmdoption:: -OO
@@ -310,11 +308,12 @@ Miscellaneous options
 
    Print a message each time a module is initialized, showing the place
    (filename or built-in module) from which it is loaded.  When given twice
-   (:option:`-vv`), print a message for each file that is checked for when
+   (:option:`!-vv`), print a message for each file that is checked for when
    searching for a module.  Also provides information on module cleanup at exit.
    See also :envvar:`PYTHONVERBOSE`.
 
 
+.. _using-on-warnings:
 .. cmdoption:: -W arg
 
    Warning control.  Python's warning machinery by default prints warning
index c529478..7ad3008 100644 (file)
@@ -89,9 +89,9 @@ venv's binary directory. The invocation of the script is platform-specific:
 +-------------+-----------------+-----------------------------------------+
 |             | csh/tcsh        | $ source <venv>/bin/activate.csh        |
 +-------------+-----------------+-----------------------------------------+
-| Windows     | cmd.exe         | C:\> <venv>\Scripts\activate.bat        |
+| Windows     | cmd.exe         | C:\\> <venv>\\Scripts\\activate.bat     |
 +-------------+-----------------+-----------------------------------------+
-|             | PowerShell      | PS C:\> <venv>\Scripts\Activate.ps1     |
+|             | PowerShell      | PS C:\\> <venv>\\Scripts\\Activate.ps1  |
 +-------------+-----------------+-----------------------------------------+
 
 You don't specifically *need* to activate an environment; activation just
index 7520d60..a4a6a30 100644 (file)
@@ -54,7 +54,7 @@ If you select "Install Now":
   users)
 * Python will be installed into your user directory
 * The :ref:`launcher` will be installed according to the option at the bottom
-  of the first pace
+  of the first page
 * The standard library, test suite, launcher and pip will be installed
 * If selected, the install directory will be added to your :envvar:`PATH`
 * Shortcuts will only be visible for the current user
@@ -382,7 +382,7 @@ 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
 :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` or . Thus, you can also execute your
+:command:`pip` for the package installer. Thus, you can also execute your
 scripts with command line options, see :ref:`using-on-cmdline` documentation.
 
 If you don't enable this option at install time, you can always re-run the
index 87462f3..010a007 100644 (file)
@@ -166,7 +166,7 @@ encoding.  Encodings are named by strings, such as ``'ascii'``, ``'utf-8'``,
 registering new encodings that are then available throughout a Python program.
 If an encoding isn't specified, the default encoding is usually 7-bit ASCII,
 though it can be changed for your Python installation by calling the
-``sys.setdefaultencoding(encoding)`` function in a customised version of
+``sys.setdefaultencoding(encoding)`` function in a customized version of
 :file:`site.py`.
 
 Combining 8-bit and Unicode strings always coerces to Unicode, using the default
@@ -476,7 +476,7 @@ lost, because benchmarking this is tricky and depends crucially on how often the
 program creates and destroys objects.  The detection of cycles can be disabled
 when Python is compiled, if you can't afford even a tiny speed penalty or
 suspect that the cycle collection is buggy, by specifying the
-:option:`--without-cycle-gc` switch when running the :program:`configure`
+:option:`!--without-cycle-gc` switch when running the :program:`configure`
 script.
 
 Several people tackled this problem and contributed to a solution.  An early
@@ -506,7 +506,7 @@ arguments and/or a dictionary of keyword arguments. In Python 1.5 and earlier,
 you'd use the :func:`apply` built-in function: ``apply(f, args, kw)`` calls the
 function :func:`f` with the argument tuple *args* and the keyword arguments in
 the dictionary *kw*.  :func:`apply`  is the same in 2.0, but thanks to a patch
-from Greg Ewing, ``f(*args, **kw)`` as a shorter and clearer way to achieve the
+from Greg Ewing, ``f(*args, **kw)`` is a shorter and clearer way to achieve the
 same effect.  This syntax is symmetrical with the syntax for defining
 functions::
 
@@ -1139,7 +1139,7 @@ module.
   Unix, not to be confused with :program:`gzip`\ -format files (which are
   supported by the :mod:`gzip` module) (Contributed by James C. Ahlstrom.)
 
-* :mod:`imputil`: A module that provides a simpler way for writing customised
+* :mod:`imputil`: A module that provides a simpler way for writing customized
   import hooks, in comparison to the existing :mod:`ihooks` module.  (Implemented
   by Greg Stein, with much discussion on python-dev along the way.)
 
index e55eaac..00151d7 100644 (file)
@@ -442,8 +442,8 @@ Python syntax::
    f.grammar = "A ::= B (C D)*"
 
 The dictionary containing attributes can be accessed as the function's
-:attr:`__dict__`. Unlike the :attr:`__dict__` attribute of class instances, in
-functions you can actually assign a new dictionary to :attr:`__dict__`, though
+:attr:`~object.__dict__`. Unlike the :attr:`~object.__dict__` attribute of class instances, in
+functions you can actually assign a new dictionary to :attr:`~object.__dict__`, though
 the new value is restricted to a regular Python dictionary; you *can't* be
 tricky and set it to a :class:`UserDict` instance, or any other random object
 that behaves like a mapping.
@@ -692,7 +692,7 @@ of the more notable changes are:
   faster than the system :func:`malloc` and have less memory overhead.  The
   allocator uses C's :func:`malloc` function to get large pools of memory, and
   then fulfills smaller memory requests from these pools.  It can be enabled by
-  providing the :option:`--with-pymalloc` option to the :program:`configure`
+  providing the :option:`!--with-pymalloc` option to the :program:`configure`
   script; see :file:`Objects/obmalloc.c` for the implementation details.
 
   Authors of C extension modules should test their code with the object allocator
@@ -731,7 +731,7 @@ of the more notable changes are:
          ...
 
   For a fuller discussion of the line I/O changes, see the python-dev summary for
-  January 1-15, 2001 at https://mail.python.org/pipermail/python-dev/2001-January/.
+  January 1--15, 2001 at https://mail.python.org/pipermail/python-dev/2001-January/.
 
 * A new method, :meth:`popitem`, was added to dictionaries to enable
   destructively iterating through the contents of a dictionary; this can be faster
index 885fd60..5f28c29 100644 (file)
@@ -157,7 +157,7 @@ attributes and methods were supported by an object. There were some informal
 conventions, such as defining :attr:`__members__` and :attr:`__methods__`
 attributes that were lists of names, but often the author of an extension type
 or a class wouldn't bother to define them.  You could fall back on inspecting
-the :attr:`__dict__` of an object, but when class inheritance or an arbitrary
+the :attr:`~object.__dict__` of an object, but when class inheritance or an arbitrary
 :meth:`__getattr__` hook were in use this could still be inaccurate.
 
 The one big idea underlying the new class model is that an API for describing
@@ -169,7 +169,7 @@ possible, as well as more exotic constructs.
 Attribute descriptors are objects that live inside class objects, and have a few
 attributes of their own:
 
-* :attr:`__name__` is the attribute's name.
+* :attr:`~definition.__name__` is the attribute's name.
 
 * :attr:`__doc__` is the attribute's docstring.
 
@@ -329,7 +329,7 @@ However, Python 2.2's support for :dfn:`properties` will often be a simpler way
 to trap attribute references.  Writing a :meth:`__getattr__` method is
 complicated because to avoid recursion you can't use regular attribute accesses
 inside them, and instead have to mess around with the contents of
-:attr:`__dict__`. :meth:`__getattr__` methods also end up being called by Python
+:attr:`~object.__dict__`. :meth:`__getattr__` methods also end up being called by Python
 when it checks for other methods such as :meth:`__repr__` or :meth:`__coerce__`,
 and so have to be written with this in mind. Finally, calling a function on
 every attribute access results in a sizable performance loss.
@@ -357,15 +357,15 @@ write::
 That is certainly clearer and easier to write than a pair of
 :meth:`__getattr__`/:meth:`__setattr__` methods that check for the :attr:`size`
 attribute and handle it specially while retrieving all other attributes from the
-instance's :attr:`__dict__`.  Accesses to :attr:`size` are also the only ones
+instance's :attr:`~object.__dict__`.  Accesses to :attr:`size` are also the only ones
 which have to perform the work of calling a function, so references to other
 attributes run at their usual speed.
 
 Finally, it's possible to constrain the list of attributes that can be
-referenced on an object using the new :attr:`__slots__` class attribute. Python
+referenced on an object using the new :attr:`~object.__slots__` class attribute. Python
 objects are usually very dynamic; at any time it's possible to define a new
 attribute on an instance by just doing ``obj.new_attr=1``.   A new-style class
-can define a class attribute named :attr:`__slots__` to limit the legal
+can define a class attribute named :attr:`~object.__slots__` to limit the legal
 attributes  to a particular set of names.  An example will make this clear::
 
    >>> class C(object):
@@ -383,7 +383,7 @@ attributes  to a particular set of names.  An example will make this clear::
    AttributeError: 'C' object has no attribute 'newattr'
 
 Note how you get an :exc:`AttributeError` on the attempt to assign to an
-attribute not listed in :attr:`__slots__`.
+attribute not listed in :attr:`~object.__slots__`.
 
 
 .. _sect-rellinks:
@@ -758,7 +758,7 @@ Here are the changes 2.2 introduces:
   operators.
 
 * Python 2.2 supports some command-line arguments for testing whether code will
-  work with the changed division semantics.  Running python with :option:`-Q
+  work with the changed division semantics.  Running python with :option:`!-Q
   warn` will cause a warning to be issued whenever division is applied to two
   integers.  You can use this to find code that's affected by the change and fix
   it.  By default, Python 2.2 will simply perform classic division without a
@@ -779,8 +779,8 @@ Unicode Changes
 Python's Unicode support has been enhanced a bit in 2.2.  Unicode strings are
 usually stored as UCS-2, as 16-bit unsigned integers. Python 2.2 can also be
 compiled to use UCS-4, 32-bit unsigned integers, as its internal encoding by
-supplying :option:`--enable-unicode=ucs4` to the configure script.   (It's also
-possible to specify :option:`--disable-unicode` to completely disable Unicode
+supplying :option:`!--enable-unicode=ucs4` to the configure script.   (It's also
+possible to specify :option:`!--disable-unicode` to completely disable Unicode
 support.)
 
 When built to use UCS-4 (a "wide Python"), the interpreter can natively handle
@@ -979,7 +979,7 @@ New and Improved Modules
   output have been corrected.  (Contributed by Fred L. Drake, Jr. and Tim Peters.)
 
 * The :mod:`socket` module can be compiled to support IPv6; specify the
-  :option:`--enable-ipv6` option to Python's configure script.  (Contributed by
+  :option:`!--enable-ipv6` option to Python's configure script.  (Contributed by
   Jun-ichiro "itojun" Hagino.)
 
 * Two new format characters were added to the :mod:`struct` module for 64-bit
@@ -1140,7 +1140,7 @@ Some of the more notable changes are:
   in the main Python CVS tree, and many changes have been made to support MacOS X.
 
   The most significant change is the ability to build Python as a framework,
-  enabled by supplying the :option:`--enable-framework` option to the configure
+  enabled by supplying the :option:`!--enable-framework` option to the configure
   script when compiling Python.  According to Jack Jansen, "This installs a self-
   contained Python installation plus the OS X framework "glue" into
   :file:`/Library/Frameworks/Python.framework` (or another location of choice).
@@ -1159,7 +1159,7 @@ Some of the more notable changes are:
      The main change is the possibility to build Python as a
      framework. This installs a self-contained Python installation plus the
      OSX framework "glue" into /Library/Frameworks/Python.framework (or
-     another location of choice). For now there is little immedeate added
+     another location of choice). For now there is little immediate added
      benefit to this (actually, there is the disadvantage that you have to
      change your PATH to be able to find Python), but it is the basis for
      creating a fullblown Python application, porting the MacPython IDE,
@@ -1168,7 +1168,7 @@ Some of the more notable changes are:
      The other change is that most MacPython toolbox modules, which
      interface to all the MacOS APIs such as windowing, quicktime,
      scripting, etc. have been ported. Again, most of these are not of
-     immedeate use, as they need a full application to be really useful, so
+     immediate use, as they need a full application to be really useful, so
      they have been commented out in setup.py. People wanting to experiment
      can uncomment them. Gestalt and Internet Config modules are enabled by
      default.
index b8cdcf1..93930b8 100644 (file)
@@ -291,7 +291,9 @@ PEP 273: Importing Modules from ZIP Archives
 The new :mod:`zipimport` module adds support for importing modules from a ZIP-
 format archive.  You don't need to import the module explicitly; it will be
 automatically imported if a ZIP archive's filename is added to ``sys.path``.
-For example::
+For example:
+
+.. code-block:: shell-session
 
    amk@nyman:~/src/python$ unzip -l /tmp/example.zip
    Archive:  /tmp/example.zip
@@ -392,7 +394,7 @@ be shared between all three operating systems without needing to convert the
 line-endings.
 
 This feature can be disabled when compiling Python by specifying the
-:option:`--without-universal-newlines` switch when running Python's
+:option:`!--without-universal-newlines` switch when running Python's
 :program:`configure` script.
 
 
@@ -1111,10 +1113,10 @@ Here are all of the changes that Python 2.3 makes to the core Python language.
      <type '_socket.socket'>
 
 * One of the noted incompatibilities between old- and new-style classes has been
-  removed: you can now assign to the :attr:`__name__` and :attr:`__bases__`
+  removed: you can now assign to the :attr:`~definition.__name__` and :attr:`~class.__bases__`
   attributes of new-style classes.  There are some restrictions on what can be
-  assigned to :attr:`__bases__` along the lines of those relating to assigning to
-  an instance's :attr:`__class__` attribute.
+  assigned to :attr:`~class.__bases__` along the lines of those relating to assigning to
+  an instance's :attr:`~instance.__class__` attribute.
 
 .. ======================================================================
 
@@ -1681,13 +1683,13 @@ Date and time types suitable for expressing timestamps were added as the
 fancy features, and just stick to the basics of representing time.
 
 The three primary types are: :class:`date`, representing a day, month, and year;
-:class:`time`, consisting of hour, minute, and second; and :class:`datetime`,
-which contains all the attributes of both :class:`date` and :class:`time`.
+:class:`~datetime.time`, consisting of hour, minute, and second; and :class:`~datetime.datetime`,
+which contains all the attributes of both :class:`date` and :class:`~datetime.time`.
 There's also a :class:`timedelta` class representing differences between two
 points in time, and time zone logic is implemented by classes inheriting from
 the abstract :class:`tzinfo` class.
 
-You can create instances of :class:`date` and :class:`time` by either supplying
+You can create instances of :class:`date` and :class:`~datetime.time` by either supplying
 keyword arguments to the appropriate constructor, e.g.
 ``datetime.date(year=1972, month=10, day=15)``, or by using one of a number of
 class methods.  For example, the :meth:`date.today` class method returns the
@@ -1706,7 +1708,7 @@ number of methods for producing formatted strings from objects::
    '2002 30 Dec'
 
 The :meth:`replace` method allows modifying one or more fields  of a
-:class:`date` or :class:`datetime` instance, returning a new instance::
+:class:`date` or :class:`~datetime.datetime` instance, returning a new instance::
 
    >>> d = datetime.datetime.now()
    >>> d
@@ -1716,11 +1718,11 @@ The :meth:`replace` method allows modifying one or more fields  of a
    >>>
 
 Instances can be compared, hashed, and converted to strings (the result is the
-same as that of :meth:`isoformat`).  :class:`date` and :class:`datetime`
+same as that of :meth:`isoformat`).  :class:`date` and :class:`~datetime.datetime`
 instances can be subtracted from each other, and added to :class:`timedelta`
 instances.  The largest missing feature is that there's no standard library
 support for parsing strings and getting back a :class:`date` or
-:class:`datetime`.
+:class:`~datetime.datetime`.
 
 For more information, refer to the module's reference documentation.
 (Contributed by Tim Peters.)
@@ -1761,7 +1763,9 @@ This returns an object containing all of the option values, and a list of
 strings containing the remaining arguments.
 
 Invoking the script with the various arguments now works as you'd expect it to.
-Note that the length argument is automatically converted to an integer. ::
+Note that the length argument is automatically converted to an integer.
+
+.. code-block:: shell-session
 
    $ ./python opt.py -i data arg1
    <Values at 0x400cad4c: {'input': 'data', 'length': None}>
@@ -1771,7 +1775,9 @@ Note that the length argument is automatically converted to an integer. ::
    []
    $
 
-The help message is automatically generated for you::
+The help message is automatically generated for you:
+
+.. code-block:: shell-session
 
    $ ./python opt.py --help
    usage: opt.py [options]
@@ -1806,9 +1812,9 @@ pools of memory and then fulfills smaller memory requests from these pools.
 
 In 2.1 and 2.2, pymalloc was an experimental feature and wasn't enabled by
 default; you had to explicitly enable it when compiling Python by providing the
-:option:`--with-pymalloc` option to the :program:`configure` script.  In 2.3,
+:option:`!--with-pymalloc` option to the :program:`configure` script.  In 2.3,
 pymalloc has had further enhancements and is now enabled by default; you'll have
-to supply :option:`--without-pymalloc` to disable it.
+to supply :option:`!--without-pymalloc` to disable it.
 
 This change is transparent to code written in Python; however, pymalloc may
 expose bugs in C extensions.  Authors of C extension modules should test their
@@ -1847,7 +1853,7 @@ Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging
 features to catch memory overwrites and doubled frees in both extension modules
 and in the interpreter itself.  To enable this support, compile a debugging
 version of the Python interpreter by running :program:`configure` with
-:option:`--with-pydebug`.
+:option:`!--with-pydebug`.
 
 To aid extension writers, a header file :file:`Misc/pymemcompat.h` is
 distributed with the source to Python 2.3 that allows Python extensions to use
@@ -1873,11 +1879,11 @@ Changes to Python's build process and to the C API include:
 
 * The cycle detection implementation used by the garbage collection has proven
   to be stable, so it's now been made mandatory.  You can no longer compile Python
-  without it, and the :option:`--with-cycle-gc` switch to :program:`configure` has
+  without it, and the :option:`!--with-cycle-gc` switch to :program:`configure` has
   been removed.
 
 * Python can now optionally be built as a shared library
-  (:file:`libpython2.3.so`) by supplying :option:`--enable-shared` when running
+  (:file:`libpython2.3.so`) by supplying :option:`!--enable-shared` when running
   Python's :program:`configure` script.  (Contributed by Ondrej Palkovsky.)
 
 * The :c:macro:`DL_EXPORT` and :c:macro:`DL_IMPORT` macros are now deprecated.
@@ -1886,7 +1892,7 @@ Changes to Python's build process and to the C API include:
   generally use the :c:macro:`PyAPI_FUNC` and :c:macro:`PyAPI_DATA` macros.
 
 * The interpreter can be compiled without any docstrings for the built-in
-  functions and modules by supplying :option:`--without-doc-strings` to the
+  functions and modules by supplying :option:`!--without-doc-strings` to the
   :program:`configure` script. This makes the Python executable about 10% smaller,
   but will also mean that you can't get help for Python's built-ins.  (Contributed
   by Gustavo Niemeyer.)
@@ -1920,7 +1926,7 @@ Changes to Python's build process and to the C API include:
 
 * If you dynamically allocate type objects in your extension, you should be
   aware of a change in the rules relating to the :attr:`__module__` and
-  :attr:`__name__` attributes.  In summary, you will want to ensure the type's
+  :attr:`~definition.__name__` attributes.  In summary, you will want to ensure the type's
   dictionary contains a ``'__module__'`` key; making the module name the part of
   the type name leading up to the final period will no longer have the desired
   effect.  For more detail, read the API reference documentation or the  source.
@@ -2078,4 +2084,3 @@ Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew
 MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans
 Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman
 Suzi, Jason Tishler, Just van Rossum.
-
index fb4558b..8db90cc 100644 (file)
@@ -1425,7 +1425,9 @@ specifying the :const:`doctest.REPORT_UDIFF` (unified diffs),
            print word
 
 Running the above function's tests with :const:`doctest.REPORT_UDIFF` specified,
-you get the following output::
+you get the following output:
+
+.. code-block:: none
 
    **********************************************************************
    File "t.py", line 15, in g
@@ -1481,10 +1483,10 @@ Some of the changes to Python's build process and to the C API are:
 
 * Python can now be built with additional profiling for the interpreter itself,
   intended as an aid to people developing the Python core.  Providing
-  :option:`--enable-profiling` to the :program:`configure` script will let you
+  :option:`!--enable-profiling` to the :program:`configure` script will let you
   profile the interpreter with :program:`gprof`, and providing the
-  :option:`--with-tsc` switch enables profiling using the Pentium's Time-Stamp-
-  Counter register.  Note that the :option:`--with-tsc` switch is slightly
+  :option:`!--with-tsc` switch enables profiling using the Pentium's Time-Stamp-
+  Counter register.  Note that the :option:`!--with-tsc` switch is slightly
   misnamed, because the profiling feature also works on the PowerPC platform,
   though that processor architecture doesn't call that register "the TSC
   register".  (Contributed by Jeremy Hylton.)
@@ -1521,7 +1523,7 @@ code:
   empty list instead of raising a :exc:`TypeError` exception if called with no
   arguments.
 
-* You can no longer compare the :class:`date` and :class:`datetime` instances
+* You can no longer compare the :class:`date` and :class:`~datetime.datetime` instances
   provided by the :mod:`datetime` module.  Two  instances of different classes
   will now always be unequal, and  relative comparisons (``<``, ``>``) will raise
   a :exc:`TypeError`.
index 093189e..db8f9df 100644 (file)
@@ -236,7 +236,7 @@ the repository.
 Before a package can be uploaded, you must be able to build a distribution using
 the :command:`sdist` Distutils command.  Once that works, you can run ``python
 setup.py upload`` to add your package to the PyPI archive.  Optionally you can
-GPG-sign the package by supplying the :option:`--sign` and :option:`--identity`
+GPG-sign the package by supplying the :option:`!--sign` and :option:`!--identity`
 options.
 
 Package uploading was implemented by Martin von Löwis and Richard Jones.
@@ -1307,7 +1307,7 @@ complete list of changes, or look through the SVN logs for all the details.
 
   (Contributed by Skip Montanaro and Andrew McNamara.)
 
-* The :class:`datetime` class in the :mod:`datetime`  module now has a
+* The :class:`~datetime.datetime` class in the :mod:`datetime`  module now has a
   ``strptime(string, format)``  method for parsing date strings, contributed
   by Josh Spoerri. It uses the same format characters as :func:`time.strptime` and
   :func:`time.strftime`::
@@ -1497,7 +1497,7 @@ complete list of changes, or look through the SVN logs for all the details.
 * The :mod:`pyexpat` module now uses version 2.0 of the Expat parser.
   (Contributed by Trent Mick.)
 
-* The :class:`Queue` class provided by the :mod:`Queue` module gained two new
+* The :class:`~queue.Queue` class provided by the :mod:`Queue` module gained two new
   methods.  :meth:`join` blocks until all items in the queue have been retrieved
   and all processing work on the items  have been completed.  Worker threads call
   the other new method,  :meth:`task_done`, to signal that processing for an item
@@ -1639,7 +1639,7 @@ complete list of changes, or look through the SVN logs for all the details.
 
 * The :mod:`webbrowser` module received a number of enhancements. It's now
   usable as a script with ``python -m webbrowser``, taking a URL as the argument;
-  there are a number of switches  to control the behaviour (:option:`-n` for a new
+  there are a number of switches  to control the behaviour (:option:`!-n` for a new
   browser window,  :option:`!-t` for a new tab).  New module-level functions,
   :func:`open_new` and :func:`open_new_tab`, were added  to support this.  The
   module's :func:`open` function supports an additional feature, an *autoraise*
@@ -1649,7 +1649,7 @@ complete list of changes, or look through the SVN logs for all the details.
 
   .. Patch #754022
 
-* The :mod:`xmlrpclib` module now supports returning  :class:`datetime` objects
+* The :mod:`xmlrpclib` module now supports returning  :class:`~datetime.datetime` objects
   for the XML-RPC date type.  Supply  ``use_datetime=True`` to the :func:`loads`
   function or the :class:`Unmarshaller` class to enable this feature. (Contributed
   by Skip Montanaro.)
@@ -2209,7 +2209,7 @@ Port-Specific Changes
 * MacOS X (10.3 and higher): dynamic loading of modules now uses the
   :c:func:`dlopen` function instead of MacOS-specific functions.
 
-* MacOS X: an :option:`--enable-universalsdk` switch was added to the
+* MacOS X: an :option:`!--enable-universalsdk` switch was added to the
   :program:`configure` script that compiles the interpreter as a universal binary
   able to run on both PowerPC and Intel processors. (Contributed by Ronald
   Oussoren; :issue:`2573`.)
index 4ab1656..4fc0c36 100644 (file)
@@ -58,7 +58,7 @@ Python 2.6 incorporates new features and syntax from 3.0 while
 remaining compatible with existing code by not removing older features
 or syntax.  When it's not possible to do that, Python 2.6 tries to do
 what it can, adding compatibility functions in a
-:mod:`future_builtins` module and a :option:`-3` switch to warn about
+:mod:`future_builtins` module and a :option:`!-3` switch to warn about
 usages that will become unsupported in 3.0.
 
 Some significant new packages have been added to the standard library,
@@ -116,7 +116,7 @@ module has versions with the new 3.0 semantics.  Code written to be
 compatible with 3.0 can do ``from future_builtins import hex, map`` as
 necessary.
 
-A new command-line switch, :option:`-3`, enables warnings
+A new command-line switch, :option:`!-3`, enables warnings
 about features that will be removed in Python 3.0.  You can run code
 with this switch to see how much work will be necessary to port
 code to 3.0.  The value of this switch is available
@@ -613,10 +613,10 @@ multiple of 4.
         result = queue.get()
         print 'Factorial', N, '=', result
 
-A :class:`Queue` is used to communicate the result of the factorial.
-The :class:`Queue` object is stored in a global variable.
+A :class:`~queue.Queue` is used to communicate the result of the factorial.
+The :class:`~queue.Queue` object is stored in a global variable.
 The child process will use the value of the variable when the child
-was created; because it's a :class:`Queue`, parent and child can use
+was created; because it's a :class:`~queue.Queue`, parent and child can use
 the object to communicate.  (If the parent were to change the value of
 the global variable, the child's value would be unaffected, and vice
 versa.)
@@ -2131,7 +2131,7 @@ changes, or look through the Subversion logs for all the details.
 
   (Contributed by Christian Heimes and Mark Dickinson.)
 
-* :class:`mmap` objects now have a :meth:`rfind` method that searches for a
+* :class:`~mmap.mmap` objects now have a :meth:`rfind` method that searches for a
   substring beginning at the end of the string and searching
   backwards.  The :meth:`find` method also gained an *end* parameter
   giving an index at which to stop searching.
@@ -2630,7 +2630,7 @@ changes, or look through the Subversion logs for all the details.
   :class:`datetime.date` and :class:`datetime.time` to the
   :class:`xmlrpclib.DateTime` type; the conversion semantics were
   not necessarily correct for all applications.  Code using
-  :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
+  :mod:`xmlrpclib` should convert :class:`date` and :class:`~datetime.time`
   instances. (:issue:`1330538`)  The code can also handle
   dates before 1900 (contributed by Ralf Schmitt; :issue:`2014`)
   and 64-bit integers represented by using ``<i8>`` in XML-RPC responses
@@ -2992,7 +2992,7 @@ Changes to Python's build process and to the C API include:
 
 * On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.
   The :program:`configure` script
-  can take a :option:`--with-universal-archs=[32-bit|64-bit|all]`
+  can take a :option:`!--with-universal-archs=[32-bit|64-bit|all]`
   switch, controlling whether the binaries are built for 32-bit
   architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.
   (Contributed by Ronald Oussoren.)
@@ -3147,7 +3147,7 @@ Port-Specific Changes: Mac OS X
 
 * When compiling a framework build of Python, you can now specify the
   framework name to be used by providing the
-  :option:`--with-framework-name=` option to the
+  :option:`!--with-framework-name=` option to the
   :program:`configure` script.
 
 * The :mod:`macfs` module has been removed.  This in turn required the
@@ -3283,7 +3283,7 @@ that may require changes to your code:
   :class:`datetime.date` and :class:`datetime.time` to the
   :class:`xmlrpclib.DateTime` type; the conversion semantics were
   not necessarily correct for all applications.  Code using
-  :mod:`xmlrpclib` should convert :class:`date` and :class:`time`
+  :mod:`xmlrpclib` should convert :class:`date` and :class:`~datetime.time`
   instances. (:issue:`1330538`)
 
 * (3.0-warning mode) The :class:`Exception` class now warns
index 702aeb4..55392fc 100644 (file)
@@ -104,7 +104,7 @@ Some key consequences of the long-term significance of 2.7 are:
   when compared to earlier 2.x versions. Python 2.7 is currently expected to
   remain supported by the core development team (receiving security updates
   and other bug fixes) until at least 2020 (10 years after its initial
-  release, compared to the more typical support period of 18-24 months).
+  release, compared to the more typical support period of 18--24 months).
 
 * As the Python 2.7 standard library ages, making effective use of the
   Python Package Index (either directly or via a redistributor) becomes
@@ -198,8 +198,8 @@ Other new Python3-mode warnings include:
 
 * :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
   which are not supported in 3.x, now trigger warnings.
-* The :option:`-3` switch now automatically
-  enables the :option:`-Qwarn <-Q>` switch that causes warnings
+* The :option:`!-3` switch now automatically
+  enables the :option:`!-Qwarn` switch that causes warnings
   about using classic division with integers and long integers.
 
 
@@ -245,8 +245,8 @@ Deleting an entry and reinserting it will move it to the end::
     [('first', 1), ('third', 3), ('second', 5)]
 
 The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
-argument that defaults to True.  If *last* is True, the most recently
-added key is returned and removed; if it's False, the
+argument that defaults to ``True``.  If *last* is true, the most recently
+added key is returned and removed; if it's false, the
 oldest key is selected::
 
     >>> od = OrderedDict([(x,0) for x in range(20)])
@@ -390,7 +390,7 @@ Here's an example::
     args = parser.parse_args()
     print args.__dict__
 
-Unless you override it, :option:`-h` and :option:`--help` switches
+Unless you override it, :option:`!-h` and :option:`!--help` switches
 are automatically added, and produce neatly formatted output::
 
     -> ./python.exe argparse-example.py --help
@@ -532,7 +532,7 @@ implemented by Vinay Sajip, are:
   calling ``log.getChild('network.listen')`` is equivalent to
   ``getLogger('app.network.listen')``.
 
-* The :class:`~logging.LoggerAdapter` class gained a
+* The :class:`~logging.LoggerAdapter` class gained an
   :meth:`~logging.LoggerAdapter.isEnabledFor` method that takes a
   *level* and returns whether the underlying logger would
   process a message of that level of importance.
@@ -960,7 +960,7 @@ Several performance enhancements have been added:
   benchmark results on 32-bit machines have been mixed.  Therefore,
   the default is to use base 2**30 on 64-bit machines and base 2**15
   on 32-bit machines; on Unix, there's a new configure option
-  :option:`--enable-big-digits` that can be used to override this default.
+  :option:`!--enable-big-digits` that can be used to override this default.
 
   Apart from the performance improvements this change should be
   invisible to end users, with one exception: for testing and
@@ -989,7 +989,7 @@ Several performance enhancements have been added:
   Gregory Smith; :issue:`1087418`).
 
 * The implementation of ``%`` checks for the left-side operand being
-  a Python string and special-cases it; this results in a 1-3%
+  a Python string and special-cases it; this results in a 1--3%
   performance increase for applications that frequently use ``%``
   with strings, such as templating libraries.
   (Implemented by Collin Winter; :issue:`5176`.)
@@ -1518,7 +1518,7 @@ changes, or look through the Subversion logs for all the details.
 * The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
   supports socket timeouts and disabling the Nagle algorithm.
   The :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute
-  defaults to False; if overridden to be True,
+  defaults to ``False``; if overridden to be true,
   new request connections will have the TCP_NODELAY option set to
   prevent buffering many small sends into a single TCP packet.
   The :attr:`~SocketServer.BaseServer.timeout` class attribute can hold
@@ -1844,12 +1844,12 @@ Consult the :mod:`unittest` module documentation for more details.
 
 The :func:`~unittest.main` function supports some other new options:
 
-* :option:`-b <unittest -b>` or :option:`--buffer` will buffer the standard output
+* :option:`-b <unittest -b>` or :option:`!--buffer` will buffer the standard output
   and standard error streams during each test.  If the test passes,
   any resulting output will be discarded; on failure, the buffered
   output will be displayed.
 
-* :option:`-c <unittest -c>` or :option:`--catch` will cause the control-C interrupt
+* :option:`-c <unittest -c>` or :option:`!--catch` will cause the control-C interrupt
   to be handled more gracefully.  Instead of interrupting the test
   process immediately, the currently running test will be completed
   and then the partial results up to the interruption will be reported.
@@ -1863,7 +1863,7 @@ The :func:`~unittest.main` function supports some other new options:
   :func:`~unittest.removeHandler` decorator that can be used to mark tests that
   should have the control-C handling disabled.
 
-* :option:`-f <unittest -f>` or :option:`--failfast` makes
+* :option:`-f <unittest -f>` or :option:`!--failfast` makes
   test execution stop immediately when a test fails instead of
   continuing to execute further tests.  (Suggested by Cliff Dyer and
   implemented by Michael Foord; :issue:`8074`.)
@@ -1879,7 +1879,7 @@ The error messages for :meth:`~unittest.TestCase.assertEqual`,
 :meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
 failures now provide more information.  If you set the
 :attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
-True, both the standard error message and any additional message you
+true, both the standard error message and any additional message you
 provide will be printed for failures.  (Added by Michael Foord; :issue:`5663`.)
 
 The :meth:`~unittest.TestCase.assertRaises` method now
@@ -1986,7 +1986,7 @@ GvR worked on merging them into Python's version of :mod:`unittest`.
   sequence comparison methods do.
 
 :func:`unittest.main` now takes an optional ``exit`` argument.  If
-False, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing
+false, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing
 :func:`~unittest.main` to be used from the interactive interpreter.
 (Contributed by J. Pablo Fernández; :issue:`3379`.)
 
@@ -2238,19 +2238,19 @@ Changes to Python's build process and to the C API include:
   with ``Py``, or with ``_ctypes``.  (Implemented by Thomas
   Heller; :issue:`3102`.)
 
-* New configure option: the :option:`--with-system-expat` switch allows
+* New configure option: the :option:`!--with-system-expat` switch allows
   building the :mod:`pyexpat` module to use the system Expat library.
   (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)
 
 * New configure option: the
-  :option:`--with-valgrind` option will now disable the pymalloc
+  :option:`!--with-valgrind` option will now disable the pymalloc
   allocator, which is difficult for the Valgrind memory-error detector
   to analyze correctly.
   Valgrind will therefore be better at detecting memory leaks and
   overruns. (Contributed by James Henstridge; :issue:`2422`.)
 
 * New configure option: you can now supply an empty string to
-  :option:`--with-dbmliborder=` in order to disable all of the various
+  :option:`!--with-dbmliborder=` in order to disable all of the various
   DBM modules.  (Added by Arfrever Frehtes Taifersar Arahesis;
   :issue:`6491`.)
 
@@ -2290,7 +2290,9 @@ There is an existing data type already used for this,
 written in pure Python could cause a segmentation fault by taking a
 :c:type:`PyCObject` from module A and somehow substituting it for the
 :c:type:`PyCObject` in module B.   Capsules know their own name,
-and getting the pointer requires providing the name::
+and getting the pointer requires providing the name:
+
+.. code-block:: c
 
    void *vtable;
 
@@ -2395,19 +2397,19 @@ Other Changes and Fixes
   renamed, moved, or is accessed through different paths.  (Patch by
   Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)
 
-* The :file:`regrtest.py` script now takes a :option:`--randseed=`
+* The :file:`regrtest.py` script now takes a :option:`!--randseed=`
   switch that takes an integer that will be used as the random seed
-  for the :option:`-r` option that executes tests in random order.
-  The :option:`-r` option also reports the seed that was used
+  for the :option:`!-r` option that executes tests in random order.
+  The :option:`!-r` option also reports the seed that was used
   (Added by Collin Winter.)
 
-* Another :file:`regrtest.py` switch is :option:`-j`, which
+* Another :file:`regrtest.py` switch is :option:`!-j`, which
   takes an integer specifying how many tests run in parallel. This
   allows reducing the total runtime on multi-core machines.
   This option is compatible with several other options, including the
   :option:`!-R` switch which is known to produce long runtimes.
   (Added by Antoine Pitrou, :issue:`6152`.)  This can also be used
-  with a new :option:`-F` switch that runs selected tests in a loop
+  with a new :option:`!-F` switch that runs selected tests in a loop
   until they fail.  (Added by Antoine Pitrou; :issue:`7312`.)
 
 * When executed as a script, the :file:`py_compile.py` module now
@@ -2616,4 +2618,3 @@ The author would like to thank the following people for offering
 suggestions, corrections and assistance with various drafts of this
 article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
 Hugh Secker-Walker.
-
index 044d7be..5ecf2eb 100644 (file)
@@ -117,7 +117,9 @@ You can also customize the separator between items, e.g.::
 
   print("There are <", 2**32, "> possibilities!", sep="")
 
-which produces::
+which produces:
+
+.. code-block:: none
 
   There are <4294967296> possibilities!
 
@@ -783,8 +785,8 @@ Operators And Special Methods
   :attr:`func_closure`, :attr:`func_code`, :attr:`func_defaults`,
   :attr:`func_dict`, :attr:`func_doc`, :attr:`func_globals`,
   :attr:`func_name` were renamed to :attr:`__closure__`,
-  :attr:`__code__`, :attr:`__defaults__`, :attr:`__dict__`,
-  :attr:`__doc__`, :attr:`__globals__`, :attr:`__name__`,
+  :attr:`__code__`, :attr:`__defaults__`, :attr:`~object.__dict__`,
+  :attr:`__doc__`, :attr:`__globals__`, :attr:`~definition.__name__`,
   respectively.
 
 * :meth:`__nonzero__` is now :meth:`__bool__`.
@@ -902,7 +904,7 @@ best strategy is the following:
    port from Python 2.x to Python 2.(x+1).  Make sure all your tests
    pass.
 
-2. (Still using 2.6:) Turn on the :option:`-3` command line switch.
+2. (Still using 2.6:) Turn on the :option:`!-3` command line switch.
    This enables warnings about features that will be removed (or
    change) in 3.0.  Run your test suite again, and fix code that you
    get warnings about until there are no warnings left, and all your
index c1a1687..5c31401 100644 (file)
@@ -548,5 +548,5 @@ that may require changes to your code:
 
 * The automatic name remapping in the pickle module for protocol 2 or lower can
   make Python 3.1 pickles unreadable in Python 3.0.  One solution is to use
-  protocol 3.  Another solution is to set the *fix_imports* option to **False**.
+  protocol 3.  Another solution is to set the *fix_imports* option to ``False``.
   See the discussion above for more details.
index baaf797..9acc734 100644 (file)
@@ -160,6 +160,8 @@ each with their own argument patterns and help displays::
     parser_m.add_argument('-c', '--course', type=int, required=True)
     parser_m.add_argument('-s', '--speed', type=int, default=0)
 
+.. code-block:: shell-session
+
     $ ./helm.py --help                         # top level help (launch and move)
     $ ./helm.py launch --help                  # help for launch options
     $ ./helm.py launch --missiles              # set missiles=True and torpedos=False
@@ -311,14 +313,14 @@ aspects that are visible to the programmer:
   of the actual file that was imported:
 
    >>> import collections
-   >>> collections.__cached__
+   >>> collections.__cached__ # doctest: +SKIP
    'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
 
 * The tag that is unique to each interpreter is accessible from the :mod:`imp`
   module:
 
    >>> import imp
-   >>> imp.get_tag()
+   >>> imp.get_tag() # doctest: +SKIP
    'cpython-32'
 
 * Scripts that try to deduce source filename from the imported file now need to
@@ -327,7 +329,7 @@ aspects that are visible to the programmer:
 
   >>> imp.source_from_cache('c:/py32/lib/__pycache__/collections.cpython-32.pyc')
   'c:/py32/lib/collections.py'
-  >>> imp.cache_from_source('c:/py32/lib/collections.py')
+  >>> imp.cache_from_source('c:/py32/lib/collections.py') # doctest: +SKIP
   'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
 
 * The :mod:`py_compile` and :mod:`compileall` modules have been updated to
@@ -478,7 +480,9 @@ Some smaller changes made to the core Python language are:
 
 * The interpreter can now be started with a quiet option, ``-q``, to prevent
   the copyright and version information from being displayed in the interactive
-  mode.  The option can be introspected using the :attr:`sys.flags` attribute::
+  mode.  The option can be introspected using the :attr:`sys.flags` attribute:
+
+  .. code-block:: shell-session
 
     $ python -q
     >>> sys.flags
@@ -528,7 +532,7 @@ Some smaller changes made to the core Python language are:
   original object.
 
   >>> with memoryview(b'abcdefgh') as v:
-          print(v.tolist())
+  ...     print(v.tolist())
   [97, 98, 99, 100, 101, 102, 103, 104]
 
   (Added by Antoine Pitrou; :issue:`9757`.)
@@ -564,16 +568,19 @@ Some smaller changes made to the core Python language are:
   expect a tuple as an argument.  This is a big step forward in making the C
   structures as flexible as their pure Python counterparts:
 
+  >>> import sys
   >>> isinstance(sys.version_info, tuple)
   True
-  >>> 'Version %d.%d.%d %s(%d)' % sys.version_info
+  >>> 'Version %d.%d.%d %s(%d)' % sys.version_info # doctest: +SKIP
   'Version 3.2.0 final(0)'
 
   (Suggested by Arfrever Frehtes Taifersar Arahesis and implemented
   by Benjamin Peterson in :issue:`8413`.)
 
 * Warnings are now easier to control using the :envvar:`PYTHONWARNINGS`
-  environment variable as an alternative to using ``-W`` at the command line::
+  environment variable as an alternative to using ``-W`` at the command line:
+
+  .. code-block:: shell-session
 
     $ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'
 
@@ -595,7 +602,9 @@ Some smaller changes made to the core Python language are:
   object ensures it closes the underlying operating system resource
   (usually, a file descriptor), the delay in deallocating the object could
   produce various issues, especially under Windows.  Here is an example
-  of enabling the warning from the command line::
+  of enabling the warning from the command line:
+
+  .. code-block:: shell-session
 
       $ python -q -Wdefault
       >>> f = open("foo", "wb")
@@ -749,18 +758,18 @@ functools
 
   >>> import functools
   >>> @functools.lru_cache(maxsize=300)
-  >>> def get_phone_number(name):
-          c = conn.cursor()
-          c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
-          return c.fetchone()[0]
+  ... def get_phone_number(name):
+  ...     c = conn.cursor()
+  ...     c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
+  ...     return c.fetchone()[0]
 
-  >>> for name in user_requests:
-          get_phone_number(name)        # cached lookup
+  >>> for name in user_requests:        # doctest: +SKIP
+  ...     get_phone_number(name)        # cached lookup
 
   To help with choosing an effective cache size, the wrapped function is
   instrumented for tracking cache statistics:
 
-  >>> get_phone_number.cache_info()
+  >>> get_phone_number.cache_info()     # doctest: +SKIP
   CacheInfo(hits=4805, misses=980, maxsize=300, currsize=300)
 
   If the phonelist table gets updated, the outdated contents of the cache can be
@@ -815,7 +824,7 @@ functools
   modern :term:`key function`:
 
   >>> # locale-aware sort order
-  >>> sorted(iterable, key=cmp_to_key(locale.strcoll))
+  >>> sorted(iterable, key=cmp_to_key(locale.strcoll)) # doctest: +SKIP
 
   For sorting examples and a brief sorting tutorial, see the `Sorting HowTo
   <https://wiki.python.org/moin/HowTo/Sorting/>`_ tutorial.
@@ -853,7 +862,8 @@ collections
   which only have positive counts, and the latter is more suitable for use cases
   that allow negative counts:
 
-  >>> tally = Counter(dogs=5, cat=3)
+  >>> from collections import Counter
+  >>> tally = Counter(dogs=5, cats=3)
   >>> tally -= Counter(dogs=2, cats=8)    # saturating subtraction
   >>> tally
   Counter({'dogs': 3})
@@ -876,6 +886,7 @@ collections
   an ordered dictionary can be used to track order of access by aging entries
   from the oldest to the most recently accessed.
 
+  >>> from collections import OrderedDict
   >>> d = OrderedDict.fromkeys(['a', 'b', 'X', 'd', 'e'])
   >>> list(d)
   ['a', 'b', 'X', 'd', 'e']
@@ -889,6 +900,7 @@ collections
   :meth:`~collections.deque.count` and :meth:`~collections.deque.reverse` that
   make them more substitutable for :class:`list` objects:
 
+  >>> from collections import deque
   >>> d = deque('simsalabim')
   >>> d.count('s')
   2
@@ -989,13 +1001,13 @@ datetime and time
   after 1900.  The new supported year range is from 1000 to 9999 inclusive.
 
 * Whenever a two-digit year is used in a time tuple, the interpretation has been
-  governed by :attr:`time.accept2dyear`.  The default is *True* which means that
+  governed by :attr:`time.accept2dyear`.  The default is ``True`` which means that
   for a two-digit year, the century is guessed according to the POSIX rules
   governing the ``%y`` strptime format.
 
   Starting with Py3.2, use of the century guessing heuristic will emit a
   :exc:`DeprecationWarning`.  Instead, it is recommended that
-  :attr:`time.accept2dyear` be set to *False* so that large date ranges
+  :attr:`time.accept2dyear` be set to ``False`` so that large date ranges
   can be used without guesswork::
 
     >>> import time, warnings
@@ -1031,9 +1043,10 @@ The :mod:`math` module has been updated with six new functions inspired by the
 C99 standard.
 
 The :func:`~math.isfinite` function provides a reliable and fast way to detect
-special values.  It returns *True* for regular numbers and *False* for *Nan* or
+special values.  It returns ``True`` for regular numbers and ``False`` for *Nan* or
 *Infinity*:
 
+>>> from math import isfinite
 >>> [isfinite(x) for x in (123, 4.56, float('Nan'), float('Inf'))]
 [True, True, False, False]
 
@@ -1041,6 +1054,7 @@ The :func:`~math.expm1` function computes ``e**x-1`` for small values of *x*
 without incurring the loss of precision that usually accompanies the subtraction
 of nearly equal quantities:
 
+>>> from math import expm1
 >>> expm1(0.013671875)   # more accurate way to compute e**x-1 for a small x
 0.013765762467652909
 
@@ -1048,6 +1062,7 @@ The :func:`~math.erf` function computes a probability integral or `Gaussian
 error function <https://en.wikipedia.org/wiki/Error_function>`_.  The
 complementary error function, :func:`~math.erfc`, is ``1 - erf(x)``:
 
+>>> from math import erf, erfc, sqrt
 >>> erf(1.0/sqrt(2.0))   # portion of normal distribution within 1 standard deviation
 0.682689492137086
 >>> erfc(1.0/sqrt(2.0))  # portion of normal distribution outside 1 standard deviation
@@ -1061,6 +1076,7 @@ the function is related to factorials, it grows large even for small values of
 *x*, so there is also a :func:`~math.lgamma` function for computing the natural
 logarithm of the gamma function:
 
+>>> from math import gamma, lgamma
 >>> gamma(7.0)           # six factorial
 720.0
 >>> lgamma(801.0)        # log(800 factorial)
@@ -1177,7 +1193,7 @@ exception or silently drop the event depending on the value of
 
 The use of filters has been simplified.  Instead of creating a
 :class:`~logging.Filter` object, the predicate can be any Python callable that
-returns *True* or *False*.
+returns ``True`` or ``False``.
 
 There were a number of other improvements that add flexibility and simplify
 configuration.  See the module documentation for a full listing of changes in
@@ -1279,7 +1295,7 @@ Some of the hashing details are exposed through a new attribute,
 prime modulus, the hash values for *infinity* and *nan*, and the multiplier
 used for the imaginary part of a number:
 
->>> sys.hash_info
+>>> sys.hash_info # doctest: +SKIP
 sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003)
 
 An early decision to limit the inter-operability of various numeric types has
@@ -1302,6 +1318,8 @@ Similar changes were made to :class:`fractions.Fraction` so that the
 :meth:`~fractions.Fraction.from_float()` and :meth:`~fractions.Fraction.from_decimal`
 methods are no longer needed (:issue:`8294`):
 
+>>> from decimal import Decimal
+>>> from fractions import Fraction
 >>> Decimal(1.1)
 Decimal('1.100000000000000088817841970012523233890533447265625')
 >>> Fraction(1.1)
@@ -1384,6 +1402,7 @@ The :mod:`gzip` module also gains the :func:`~gzip.compress` and
 decompression.  Keep in mind that text needs to be encoded as :class:`bytes`
 before compressing and decompressing:
 
+>>> import gzip
 >>> s = 'Three shall be the number thou shalt count, '
 >>> s += 'and the number of the counting shall be three'
 >>> b = s.encode()                        # convert to utf-8
@@ -1393,7 +1412,7 @@ before compressing and decompressing:
 >>> len(c)
 77
 >>> gzip.decompress(c).decode()[:42]      # decompress and convert to text
-'Three shall be the number thou shalt count,'
+'Three shall be the number thou shalt count'
 
 (Contributed by Anand B. Pillai in :issue:`3488`; and by Antoine Pitrou, Nir
 Aides and Brian Curtin in :issue:`9962`, :issue:`1675951`, :issue:`7471` and
@@ -1420,7 +1439,7 @@ which is now deprecated.  If specified, the optional *filter* parameter needs to
 be a :term:`keyword argument`.  The user-supplied filter function accepts a
 :class:`~tarfile.TarInfo` object and returns an updated
 :class:`~tarfile.TarInfo` object, or if it wants the file to be excluded, the
-function can return *None*::
+function can return ``None``::
 
     >>> import tarfile, glob
 
@@ -1469,7 +1488,7 @@ evaluating expression strings using the Python literal
 syntax.  The :func:`ast.literal_eval` function serves as a secure alternative to
 the builtin :func:`eval` function which is easily abused.  Python 3.2 adds
 :class:`bytes` and :class:`set` literals to the list of supported types:
-strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
+strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and ``None``.
 
 ::
 
@@ -1495,6 +1514,7 @@ variables.  The :mod:`os` module provides two new functions,
 :func:`~os.fsencode` and :func:`~os.fsdecode`, for encoding and decoding
 filenames:
 
+>>> import os
 >>> filename = 'Sehenswürdigkeiten'
 >>> os.fsencode(filename)
 b'Sehensw\xc3\xbcrdigkeiten'
@@ -1720,7 +1740,9 @@ names.
   test discovery can find tests within packages, locating any test importable
   from the top-level directory.  The top-level directory can be specified with
   the `-t` option, a pattern for matching files with ``-p``, and a directory to
-  start discovery with ``-s``::
+  start discovery with ``-s``:
+
+  .. code-block:: shell-session
 
     $ python -m unittest discover -s my_proj_dir -p _test.py
 
@@ -1730,6 +1752,7 @@ names.
   :class:`unittest.case.TestCase` class can now be instantiated without
   arguments:
 
+  >>> from unittest import TestCase
   >>> TestCase().assertEqual(pow(2, 3), 8)
 
   (Contributed by Michael Foord.)
@@ -1895,7 +1918,9 @@ pydoc
 
 The :mod:`pydoc` module now provides a much-improved Web server interface, as
 well as a new command-line option ``-b`` to automatically open a browser window
-to display that server::
+to display that server:
+
+.. code-block:: shell-session
 
     $ pydoc3.2 -b
 
@@ -1998,7 +2023,9 @@ details of a given Python installation.
     '/Users/raymondhettinger/Library/Python/3.2/lib/python/site-packages'
 
 Conveniently, some of site's functionality is accessible directly from the
-command-line::
+command-line:
+
+.. code-block:: shell-session
 
     $ python -m site --user-base
     /Users/raymondhettinger/.local
@@ -2031,7 +2058,9 @@ seven named schemes used by :mod:`distutils`.  Those include *posix_prefix*,
 * :func:`~sysconfig.get_config_vars` returns a dictionary of platform specific
   variables.
 
-There is also a convenient command-line interface::
+There is also a convenient command-line interface:
+
+.. code-block:: doscon
 
   C:\Python32>python -m sysconfig
   Platform: "win32"
@@ -2185,7 +2214,7 @@ The :func:`~urllib.parse.urlparse` function now supports `IPv6
 <https://en.wikipedia.org/wiki/IPv6>`_ addresses as described in :rfc:`2732`:
 
     >>> import urllib.parse
-    >>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
+    >>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/') # doctest: +NORMALIZE_WHITESPACE
     ParseResult(scheme='http',
                 netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',
                 path='/foo/',
@@ -2219,7 +2248,7 @@ functions now accept ASCII-encoded byte strings as input, so long as they are
 not mixed with regular strings.  If ASCII-encoded byte strings are given as
 parameters, the return types will also be an ASCII-encoded byte strings:
 
-    >>> urllib.parse.urlparse(b'http://www.python.org:80/about/')
+    >>> urllib.parse.urlparse(b'http://www.python.org:80/about/') # doctest: +NORMALIZE_WHITESPACE
     ParseResultBytes(scheme=b'http', netloc=b'www.python.org:80',
                      path=b'/about/', params=b'', query=b'', fragment=b'')
 
@@ -2265,7 +2294,9 @@ turtledemo
 The demonstration code for the :mod:`turtle` module was moved from the *Demo*
 directory to main library.  It includes over a dozen sample scripts with
 lively displays.  Being on :attr:`sys.path`, it can now be run directly
-from the command-line::
+from the command-line:
+
+.. code-block:: shell-session
 
     $ python -m turtledemo
 
@@ -2666,7 +2697,7 @@ require changes to your code:
 
 * The :class:`xml.etree.ElementTree` class now raises an
   :exc:`xml.etree.ElementTree.ParseError` when a parse fails. Previously it
-  raised a :exc:`xml.parsers.expat.ExpatError`.
+  raised an :exc:`xml.parsers.expat.ExpatError`.
 
 * The new, longer :func:`str` value on floats may break doctests which rely on
   the old output format.
@@ -2701,4 +2732,3 @@ require changes to your code:
 
 * Due to the new :term:`GIL` implementation, :c:func:`PyEval_InitThreads()`
   cannot be called before :c:func:`Py_Initialize()` anymore.
-
index 2096b0b..0c9f2bb 100644 (file)
@@ -182,7 +182,7 @@ API changes
 * The maximum number of dimensions is officially limited to 64.
 
 * The representation of empty shape, strides and suboffsets is now
-  an empty tuple instead of None.
+  an empty tuple instead of ``None``.
 
 * Accessing a memoryview element with format 'B' (unsigned bytes)
   now returns an integer (in accordance with the struct module syntax).
@@ -871,7 +871,9 @@ signal. Call :func:`faulthandler.enable` to install fault handlers for the
 :envvar:`PYTHONFAULTHANDLER` environment variable or by using :option:`-X`
 ``faulthandler`` command line option.
 
-Example of a segmentation fault on Linux: ::
+Example of a segmentation fault on Linux:
+
+.. code-block:: shell-session
 
     $ python -q -X faulthandler
     >>> import ctypes
@@ -999,7 +1001,6 @@ byte of an invalid byte sequence. For example, ``b'\xff\n'.decode('gb2312',
 Incremental CJK codec encoders are no longer reset at each call to their
 encode() methods. For example::
 
-    $ ./python -q
     >>> import codecs
     >>> encoder = codecs.getincrementalencoder('hz')('strict')
     >>> b''.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
@@ -1741,7 +1742,7 @@ sched
 -----
 
 * :meth:`~sched.scheduler.run` now accepts a *blocking* parameter which when
-  set to False makes the method execute the scheduled events due to expire
+  set to false makes the method execute the scheduled events due to expire
   soonest (if any) and then return immediately.
   This is useful in case you want to use the :class:`~sched.scheduler` in
   non-blocking applications.  (Contributed by Giampaolo Rodolà in :issue:`13449`.)
@@ -1953,7 +1954,7 @@ ssl
   :attr:`~ssl.OP_NO_COMPRESSION` can be used to disable compression.
   (Contributed by Antoine Pitrou in :issue:`13634`.)
 
-* Support has been added for the Next Procotol Negotiation extension using
+* Support has been added for the Next Protocol Negotiation extension using
   the :meth:`ssl.SSLContext.set_npn_protocols` method.
   (Contributed by Colin Marc in :issue:`14204`.)
 
index 8fc2f6c..ab61d7a 100644 (file)
@@ -46,8 +46,7 @@
 
 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
-`changelog <https://docs.python.org/3.5/whatsnew/changelog.html>`_ for a full
-list of changes.
+:ref:`changelog <changelog>` for a full list of changes.
 
 .. seealso::
 
@@ -742,7 +741,9 @@ publicized, either at the time or since.
 
 With the new module, bundling your application is as simple as putting all
 the files, including a ``__main__.py`` file, into a directory ``myapp``
-and running::
+and running:
+
+.. code-block:: shell-session
 
     $ python -m zipapp myapp
     $ python myapp.pyz
@@ -802,11 +803,12 @@ Notable changes in the :mod:`asyncio` module since Python 3.4.0:
   :func:`~asyncio.ensure_future`.
   (Contributed by Yury Selivanov.)
 
-* New :meth:`loop.set_task_factory() <asyncio.BaseEventLoop.set_task_factory>`
-  and :meth:`loop.set_task_factory() <asyncio.BaseEventLoop.get_task_factory>`
-  methods to customize the task factory that
-  :meth:`loop.create_task() <asyncio.BaseEventLoop.create_task>` method uses.
-  (Contributed by Yury Selivanov.)
+* New :meth:`loop.set_task_factory()
+  <asyncio.AbstractEventLoop.set_task_factory>` and
+  :meth:`loop.get_task_factory() <asyncio.AbstractEventLoop.get_task_factory>`
+  methods to customize the task factory that :meth:`loop.create_task()
+  <asyncio.BaseEventLoop.create_task>` method uses.  (Contributed by Yury
+  Selivanov.)
 
 * New :meth:`Queue.join() <asyncio.Queue.join>` and
   :meth:`Queue.task_done() <asyncio.Queue.task_done>` queue methods.
@@ -1889,7 +1891,7 @@ to request exclusive creation.  (Contributed by Berker Peksag in :issue:`21717`.
 
 The :meth:`TarFile.extractall() <tarfile.TarFile.extractall>` and
 :meth:`TarFile.extract() <tarfile.TarFile.extract>` methods now take a keyword
-argument *numeric_only*.  If set to ``True``, the extracted files and
+argument *numeric_owner*.  If set to ``True``, the extracted files and
 directories will be owned by the numeric ``uid`` and ``gid`` from the tarfile.
 If set to ``False`` (the default, and the behavior in versions prior to 3.5),
 they will be owned by the named user and group in the tarfile.
@@ -2127,8 +2129,8 @@ Many operations on :class:`io.BytesIO` are now 50% to 100% faster.
 (Contributed by Serhiy Storchaka in :issue:`15381` and David Wilson in
 :issue:`22003`.)
 
-The :func:`marshal.dumps` function is now faster: 65-85% with versions 3
-and 4, 20-25% with versions 0 to 2 on typical data, and up to 5 times in
+The :func:`marshal.dumps` function is now faster: 65--85% with versions 3
+and 4, 20--25% with versions 0 to 2 on typical data, and up to 5 times in
 best cases.
 (Contributed by Serhiy Storchaka in :issue:`20416` and :issue:`23344`.)
 
index 07f9094..67a12f3 100644 (file)
@@ -1,3 +1,5 @@
+.. _changelog:
+
 +++++++++
 Changelog
 +++++++++
index 99fcea0..4307523 100644 (file)
@@ -132,7 +132,7 @@ arglist: argument (',' argument)*  [',']
 # to our LL(1) parser. Even though 'test' includes '*expr' in star_expr,
 # we explicitly match '*' here, too, to give it proper precedence.
 # Illegal combinations and orderings are blocked in ast.c:
-# multiple (test comp_for) arguements are blocked; keyword unpackings
+# multiple (test comp_for) arguments are blocked; keyword unpackings
 # that precede iterable unpackings are blocked; etc.
 argument: ( test [comp_for] |
             test '=' test |
index 4ff79f2..7dbbb74 100644 (file)
@@ -266,18 +266,18 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
      PyAPI_FUNC(PyObject *) PyObject_Call(PyObject *callable_object,
                                           PyObject *args, PyObject *kw);
 
-#ifndef Py_LIMITED_API
-     PyAPI_FUNC(PyObject *) _Py_CheckFunctionResult(PyObject *func,
-                                                    PyObject *result,
-                                                    const char *where);
-#endif
-
        /*
      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.
        */
 
+#ifndef Py_LIMITED_API
+     PyAPI_FUNC(PyObject *) _Py_CheckFunctionResult(PyObject *func,
+                                                    PyObject *result,
+                                                    const char *where);
+#endif
+
      PyAPI_FUNC(PyObject *) PyObject_CallObject(PyObject *callable_object,
                                                 PyObject *args);
 
@@ -458,7 +458,7 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
     /* old buffer API
        FIXME:  usage of these should all be replaced in Python itself
        but for backwards compatibility we will implement them.
-       Their usage without a corresponding "unlock" mechansim
+       Their usage without a corresponding "unlock" mechanism
        may create issues (but they would already be there). */
 
      PyAPI_FUNC(int) PyObject_AsCharBuffer(PyObject *obj,
@@ -1216,23 +1216,23 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
      PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o);
 
        /*
-     On success, return a list, a tuple or a dictionary view in case of a dict,
-     of the keys in object o. On failure, return NULL.
+     On success, return a list or tuple of the keys in object o.
+     On failure, return NULL.
        */
 
      PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o);
 
        /*
-     On success, return a list, a tuple or a dictionary view in case of a dict,
-     of the values in object o. On failure, return NULL.
+     On success, return a list or tuple of the values in object o.
+     On failure, return NULL.
        */
 
      PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o);
 
        /*
-     On success, return a list, a tuple or a dictionary view in case of a dict,
-     of the items in object o, where each item is a tuple containing a key-value
-     pair. On failure, return NULL.
+     On success, return a list or tuple of the items in object o,
+     where each item is a tuple containing a key-value pair.
+     On failure, return NULL.
 
        */
 
index ba90aaf..e0e1c26 100644 (file)
@@ -75,6 +75,8 @@ PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key);
 #ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PyDict_DelItem_KnownHash(PyObject *mp, PyObject *key,
                                           Py_hash_t hash);
+PyAPI_FUNC(int) _PyDict_DelItemIf(PyObject *mp, PyObject *key,
+                                  int (*predicate)(PyObject *value));
 #endif
 PyAPI_FUNC(void) PyDict_Clear(PyObject *mp);
 PyAPI_FUNC(int) PyDict_Next(
index 1ff32a8..61e708a 100644 (file)
@@ -41,6 +41,7 @@ PyAPI_FUNC(PyObject *) PyGen_New(struct _frame *);
 PyAPI_FUNC(PyObject *) PyGen_NewWithQualName(struct _frame *,
     PyObject *name, PyObject *qualname);
 PyAPI_FUNC(int) PyGen_NeedsFinalizing(PyGenObject *);
+PyAPI_FUNC(int) _PyGen_SetStopIterationValue(PyObject *);
 PyAPI_FUNC(int) _PyGen_FetchStopIterationValue(PyObject **);
 PyObject *_PyGen_Send(PyGenObject *, PyObject *);
 PyObject *_PyGen_yf(PyGenObject *);
index aed59ce..2a2eecf 100644 (file)
@@ -159,7 +159,7 @@ PyAPI_FUNC(PyObject *) _PyLong_FromByteArray(
      example, if is_signed is 0 and there are more digits in the v than
      fit in n; or if is_signed is 1, v < 0, and n is just 1 bit shy of
      being large enough to hold a sign bit.  OverflowError is set in this
-     case, but bytes holds the least-signficant n bytes of the true value.
+     case, but bytes holds the least-significant n bytes of the true value.
 */
 PyAPI_FUNC(int) _PyLong_AsByteArray(PyLongObject* v,
     unsigned char* bytes, size_t n,
index 229d7fa..b44fb9b 100644 (file)
@@ -77,7 +77,7 @@ typedef struct PyModuleDef{
   traverseproc m_traverse;
   inquiry m_clear;
   freefunc m_free;
-}PyModuleDef;
+} PyModuleDef;
 
 #ifdef __cplusplus
 }
index 60851c1..77e7249 100644 (file)
 /*--start constants--*/
 #define PY_MAJOR_VERSION       3
 #define PY_MINOR_VERSION       5
-#define PY_MICRO_VERSION       2
+#define PY_MICRO_VERSION       3
 #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.5.3"
 /*--end constants--*/
 
 /* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2.
index e957119..f9a15e6 100644 (file)
@@ -45,10 +45,10 @@ extern "C" {
  *       Define macros for handling SIGFPE.
  *       Lee Busby, LLNL, November, 1996
  *       busby1@llnl.gov
- * 
+ *
  *********************************************
  * Overview of the system for handling SIGFPE:
- * 
+ *
  * This file (Include/pyfpe.h) defines a couple of "wrapper" macros for
  * insertion into your Python C code of choice. Their proper use is
  * discussed below. The file Python/pyfpe.c defines a pair of global
@@ -59,33 +59,33 @@ extern "C" {
  * named fpectl. This module is standard in every respect. It can be loaded
  * either statically or dynamically as you choose, and like any other
  * Python module, has no effect until you import it.
- * 
+ *
  * In the general case, there are three steps toward handling SIGFPE in any
  * Python code:
- * 
+ *
  * 1) Add the *_PROTECT macros to your C code as required to protect
  *    dangerous floating point sections.
- * 
+ *
  * 2) Turn on the inclusion of the code by adding the ``--with-fpectl''
  *    flag at the time you run configure.  If the fpectl or other modules
  *    which use the *_PROTECT macros are to be dynamically loaded, be
  *    sure they are compiled with WANT_SIGFPE_HANDLER defined.
- * 
+ *
  * 3) When python is built and running, import fpectl, and execute
  *    fpectl.turnon_sigfpe(). This sets up the signal handler and enables
  *    generation of SIGFPE whenever an exception occurs. From this point
  *    on, any properly trapped SIGFPE should result in the Python
  *    FloatingPointError exception.
- * 
+ *
  * Step 1 has been done already for the Python kernel code, and should be
  * done soon for the NumPy array package.  Step 2 is usually done once at
  * python install time. Python's behavior with respect to SIGFPE is not
  * changed unless you also do step 3. Thus you can control this new
  * facility at compile time, or run time, or both.
- * 
- ******************************** 
+ *
+ ********************************
  * Using the macros in your code:
- * 
+ *
  * static PyObject *foobar(PyObject *self,PyObject *args)
  * {
  *     ....
@@ -94,17 +94,17 @@ extern "C" {
  *     PyFPE_END_PROTECT(result)
  *     ....
  * }
- * 
+ *
  * If a floating point error occurs in dangerous_op, foobar returns 0 (NULL),
  * after setting the associated value of the FloatingPointError exception to
  * "Error in foobar". ``Dangerous_op'' can be a single operation, or a block
  * of code, function calls, or any combination, so long as no alternate
  * return is possible before the PyFPE_END_PROTECT macro is reached.
- * 
+ *
  * The macros can only be used in a function context where an error return
  * can be recognized as signaling a Python exception. (Generally, most
  * functions that return a PyObject * will qualify.)
- * 
+ *
  * Guido's original design suggestion for PyFPE_START_PROTECT and
  * PyFPE_END_PROTECT had them open and close a local block, with a locally
  * defined jmp_buf and jmp_buf pointer. This would allow recursive nesting
@@ -112,17 +112,17 @@ extern "C" {
  * variables need to be declared with the "volatile" type qualifier to keep
  * setjmp from corrupting their values. Some current implementations seem
  * to be more restrictive. For example, the HPUX man page for setjmp says
- * 
+ *
  *   Upon the return from a setjmp() call caused by a longjmp(), the
  *   values of any non-static local variables belonging to the routine
  *   from which setjmp() was called are undefined. Code which depends on
  *   such values is not guaranteed to be portable.
- * 
+ *
  * I therefore decided on a more limited form of nesting, using a counter
  * variable (PyFPE_counter) to keep track of any recursion.  If an exception
  * occurs in an ``inner'' pair of macros, the return will apparently
  * come from the outermost level.
- * 
+ *
  */
 
 #ifdef WANT_SIGFPE_HANDLER
@@ -146,14 +146,14 @@ if (!PyFPE_counter++ && setjmp(PyFPE_jbuf)) { \
  * this statement so that it gets executed *before* the unsafe expression
  * which we're trying to protect.  That pretty well messes things up,
  * of course.
- * 
+ *
  * If the expression(s) you're trying to protect don't happen to return a
  * value, you will need to manufacture a dummy result just to preserve the
  * correct ordering of statements.  Note that the macro passes the address
  * of its argument (so you need to give it something which is addressable).
  * If your expression returns multiple results, pass the last such result
  * to PyFPE_END_PROTECT.
- * 
+ *
  * Note that PyFPE_dummy returns a double, which is cast to int.
  * This seeming insanity is to tickle the Floating Point Unit (FPU).
  * If an exception has occurred in a preceding floating point operation,
index 0c28f5c..9dde11b 100644 (file)
@@ -63,7 +63,7 @@
 #    if defined(__LP64__)
      /* MacOSX 10.4 (the first release to support 64-bit code
       * at all) only supports 64-bit in the UNIX layer.
-      * Therefore surpress the toolbox-glue in 64-bit mode.
+      * Therefore suppress the toolbox-glue in 64-bit mode.
       */
 
     /* In 64-bit mode setpgrp always has no arguments, in 32-bit
@@ -91,7 +91,7 @@
      *
      * Specifically: OSX 10.4 has limited supported for '%zd', while
      * 10.5 has full support for '%zd'. A binary built on 10.5 won't
-     * work properly on 10.4 unless we surpress the definition
+     * work properly on 10.4 unless we suppress the definition
      * of PY_FORMAT_SIZE_T
      */
 #undef  PY_FORMAT_SIZE_T
index 1ea9ac1..1c8d718 100644 (file)
@@ -37,7 +37,7 @@ extern double pow(double, double);
 #endif /* __STDC__ */
 #endif /* _MSC_VER */
 
-/* High precision defintion of pi and e (Euler)
+/* High precision definition of pi and e (Euler)
  * The values are taken from libc6's math.h.
  */
 #ifndef Py_MATH_PIl
index 66e00d4..e7e5178 100644 (file)
@@ -677,7 +677,9 @@ extern pid_t forkpty(int *, char *, struct termios *, struct winsize *);
 
 #ifdef __FreeBSD__
 #include <osreldate.h>
-#if __FreeBSD_version > 500039
+#if (__FreeBSD_version >= 500040 && __FreeBSD_version < 602113) || \
+    (__FreeBSD_version >= 700000 && __FreeBSD_version < 700054) || \
+    (__FreeBSD_version >= 800000 && __FreeBSD_version < 800001)
 # define _PY_PORT_CTYPE_UTF8_ISSUE
 #endif
 #endif
@@ -688,6 +690,12 @@ extern pid_t forkpty(int *, char *, struct termios *, struct winsize *);
 #endif
 
 #ifdef _PY_PORT_CTYPE_UTF8_ISSUE
+#ifndef __cplusplus
+   /* The workaround below is unsafe in C++ because
+    * the <locale> defines these symbols as real functions,
+    * with a slightly different signature.
+    * See issue #10910
+    */
 #include <ctype.h>
 #include <wctype.h>
 #undef isalnum
@@ -705,6 +713,7 @@ extern pid_t forkpty(int *, char *, struct termios *, struct winsize *);
 #undef toupper
 #define toupper(c) towupper(btowc(c))
 #endif
+#endif
 
 
 /* Declarations for symbol visibility.
@@ -877,7 +886,7 @@ extern pid_t forkpty(int *, char *, struct termios *, struct winsize *);
 #define PY_LITTLE_ENDIAN 1
 #endif
 
-#ifdef Py_BUILD_CORE 
+#ifdef Py_BUILD_CORE
 /*
  * Macros to protect CRT calls against instant termination when passed an
  * invalid parameter (issue23524).
index 533dd75..9308a6a 100644 (file)
@@ -176,7 +176,7 @@ typedef unsigned char Py_UCS1;
 
 #define Py_UNICODE_FILL(target, value, length) \
     do {Py_ssize_t i_; Py_UNICODE *t_ = (target); Py_UNICODE v_ = (value);\
-    for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\
+        for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\
     } while (0)
 
 /* macros to work with surrogates */
@@ -749,7 +749,7 @@ PyAPI_FUNC(Py_UCS4) _PyUnicode_FindMaxChar (
 #endif
 
 /* 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 ValueError if
+   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.
 
    buflen is the length of the buffer in (Py_UCS4) characters. */
@@ -2000,27 +2000,53 @@ 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.
+   Any error occurs inside will be cleared before return. */
+
+PyAPI_FUNC(int) _PyUnicode_EqualToASCIIId(
+    PyObject *left,             /* Left string */
+    _Py_Identifier *right       /* Right identifier */
+    );
 #endif
 
+/* Compare a Unicode object with C string and return -1, 0, 1 for less than,
+   equal, and greater than, respectively.  It is best to pass only
+   ASCII-encoded strings, but the function interprets the input string as
+   ISO-8859-1 if it contains non-ASCII characters.
+   This function does not raise exceptions. */
+
 PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString(
     PyObject *left,
     const char *right           /* ASCII-encoded string */
     );
 
+#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.
+   Any error occurs inside will be cleared before return. */
+
+PyAPI_FUNC(int) _PyUnicode_EqualToASCIIString(
+    PyObject *left,
+    const char *right           /* ASCII-encoded string */
+    );
+#endif
+
 /* Rich compare two strings and return one of the following:
 
    - NULL in case an exception was raised
-   - Py_True or Py_False for successfully comparisons
+   - Py_True or Py_False for successful comparisons
    - Py_NotImplemented in case the type combination is unknown
 
-   Note that Py_EQ and Py_NE comparisons can cause a UnicodeWarning in
-   case the conversion of the arguments to Unicode fails with a
-   UnicodeDecodeError.
-
    Possible values for op:
 
      Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE
diff --git a/LICENSE b/LICENSE
index 84a3337..f5d0b39 100644 (file)
--- a/LICENSE
+++ b/LICENSE
@@ -74,7 +74,7 @@ analyze, test, perform and/or display publicly, prepare derivative works,
 distribute, and otherwise use Python alone or in any derivative version,
 provided, however, that PSF's License Agreement and PSF's notice of copyright,
 i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
-2011, 2012, 2013, 2014, 2015, 2016 Python Software Foundation; All Rights
+2011, 2012, 2013, 2014, 2015, 2016, 2017 Python Software Foundation; All Rights
 Reserved" are retained in Python alone or in any derivative version prepared by
 Licensee.
 
index fc9c9f1..8bebd69 100644 (file)
@@ -29,8 +29,8 @@ __name__ = "collections.abc"
 # so that they will pass tests like:
 #       it = iter(somebytearray)
 #       assert isinstance(it, Iterable)
-# Note:  in other implementations, these types many not be distinct
-# and they make have their own implementation specific types that
+# Note:  in other implementations, these types might not be distinct
+# and they may have their own implementation specific types that
 # are not included on this list.
 bytes_iterator = type(iter(b''))
 bytearray_iterator = type(iter(bytearray()))
@@ -41,6 +41,7 @@ dict_itemiterator = type(iter({}.items()))
 list_iterator = type(iter([]))
 list_reverseiterator = type(iter(reversed([])))
 range_iterator = type(iter(range(0)))
+longrange_iterator = type(iter(range(1 << 1000)))
 set_iterator = type(iter(set()))
 str_iterator = type(iter(""))
 tuple_iterator = type(iter(()))
@@ -234,6 +235,7 @@ Iterator.register(dict_itemiterator)
 Iterator.register(list_iterator)
 Iterator.register(list_reverseiterator)
 Iterator.register(range_iterator)
+Iterator.register(longrange_iterator)
 Iterator.register(set_iterator)
 Iterator.register(str_iterator)
 Iterator.register(tuple_iterator)
index c719424..a5ea340 100644 (file)
@@ -1068,12 +1068,11 @@ class Decimal(object):
         return sign + intpart + fracpart + exp
 
     def to_eng_string(self, context=None):
-        """Convert to engineering-type string.
+        """Convert to a string, using engineering notation if an exponent is needed.
 
-        Engineering notation has an exponent which is a multiple of 3, so there
-        are up to 3 digits left of the decimal place.
-
-        Same rules for when in exponential and when as a value as in __str__.
+        Engineering notation has an exponent which is a multiple of 3.  This
+        can leave up to 3 digits to the left of the decimal place and may
+        require the addition of either one or two trailing zeros.
         """
         return self.__str__(eng=True, context=context)
 
@@ -4107,7 +4106,7 @@ class Context(object):
         >>> context.create_decimal_from_float(3.1415926535897932)
         Traceback (most recent call last):
             ...
-        decimal.Inexact
+        decimal.Inexact: None
 
         """
         d = Decimal.from_float(f)       # An exact conversion
@@ -5502,9 +5501,29 @@ class Context(object):
             return r
 
     def to_eng_string(self, a):
-        """Converts a number to a string, using scientific notation.
+        """Convert to a string, using engineering notation if an exponent is needed.
+
+        Engineering notation has an exponent which is a multiple of 3.  This
+        can leave up to 3 digits to the left of the decimal place and may
+        require the addition of either one or two trailing zeros.
 
         The operation is not affected by the context.
+
+        >>> ExtendedContext.to_eng_string(Decimal('123E+1'))
+        '1.23E+3'
+        >>> ExtendedContext.to_eng_string(Decimal('123E+3'))
+        '123E+3'
+        >>> ExtendedContext.to_eng_string(Decimal('123E-10'))
+        '12.3E-9'
+        >>> ExtendedContext.to_eng_string(Decimal('-123E-12'))
+        '-123E-12'
+        >>> ExtendedContext.to_eng_string(Decimal('7E-7'))
+        '700E-9'
+        >>> ExtendedContext.to_eng_string(Decimal('7E+1'))
+        '70'
+        >>> ExtendedContext.to_eng_string(Decimal('0E+1'))
+        '0.00E+3'
+
         """
         a = _convert_other(a, raiseit=True)
         return a.to_eng_string(context=self)
index 0d98b74..f2fe447 100644 (file)
@@ -276,7 +276,7 @@ class OpenWrapper:
 try:
     UnsupportedOperation = io.UnsupportedOperation
 except AttributeError:
-    class UnsupportedOperation(ValueError, OSError):
+    class UnsupportedOperation(OSError, ValueError):
         pass
 
 
index 7670187..9b14368 100644 (file)
@@ -2,7 +2,7 @@
 import webbrowser
 import hashlib
 
-webbrowser.open("http://xkcd.com/353/")
+webbrowser.open("https://xkcd.com/353/")
 
 def geohash(latitude, longitude, datedow):
     '''Compute geohash() using the Munroe algorithm.
index 172a463..50153f8 100644 (file)
@@ -13,7 +13,6 @@ conscious design decision, leaving the door open for keyword arguments
 to modify the meaning of the API call itself.
 """
 
-
 import collections
 import concurrent.futures
 import heapq
@@ -28,6 +27,7 @@ import time
 import traceback
 import sys
 import warnings
+import weakref
 
 from . import compat
 from . import coroutines
@@ -41,9 +41,6 @@ from .log import logger
 __all__ = ['BaseEventLoop']
 
 
-# Argument for default thread pool executor creation.
-_MAX_WORKERS = 5
-
 # Minimum number of _scheduled timer handles before cleanup of
 # cancelled handles is performed.
 _MIN_SCHEDULED_TIMER_HANDLES = 100
@@ -76,12 +73,29 @@ def _format_pipe(fd):
         return repr(fd)
 
 
-# Linux's sock.type is a bitmask that can include extra info about socket.
-_SOCKET_TYPE_MASK = 0
-if hasattr(socket, 'SOCK_NONBLOCK'):
-    _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
-if hasattr(socket, 'SOCK_CLOEXEC'):
-    _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
+def _set_reuseport(sock):
+    if not hasattr(socket, 'SO_REUSEPORT'):
+        raise ValueError('reuse_port not supported by socket module')
+    else:
+        try:
+            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
+        except OSError:
+            raise ValueError('reuse_port not supported by socket module, '
+                             'SO_REUSEPORT defined but not implemented.')
+
+
+def _is_stream_socket(sock):
+    # Linux's socket.type is a bitmask that can include extra info
+    # about socket, therefore we can't do simple
+    # `sock_type == socket.SOCK_STREAM`.
+    return (sock.type & socket.SOCK_STREAM) == socket.SOCK_STREAM
+
+
+def _is_dgram_socket(sock):
+    # Linux's socket.type is a bitmask that can include extra info
+    # about socket, therefore we can't do simple
+    # `sock_type == socket.SOCK_DGRAM`.
+    return (sock.type & socket.SOCK_DGRAM) == socket.SOCK_DGRAM
 
 
 def _ipaddr_info(host, port, family, type, proto):
@@ -94,8 +108,12 @@ def _ipaddr_info(host, port, family, type, proto):
             host is None:
         return None
 
-    type &= ~_SOCKET_TYPE_MASK
     if type == socket.SOCK_STREAM:
+        # Linux only:
+        #    getaddrinfo() can raise when socket.type is a bit mask.
+        #    So if socket.type is a bit mask of SOCK_STREAM, and say
+        #    SOCK_NONBLOCK, we simply return None, which will trigger
+        #    a call to getaddrinfo() letting it process this request.
         proto = socket.IPPROTO_TCP
     elif type == socket.SOCK_DGRAM:
         proto = socket.IPPROTO_UDP
@@ -104,27 +122,21 @@ def _ipaddr_info(host, port, family, type, proto):
 
     if port is None:
         port = 0
-    elif isinstance(port, bytes):
-        if port == b'':
-            port = 0
-        else:
-            try:
-                port = int(port)
-            except ValueError:
-                # Might be a service name like b"http".
-                port = socket.getservbyname(port.decode('ascii'))
-    elif isinstance(port, str):
-        if port == '':
-            port = 0
-        else:
-            try:
-                port = int(port)
-            except ValueError:
-                # Might be a service name like "http".
-                port = socket.getservbyname(port)
+    elif isinstance(port, bytes) and port == b'':
+        port = 0
+    elif isinstance(port, str) and port == '':
+        port = 0
+    else:
+        # If port's a service name like "http", don't skip getaddrinfo.
+        try:
+            port = int(port)
+        except (TypeError, ValueError):
+            return None
 
     if family == socket.AF_UNSPEC:
-        afs = [socket.AF_INET, socket.AF_INET6]
+        afs = [socket.AF_INET]
+        if hasattr(socket, 'AF_INET6'):
+            afs.append(socket.AF_INET6)
     else:
         afs = [family]
 
@@ -242,6 +254,17 @@ class BaseEventLoop(events.AbstractEventLoop):
         self._task_factory = None
         self._coroutine_wrapper_set = False
 
+        if hasattr(sys, 'get_asyncgen_hooks'):
+            # Python >= 3.6
+            # A weak set of all asynchronous generators that are
+            # being iterated by the loop.
+            self._asyncgens = weakref.WeakSet()
+        else:
+            self._asyncgens = None
+
+        # Set to True when `loop.shutdown_asyncgens` is called.
+        self._asyncgens_shutdown_called = False
+
     def __repr__(self):
         return ('<%s running=%s closed=%s debug=%s>'
                 % (self.__class__.__name__, self.is_running(),
@@ -333,14 +356,67 @@ class BaseEventLoop(events.AbstractEventLoop):
         if self._closed:
             raise RuntimeError('Event loop is closed')
 
+    def _asyncgen_finalizer_hook(self, agen):
+        self._asyncgens.discard(agen)
+        if not self.is_closed():
+            self.create_task(agen.aclose())
+            # Wake up the loop if the finalizer was called from
+            # a different thread.
+            self._write_to_self()
+
+    def _asyncgen_firstiter_hook(self, agen):
+        if self._asyncgens_shutdown_called:
+            warnings.warn(
+                "asynchronous generator {!r} was scheduled after "
+                "loop.shutdown_asyncgens() call".format(agen),
+                ResourceWarning, source=self)
+
+        self._asyncgens.add(agen)
+
+    @coroutine
+    def shutdown_asyncgens(self):
+        """Shutdown all active asynchronous generators."""
+        self._asyncgens_shutdown_called = True
+
+        if self._asyncgens is None or not len(self._asyncgens):
+            # If Python version is <3.6 or we don't have any asynchronous
+            # generators alive.
+            return
+
+        closing_agens = list(self._asyncgens)
+        self._asyncgens.clear()
+
+        shutdown_coro = tasks.gather(
+            *[ag.aclose() for ag in closing_agens],
+            return_exceptions=True,
+            loop=self)
+
+        results = yield from shutdown_coro
+        for result, agen in zip(results, closing_agens):
+            if isinstance(result, Exception):
+                self.call_exception_handler({
+                    'message': 'an error occurred during closing of '
+                               'asynchronous generator {!r}'.format(agen),
+                    'exception': result,
+                    'asyncgen': agen
+                })
+
     def run_forever(self):
         """Run until stop() is called."""
         self._check_closed()
         if self.is_running():
-            raise RuntimeError('Event loop is running.')
+            raise RuntimeError('This event loop is already running')
+        if events._get_running_loop() is not None:
+            raise RuntimeError(
+                'Cannot run the event loop while another loop is running')
         self._set_coroutine_wrapper(self._debug)
         self._thread_id = threading.get_ident()
+        if self._asyncgens is not None:
+            old_agen_hooks = sys.get_asyncgen_hooks()
+            sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
+                                   finalizer=self._asyncgen_finalizer_hook)
         try:
+            events._set_running_loop(self)
             while True:
                 self._run_once()
                 if self._stopping:
@@ -348,7 +424,10 @@ class BaseEventLoop(events.AbstractEventLoop):
         finally:
             self._stopping = False
             self._thread_id = None
+            events._set_running_loop(None)
             self._set_coroutine_wrapper(False)
+            if self._asyncgens is not None:
+                sys.set_asyncgen_hooks(*old_agen_hooks)
 
     def run_until_complete(self, future):
         """Run until the Future is done.
@@ -363,7 +442,7 @@ class BaseEventLoop(events.AbstractEventLoop):
         """
         self._check_closed()
 
-        new_task = not isinstance(future, futures.Future)
+        new_task = not futures.isfuture(future)
         future = tasks.ensure_future(future, loop=self)
         if new_task:
             # An exception is raised if the future didn't complete, so there
@@ -469,12 +548,10 @@ class BaseEventLoop(events.AbstractEventLoop):
 
         Absolute time corresponds to the event loop's time() method.
         """
-        if (coroutines.iscoroutine(callback)
-        or coroutines.iscoroutinefunction(callback)):
-            raise TypeError("coroutines cannot be used with call_at()")
         self._check_closed()
         if self._debug:
             self._check_thread()
+            self._check_callback(callback, 'call_at')
         timer = events.TimerHandle(when, callback, args, self)
         if timer._source_traceback:
             del timer._source_traceback[-1]
@@ -492,18 +569,27 @@ class BaseEventLoop(events.AbstractEventLoop):
         Any positional arguments after the callback will be passed to
         the callback when it is called.
         """
+        self._check_closed()
         if self._debug:
             self._check_thread()
+            self._check_callback(callback, 'call_soon')
         handle = self._call_soon(callback, args)
         if handle._source_traceback:
             del handle._source_traceback[-1]
         return handle
 
+    def _check_callback(self, callback, method):
+        if (coroutines.iscoroutine(callback) or
+                coroutines.iscoroutinefunction(callback)):
+            raise TypeError(
+                "coroutines cannot be used with {}()".format(method))
+        if not callable(callback):
+            raise TypeError(
+                'a callable object was expected by {}(), got {!r}'.format(
+                    method, callback))
+
+
     def _call_soon(self, callback, args):
-        if (coroutines.iscoroutine(callback)
-        or coroutines.iscoroutinefunction(callback)):
-            raise TypeError("coroutines cannot be used with call_soon()")
-        self._check_closed()
         handle = events.Handle(callback, args, self)
         if handle._source_traceback:
             del handle._source_traceback[-1]
@@ -529,6 +615,9 @@ class BaseEventLoop(events.AbstractEventLoop):
 
     def call_soon_threadsafe(self, callback, *args):
         """Like call_soon(), but thread-safe."""
+        self._check_closed()
+        if self._debug:
+            self._check_callback(callback, 'call_soon_threadsafe')
         handle = self._call_soon(callback, args)
         if handle._source_traceback:
             del handle._source_traceback[-1]
@@ -536,22 +625,13 @@ class BaseEventLoop(events.AbstractEventLoop):
         return handle
 
     def run_in_executor(self, executor, func, *args):
-        if (coroutines.iscoroutine(func)
-        or coroutines.iscoroutinefunction(func)):
-            raise TypeError("coroutines cannot be used with run_in_executor()")
         self._check_closed()
-        if isinstance(func, events.Handle):
-            assert not args
-            assert not isinstance(func, events.TimerHandle)
-            if func._cancelled:
-                f = self.create_future()
-                f.set_result(None)
-                return f
-            func, args = func._callback, func._args
+        if self._debug:
+            self._check_callback(func, 'run_in_executor')
         if executor is None:
             executor = self._default_executor
             if executor is None:
-                executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
+                executor = concurrent.futures.ThreadPoolExecutor()
                 self._default_executor = executor
         return futures.wrap_future(executor.submit(func, *args), loop=self)
 
@@ -703,11 +783,19 @@ class BaseEventLoop(events.AbstractEventLoop):
                     raise OSError('Multiple exceptions: {}'.format(
                         ', '.join(str(exc) for exc in exceptions)))
 
-        elif sock is None:
-            raise ValueError(
-                'host and port was not specified and no sock specified')
-
-        sock.setblocking(False)
+        else:
+            if sock is None:
+                raise ValueError(
+                    'host and port was not specified and no sock specified')
+            if not _is_stream_socket(sock):
+                # We allow AF_INET, AF_INET6, AF_UNIX as long as they
+                # are SOCK_STREAM.
+                # We support passing AF_UNIX sockets even though we have
+                # a dedicated API for that: create_unix_connection.
+                # Disallowing AF_UNIX in this method, breaks backwards
+                # compatibility.
+                raise ValueError(
+                    'A Stream Socket was expected, got {!r}'.format(sock))
 
         transport, protocol = yield from self._create_connection_transport(
             sock, protocol_factory, ssl, server_hostname)
@@ -721,14 +809,17 @@ class BaseEventLoop(events.AbstractEventLoop):
 
     @coroutine
     def _create_connection_transport(self, sock, protocol_factory, ssl,
-                                     server_hostname):
+                                     server_hostname, server_side=False):
+
+        sock.setblocking(False)
+
         protocol = protocol_factory()
         waiter = self.create_future()
         if ssl:
             sslcontext = None if isinstance(ssl, bool) else ssl
             transport = self._make_ssl_transport(
                 sock, protocol, sslcontext, waiter,
-                server_side=False, server_hostname=server_hostname)
+                server_side=server_side, server_hostname=server_hostname)
         else:
             transport = self._make_socket_transport(sock, protocol, waiter)
 
@@ -748,6 +839,9 @@ class BaseEventLoop(events.AbstractEventLoop):
                                  allow_broadcast=None, sock=None):
         """Create datagram connection."""
         if sock is not None:
+            if not _is_dgram_socket(sock):
+                raise ValueError(
+                    'A UDP Socket was expected, got {!r}'.format(sock))
             if (local_addr or remote_addr or
                     family or proto or flags or
                     reuse_address or reuse_port or allow_broadcast):
@@ -813,12 +907,7 @@ class BaseEventLoop(events.AbstractEventLoop):
                         sock.setsockopt(
                             socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                     if reuse_port:
-                        if not hasattr(socket, 'SO_REUSEPORT'):
-                            raise ValueError(
-                                'reuse_port not supported by socket module')
-                        else:
-                            sock.setsockopt(
-                                socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
+                        _set_reuseport(sock)
                     if allow_broadcast:
                         sock.setsockopt(
                             socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
@@ -941,12 +1030,7 @@ class BaseEventLoop(events.AbstractEventLoop):
                         sock.setsockopt(
                             socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
                     if reuse_port:
-                        if not hasattr(socket, 'SO_REUSEPORT'):
-                            raise ValueError(
-                                'reuse_port not supported by socket module')
-                        else:
-                            sock.setsockopt(
-                                socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
+                        _set_reuseport(sock)
                     # Disable IPv4/IPv6 dual stack support (enabled by
                     # default on Linux) which makes a single socket
                     # listen on both address families.
@@ -968,18 +1052,44 @@ class BaseEventLoop(events.AbstractEventLoop):
         else:
             if sock is None:
                 raise ValueError('Neither host/port nor sock were specified')
+            if not _is_stream_socket(sock):
+                raise ValueError(
+                    'A Stream Socket was expected, got {!r}'.format(sock))
             sockets = [sock]
 
         server = Server(self, sockets)
         for sock in sockets:
             sock.listen(backlog)
             sock.setblocking(False)
-            self._start_serving(protocol_factory, sock, ssl, server)
+            self._start_serving(protocol_factory, sock, ssl, server, backlog)
         if self._debug:
             logger.info("%r is serving", server)
         return server
 
     @coroutine
+    def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
+        """Handle an accepted connection.
+
+        This is used by servers that accept connections outside of
+        asyncio but that use asyncio to handle connections.
+
+        This method is a coroutine.  When completed, the coroutine
+        returns a (transport, protocol) pair.
+        """
+        if not _is_stream_socket(sock):
+            raise ValueError(
+                'A Stream Socket was expected, got {!r}'.format(sock))
+
+        transport, protocol = yield from self._create_connection_transport(
+            sock, protocol_factory, ssl, '', server_side=True)
+        if self._debug:
+            # Get the socket from the transport because SSL transport closes
+            # the old socket and creates a new SSL socket
+            sock = transport.get_extra_info('socket')
+            logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
+        return transport, protocol
+
+    @coroutine
     def connect_read_pipe(self, protocol_factory, pipe):
         protocol = protocol_factory()
         waiter = self.create_future()
@@ -1048,7 +1158,7 @@ class BaseEventLoop(events.AbstractEventLoop):
         transport = yield from self._make_subprocess_transport(
             protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
         if self._debug:
-            logger.info('%s: %r' % (debug_log, transport))
+            logger.info('%s: %r', debug_log, transport)
         return transport, protocol
 
     @coroutine
@@ -1078,7 +1188,7 @@ class BaseEventLoop(events.AbstractEventLoop):
             protocol, popen_args, False, stdin, stdout, stderr,
             bufsize, **kwargs)
         if self._debug:
-            logger.info('%s: %r' % (debug_log, transport))
+            logger.info('%s: %r', debug_log, transport)
         return transport, protocol
 
     def get_exception_handler(self):
@@ -1158,7 +1268,9 @@ class BaseEventLoop(events.AbstractEventLoop):
         - 'handle' (optional): Handle instance;
         - 'protocol' (optional): Protocol instance;
         - 'transport' (optional): Transport instance;
-        - 'socket' (optional): Socket instance.
+        - 'socket' (optional): Socket instance;
+        - 'asyncgen' (optional): Asynchronous generator that caused
+                                 the exception.
 
         New keys maybe introduced in the future.
 
index 8fc253c..23742a1 100644 (file)
@@ -3,7 +3,6 @@ import subprocess
 import warnings
 
 from . import compat
-from . import futures
 from . import protocols
 from . import transports
 from .coroutines import coroutine
@@ -87,6 +86,12 @@ class BaseSubprocessTransport(transports.SubprocessTransport):
     def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
         raise NotImplementedError
 
+    def set_protocol(self, protocol):
+        self._protocol = protocol
+
+    def get_protocol(self):
+        return self._protocol
+
     def is_closing(self):
         return self._closed
 
index 71bc6fb..5bdeceb 100644 (file)
@@ -33,12 +33,16 @@ _DEBUG = (not sys.flags.ignore_environment and
 
 try:
     _types_coroutine = types.coroutine
+    _types_CoroutineType = types.CoroutineType
 except AttributeError:
+    # Python 3.4
     _types_coroutine = None
+    _types_CoroutineType = None
 
 try:
     _inspect_iscoroutinefunction = inspect.iscoroutinefunction
 except AttributeError:
+    # Python 3.4
     _inspect_iscoroutinefunction = lambda func: False
 
 try:
@@ -120,8 +124,8 @@ class CoroWrapper:
         def send(self, value):
             return self.gen.send(value)
 
-    def throw(self, exc):
-        return self.gen.throw(exc)
+    def throw(self, type, value=None, traceback=None):
+        return self.gen.throw(type, value, traceback)
 
     def close(self):
         return self.gen.close()
@@ -204,8 +208,8 @@ def coroutine(func):
         @functools.wraps(func)
         def coro(*args, **kw):
             res = func(*args, **kw)
-            if isinstance(res, futures.Future) or inspect.isgenerator(res) or \
-                    isinstance(res, CoroWrapper):
+            if (futures.isfuture(res) or inspect.isgenerator(res) or
+                isinstance(res, CoroWrapper)):
                 res = yield from res
             elif _AwaitableABC is not None:
                 # If 'func' returns an Awaitable (new in 3.5) we
@@ -238,19 +242,27 @@ def coroutine(func):
             w.__qualname__ = getattr(func, '__qualname__', None)
             return w
 
-    wrapper._is_coroutine = True  # For iscoroutinefunction().
+    wrapper._is_coroutine = _is_coroutine  # For iscoroutinefunction().
     return wrapper
 
 
+# A marker for iscoroutinefunction.
+_is_coroutine = object()
+
+
 def iscoroutinefunction(func):
     """Return True if func is a decorated coroutine function."""
-    return (getattr(func, '_is_coroutine', False) or
+    return (getattr(func, '_is_coroutine', None) is _is_coroutine or
             _inspect_iscoroutinefunction(func))
 
 
 _COROUTINE_TYPES = (types.GeneratorType, CoroWrapper)
 if _CoroutineABC is not None:
     _COROUTINE_TYPES += (_CoroutineABC,)
+if _types_CoroutineType is not None:
+    # Prioritize native coroutine check to speed-up
+    # asyncio.iscoroutine.
+    _COROUTINE_TYPES = (_types_CoroutineType,) + _COROUTINE_TYPES
 
 
 def iscoroutine(obj):
@@ -261,6 +273,29 @@ def iscoroutine(obj):
 def _format_coroutine(coro):
     assert iscoroutine(coro)
 
+    if not hasattr(coro, 'cr_code') and not hasattr(coro, 'gi_code'):
+        # Most likely a built-in type or a Cython coroutine.
+
+        # Built-in types might not have __qualname__ or __name__.
+        coro_name = getattr(
+            coro, '__qualname__',
+            getattr(coro, '__name__', type(coro).__name__))
+        coro_name = '{}()'.format(coro_name)
+
+        running = False
+        try:
+            running = coro.cr_running
+        except AttributeError:
+            try:
+                running = coro.gi_running
+            except AttributeError:
+                pass
+
+        if running:
+            return '{} running'.format(coro_name)
+        else:
+            return coro_name
+
     coro_name = None
     if isinstance(coro, CoroWrapper):
         func = coro.func
@@ -271,7 +306,7 @@ def _format_coroutine(coro):
         func = coro
 
     if coro_name is None:
-        coro_name = events._format_callback(func, ())
+        coro_name = events._format_callback(func, (), {})
 
     try:
         coro_code = coro.gi_code
index c48c5be..28a45fc 100644 (file)
@@ -6,6 +6,7 @@ __all__ = ['AbstractEventLoopPolicy',
            'get_event_loop_policy', 'set_event_loop_policy',
            'get_event_loop', 'set_event_loop', 'new_event_loop',
            'get_child_watcher', 'set_child_watcher',
+           '_set_running_loop', '_get_running_loop',
            ]
 
 import functools
@@ -35,23 +36,25 @@ def _get_function_source(func):
     return None
 
 
-def _format_args(args):
-    """Format function arguments.
+def _format_args_and_kwargs(args, kwargs):
+    """Format function arguments and keyword arguments.
 
     Special case for a single parameter: ('hello',) is formatted as ('hello').
     """
     # use reprlib to limit the length of the output
-    args_repr = reprlib.repr(args)
-    if len(args) == 1 and args_repr.endswith(',)'):
-        args_repr = args_repr[:-2] + ')'
-    return args_repr
+    items = []
+    if args:
+        items.extend(reprlib.repr(arg) for arg in args)
+    if kwargs:
+        items.extend('{}={}'.format(k, reprlib.repr(v))
+                     for k, v in kwargs.items())
+    return '(' + ', '.join(items) + ')'
 
 
-def _format_callback(func, args, suffix=''):
+def _format_callback(func, args, kwargs, suffix=''):
     if isinstance(func, functools.partial):
-        if args is not None:
-            suffix = _format_args(args) + suffix
-        return _format_callback(func.func, func.args, suffix)
+        suffix = _format_args_and_kwargs(args, kwargs) + suffix
+        return _format_callback(func.func, func.args, func.keywords, suffix)
 
     if hasattr(func, '__qualname__'):
         func_repr = getattr(func, '__qualname__')
@@ -60,14 +63,13 @@ def _format_callback(func, args, suffix=''):
     else:
         func_repr = repr(func)
 
-    if args is not None:
-        func_repr += _format_args(args)
+    func_repr += _format_args_and_kwargs(args, kwargs)
     if suffix:
         func_repr += suffix
     return func_repr
 
 def _format_callback_source(func, args):
-    func_repr = _format_callback(func, args)
+    func_repr = _format_callback(func, args, None)
     source = _get_function_source(func)
     if source:
         func_repr += ' at %s:%s' % source
@@ -81,7 +83,6 @@ class Handle:
                  '_source_traceback', '_repr', '__weakref__')
 
     def __init__(self, callback, args, loop):
-        assert not isinstance(callback, Handle), 'A Handle is not a callback'
         self._loop = loop
         self._callback = callback
         self._args = args
@@ -248,6 +249,10 @@ class AbstractEventLoop:
         """
         raise NotImplementedError
 
+    def shutdown_asyncgens(self):
+        """Shutdown all active asynchronous generators."""
+        raise NotImplementedError
+
     # Methods scheduling callbacks.  All these return Handles.
 
     def _timer_handle_cancelled(self, handle):
@@ -603,6 +608,30 @@ _event_loop_policy = None
 _lock = threading.Lock()
 
 
+# A TLS for the running event loop, used by _get_running_loop.
+class _RunningLoop(threading.local):
+    _loop = None
+_running_loop = _RunningLoop()
+
+
+def _get_running_loop():
+    """Return the running event loop or None.
+
+    This is a low-level function intended to be used by event loops.
+    This function is thread-specific.
+    """
+    return _running_loop._loop
+
+
+def _set_running_loop(loop):
+    """Set the running event loop.
+
+    This is a low-level function intended to be used by event loops.
+    This function is thread-specific.
+    """
+    _running_loop._loop = loop
+
+
 def _init_event_loop_policy():
     global _event_loop_policy
     with _lock:
@@ -628,7 +657,17 @@ def set_event_loop_policy(policy):
 
 
 def get_event_loop():
-    """Equivalent to calling get_event_loop_policy().get_event_loop()."""
+    """Return an asyncio event loop.
+
+    When called from a coroutine or a callback (e.g. scheduled with call_soon
+    or similar API), this function will always return the running event loop.
+
+    If there is no running event loop set, the function will return
+    the result of `get_event_loop_policy().get_event_loop()` call.
+    """
+    current_loop = _get_running_loop()
+    if current_loop is not None:
+        return current_loop
     return get_event_loop_policy().get_event_loop()
 
 
index 1feba4d..9ca8d84 100644 (file)
@@ -2,7 +2,7 @@
 
 __all__ = ['CancelledError', 'TimeoutError',
            'InvalidStateError',
-           'Future', 'wrap_future',
+           'Future', 'wrap_future', 'isfuture',
            ]
 
 import concurrent.futures._base
@@ -110,6 +110,17 @@ 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.
 
@@ -134,7 +145,15 @@ class Future:
     _loop = None
     _source_traceback = None
 
-    _blocking = False  # proper use of future (yield vs yield from)
+    # This field is used for a dual purpose:
+    # - Its presence is a marker to declare that a class implements
+    #   the Future protocol (i.e. is intended to be duck-type compatible).
+    #   The value must also be not-None, to enable a subclass to declare
+    #   that it is not compatible by setting this to None.
+    # - It is set by __iter__() below so that Task._step() can tell
+    #   the difference between `yield from Future()` (correct) vs.
+    #   `yield Future()` (incorrect).
+    _asyncio_future_blocking = False
 
     _log_traceback = False   # Used for Python 3.4 and later
     _tb_logger = None        # Used for Python 3.3 only
@@ -357,7 +376,7 @@ class Future:
 
     def __iter__(self):
         if not self.done():
-            self._blocking = True
+            self._asyncio_future_blocking = True
             yield self  # This tells Task to wait for completion.
         assert self.done(), "yield from wasn't used with future"
         return self.result()  # May raise too.
@@ -415,15 +434,17 @@ def _chain_future(source, destination):
     If destination is cancelled, source gets cancelled too.
     Compatible with both asyncio.Future and concurrent.futures.Future.
     """
-    if not isinstance(source, (Future, concurrent.futures.Future)):
+    if not isfuture(source) and not isinstance(source,
+                                               concurrent.futures.Future):
         raise TypeError('A future is required for source argument')
-    if not isinstance(destination, (Future, concurrent.futures.Future)):
+    if not isfuture(destination) and not isinstance(destination,
+                                                    concurrent.futures.Future):
         raise TypeError('A future is required for destination argument')
-    source_loop = source._loop if isinstance(source, Future) else None
-    dest_loop = destination._loop if isinstance(destination, Future) else None
+    source_loop = source._loop if isfuture(source) else None
+    dest_loop = destination._loop if isfuture(destination) else None
 
     def _set_state(future, other):
-        if isinstance(future, Future):
+        if isfuture(future):
             _copy_future_state(other, future)
         else:
             _set_concurrent_future_state(future, other)
@@ -447,7 +468,7 @@ def _chain_future(source, destination):
 
 def wrap_future(future, *, loop=None):
     """Wrap concurrent.futures.Future object."""
-    if isinstance(future, Future):
+    if isfuture(future):
         return future
     assert isinstance(future, concurrent.futures.Future), \
         'concurrent.futures.Future is expected, got {!r}'.format(future)
index 741aaf2..deefc93 100644 (file)
@@ -166,7 +166,7 @@ class Lock(_ContextManagerMixin):
         This method blocks until the lock is unlocked, then sets it to
         locked and returns True.
         """
-        if not self._waiters and not self._locked:
+        if not self._locked and all(w.cancelled() for w in self._waiters):
             self._locked = True
             return True
 
index 3ac314c..fef3205 100644 (file)
@@ -66,6 +66,12 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin,
     def _set_extra(self, sock):
         self._extra['pipe'] = sock
 
+    def set_protocol(self, protocol):
+        self._protocol = protocol
+
+    def get_protocol(self):
+        return self._protocol
+
     def is_closing(self):
         return self._closing
 
@@ -488,7 +494,7 @@ class BaseProactorEventLoop(base_events.BaseEventLoop):
         self._csock.send(b'\0')
 
     def _start_serving(self, protocol_factory, sock,
-                       sslcontext=None, server=None):
+                       sslcontext=None, server=None, backlog=100):
 
         def loop(f=None):
             try:
index c453f02..2d38972 100644 (file)
@@ -7,7 +7,6 @@ import heapq
 
 from . import compat
 from . import events
-from . import futures
 from . import locks
 from .coroutines import coroutine
 
index 9564d01..12d357b 100644 (file)
@@ -11,6 +11,7 @@ import errno
 import functools
 import socket
 import warnings
+import weakref
 try:
     import ssl
 except ImportError:  # pragma: no cover
@@ -39,6 +40,17 @@ def _test_selector_event(selector, fd, event):
         return bool(key.events & event)
 
 
+if hasattr(socket, 'TCP_NODELAY'):
+    def _set_nodelay(sock):
+        if (sock.family in {socket.AF_INET, socket.AF_INET6} and
+                sock.type == socket.SOCK_STREAM and
+                sock.proto == socket.IPPROTO_TCP):
+            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+else:
+    def _set_nodelay(sock):
+        pass
+
+
 class BaseSelectorEventLoop(base_events.BaseEventLoop):
     """Selector event loop.
 
@@ -53,6 +65,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
         logger.debug('Using selector: %s', selector.__class__.__name__)
         self._selector = selector
         self._make_self_pipe()
+        self._transports = weakref.WeakValueDictionary()
 
     def _make_socket_transport(self, sock, protocol, waiter=None, *,
                                extra=None, server=None):
@@ -104,7 +117,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
         raise NotImplementedError
 
     def _close_self_pipe(self):
-        self.remove_reader(self._ssock.fileno())
+        self._remove_reader(self._ssock.fileno())
         self._ssock.close()
         self._ssock = None
         self._csock.close()
@@ -117,7 +130,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
         self._ssock.setblocking(False)
         self._csock.setblocking(False)
         self._internal_fds += 1
-        self.add_reader(self._ssock.fileno(), self._read_from_self)
+        self._add_reader(self._ssock.fileno(), self._read_from_self)
 
     def _process_self_data(self, data):
         pass
@@ -151,43 +164,50 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
                                  exc_info=True)
 
     def _start_serving(self, protocol_factory, sock,
-                       sslcontext=None, server=None):
-        self.add_reader(sock.fileno(), self._accept_connection,
-                        protocol_factory, sock, sslcontext, server)
+                       sslcontext=None, server=None, backlog=100):
+        self._add_reader(sock.fileno(), self._accept_connection,
+                         protocol_factory, sock, sslcontext, server, backlog)
 
     def _accept_connection(self, protocol_factory, sock,
-                           sslcontext=None, server=None):
-        try:
-            conn, addr = sock.accept()
-            if self._debug:
-                logger.debug("%r got a new connection from %r: %r",
-                             server, addr, conn)
-            conn.setblocking(False)
-        except (BlockingIOError, InterruptedError, ConnectionAbortedError):
-            pass  # False alarm.
-        except OSError as exc:
-            # There's nowhere to send the error, so just log it.
-            if exc.errno in (errno.EMFILE, errno.ENFILE,
-                             errno.ENOBUFS, errno.ENOMEM):
-                # Some platforms (e.g. Linux keep reporting the FD as
-                # ready, so we remove the read handler temporarily.
-                # We'll try again in a while.
-                self.call_exception_handler({
-                    'message': 'socket.accept() out of system resource',
-                    'exception': exc,
-                    'socket': sock,
-                })
-                self.remove_reader(sock.fileno())
-                self.call_later(constants.ACCEPT_RETRY_DELAY,
-                                self._start_serving,
-                                protocol_factory, sock, sslcontext, server)
+                           sslcontext=None, server=None, backlog=100):
+        # This method is only called once for each event loop tick where the
+        # listening socket has triggered an EVENT_READ. There may be multiple
+        # connections waiting for an .accept() so it is called in a loop.
+        # See https://bugs.python.org/issue27906 for more details.
+        for _ in range(backlog):
+            try:
+                conn, addr = sock.accept()
+                if self._debug:
+                    logger.debug("%r got a new connection from %r: %r",
+                                 server, addr, conn)
+                conn.setblocking(False)
+            except (BlockingIOError, InterruptedError, ConnectionAbortedError):
+                # Early exit because the socket accept buffer is empty.
+                return None
+            except OSError as exc:
+                # There's nowhere to send the error, so just log it.
+                if exc.errno in (errno.EMFILE, errno.ENFILE,
+                                 errno.ENOBUFS, errno.ENOMEM):
+                    # Some platforms (e.g. Linux keep reporting the FD as
+                    # ready, so we remove the read handler temporarily.
+                    # We'll try again in a while.
+                    self.call_exception_handler({
+                        'message': 'socket.accept() out of system resource',
+                        'exception': exc,
+                        'socket': sock,
+                    })
+                    self._remove_reader(sock.fileno())
+                    self.call_later(constants.ACCEPT_RETRY_DELAY,
+                                    self._start_serving,
+                                    protocol_factory, sock, sslcontext, server,
+                                    backlog)
+                else:
+                    raise  # The event loop will catch, log and ignore it.
             else:
-                raise  # The event loop will catch, log and ignore it.
-        else:
-            extra = {'peername': addr}
-            accept = self._accept_connection2(protocol_factory, conn, extra,
-                                              sslcontext, server)
-            self.create_task(accept)
+                extra = {'peername': addr}
+                accept = self._accept_connection2(protocol_factory, conn, extra,
+                                                  sslcontext, server)
+                self.create_task(accept)
 
     @coroutine
     def _accept_connection2(self, protocol_factory, conn, extra,
@@ -226,8 +246,18 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
                     context['transport'] = transport
                 self.call_exception_handler(context)
 
-    def add_reader(self, fd, callback, *args):
-        """Add a reader callback."""
+    def _ensure_fd_no_transport(self, fd):
+        try:
+            transport = self._transports[fd]
+        except KeyError:
+            pass
+        else:
+            if not transport.is_closing():
+                raise RuntimeError(
+                    'File descriptor {!r} is used by transport {!r}'.format(
+                        fd, transport))
+
+    def _add_reader(self, fd, callback, *args):
         self._check_closed()
         handle = events.Handle(callback, args, self)
         try:
@@ -242,8 +272,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
             if reader is not None:
                 reader.cancel()
 
-    def remove_reader(self, fd):
-        """Remove a reader callback."""
+    def _remove_reader(self, fd):
         if self.is_closed():
             return False
         try:
@@ -264,8 +293,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
             else:
                 return False
 
-    def add_writer(self, fd, callback, *args):
-        """Add a writer callback.."""
+    def _add_writer(self, fd, callback, *args):
         self._check_closed()
         handle = events.Handle(callback, args, self)
         try:
@@ -280,7 +308,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
             if writer is not None:
                 writer.cancel()
 
-    def remove_writer(self, fd):
+    def _remove_writer(self, fd):
         """Remove a writer callback."""
         if self.is_closed():
             return False
@@ -303,6 +331,26 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
             else:
                 return False
 
+    def add_reader(self, fd, callback, *args):
+        """Add a reader callback."""
+        self._ensure_fd_no_transport(fd)
+        return self._add_reader(fd, callback, *args)
+
+    def remove_reader(self, fd):
+        """Remove a reader callback."""
+        self._ensure_fd_no_transport(fd)
+        return self._remove_reader(fd)
+
+    def add_writer(self, fd, callback, *args):
+        """Add a writer callback.."""
+        self._ensure_fd_no_transport(fd)
+        return self._add_writer(fd, callback, *args)
+
+    def remove_writer(self, fd):
+        """Remove a writer callback."""
+        self._ensure_fd_no_transport(fd)
+        return self._remove_writer(fd)
+
     def sock_recv(self, sock, n):
         """Receive data from the socket.
 
@@ -382,6 +430,7 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
                 data = data[n:]
             self.add_writer(fd, self._sock_sendall, fut, True, sock, data)
 
+    @coroutine
     def sock_connect(self, sock, address):
         """Connect to a remote socket at address.
 
@@ -390,23 +439,16 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
         if self._debug and sock.gettimeout() != 0:
             raise ValueError("the socket must be non-blocking")
 
-        fut = self.create_future()
-        if hasattr(socket, 'AF_UNIX') and sock.family == socket.AF_UNIX:
-            self._sock_connect(fut, sock, address)
-        else:
-            resolved = base_events._ensure_resolved(address, loop=self)
-            resolved.add_done_callback(
-                lambda resolved: self._on_resolved(fut, sock, resolved))
-
-        return fut
-
-    def _on_resolved(self, fut, sock, resolved):
-        try:
+        if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX:
+            resolved = base_events._ensure_resolved(
+                address, family=sock.family, proto=sock.proto, loop=self)
+            if not resolved.done():
+                yield from resolved
             _, _, _, _, address = resolved.result()[0]
-        except Exception as exc:
-            fut.set_exception(exc)
-        else:
-            self._sock_connect(fut, sock, address)
+
+        fut = self.create_future()
+        self._sock_connect(fut, sock, address)
+        return (yield from fut)
 
     def _sock_connect(self, fut, sock, address):
         fd = sock.fileno()
@@ -417,8 +459,8 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
             # connection runs in background. We have to wait until the socket
             # becomes writable to be notified when the connection succeed or
             # fails.
-            fut.add_done_callback(functools.partial(self._sock_connect_done,
-                                                    fd))
+            fut.add_done_callback(
+                functools.partial(self._sock_connect_done, fd))
             self.add_writer(fd, self._sock_connect_cb, fut, sock, address)
         except Exception as exc:
             fut.set_exception(exc)
@@ -482,17 +524,17 @@ class BaseSelectorEventLoop(base_events.BaseEventLoop):
             fileobj, (reader, writer) = key.fileobj, key.data
             if mask & selectors.EVENT_READ and reader is not None:
                 if reader._cancelled:
-                    self.remove_reader(fileobj)
+                    self._remove_reader(fileobj)
                 else:
                     self._add_callback(reader)
             if mask & selectors.EVENT_WRITE and writer is not None:
                 if writer._cancelled:
-                    self.remove_writer(fileobj)
+                    self._remove_writer(fileobj)
                 else:
                     self._add_callback(writer)
 
     def _stop_serving(self, sock):
-        self.remove_reader(sock.fileno())
+        self._remove_reader(sock.fileno())
         sock.close()
 
 
@@ -527,6 +569,7 @@ class _SelectorTransport(transports._FlowControlMixin,
         self._closing = False  # Set when close() called.
         if self._server is not None:
             self._server._attach()
+        loop._transports[self._sock_fd] = self
 
     def __repr__(self):
         info = [self.__class__.__name__]
@@ -559,6 +602,12 @@ class _SelectorTransport(transports._FlowControlMixin,
     def abort(self):
         self._force_close(None)
 
+    def set_protocol(self, protocol):
+        self._protocol = protocol
+
+    def get_protocol(self):
+        return self._protocol
+
     def is_closing(self):
         return self._closing
 
@@ -566,10 +615,10 @@ class _SelectorTransport(transports._FlowControlMixin,
         if self._closing:
             return
         self._closing = True
-        self._loop.remove_reader(self._sock_fd)
+        self._loop._remove_reader(self._sock_fd)
         if not self._buffer:
             self._conn_lost += 1
-            self._loop.remove_writer(self._sock_fd)
+            self._loop._remove_writer(self._sock_fd)
             self._loop.call_soon(self._call_connection_lost, None)
 
     # On Python 3.3 and older, objects with a destructor part of a reference
@@ -600,10 +649,10 @@ class _SelectorTransport(transports._FlowControlMixin,
             return
         if self._buffer:
             self._buffer.clear()
-            self._loop.remove_writer(self._sock_fd)
+            self._loop._remove_writer(self._sock_fd)
         if not self._closing:
             self._closing = True
-            self._loop.remove_reader(self._sock_fd)
+            self._loop._remove_reader(self._sock_fd)
         self._conn_lost += 1
         self._loop.call_soon(self._call_connection_lost, exc)
 
@@ -633,9 +682,14 @@ class _SelectorSocketTransport(_SelectorTransport):
         self._eof = False
         self._paused = False
 
+        # Disable the Nagle algorithm -- small writes will be
+        # sent without waiting for the TCP ACK.  This generally
+        # decreases the latency (in some cases significantly.)
+        _set_nodelay(self._sock)
+
         self._loop.call_soon(self._protocol.connection_made, self)
         # only start reading when connection_made() has been called
-        self._loop.call_soon(self._loop.add_reader,
+        self._loop.call_soon(self._loop._add_reader,
                              self._sock_fd, self._read_ready)
         if waiter is not None:
             # only wake up the waiter when connection_made() has been called
@@ -648,7 +702,7 @@ class _SelectorSocketTransport(_SelectorTransport):
         if self._paused:
             raise RuntimeError('Already paused')
         self._paused = True
-        self._loop.remove_reader(self._sock_fd)
+        self._loop._remove_reader(self._sock_fd)
         if self._loop.get_debug():
             logger.debug("%r pauses reading", self)
 
@@ -658,7 +712,7 @@ class _SelectorSocketTransport(_SelectorTransport):
         self._paused = False
         if self._closing:
             return
-        self._loop.add_reader(self._sock_fd, self._read_ready)
+        self._loop._add_reader(self._sock_fd, self._read_ready)
         if self._loop.get_debug():
             logger.debug("%r resumes reading", self)
 
@@ -682,7 +736,7 @@ class _SelectorSocketTransport(_SelectorTransport):
                     # We're keeping the connection open so the
                     # protocol can write more, but we still can't
                     # receive more, so remove the reader callback.
-                    self._loop.remove_reader(self._sock_fd)
+                    self._loop._remove_reader(self._sock_fd)
                 else:
                     self.close()
 
@@ -715,7 +769,7 @@ class _SelectorSocketTransport(_SelectorTransport):
                 if not data:
                     return
             # Not all was written; register write handler.
-            self._loop.add_writer(self._sock_fd, self._write_ready)
+            self._loop._add_writer(self._sock_fd, self._write_ready)
 
         # Add it to the buffer.
         self._buffer.extend(data)
@@ -731,7 +785,7 @@ class _SelectorSocketTransport(_SelectorTransport):
         except (BlockingIOError, InterruptedError):
             pass
         except Exception as exc:
-            self._loop.remove_writer(self._sock_fd)
+            self._loop._remove_writer(self._sock_fd)
             self._buffer.clear()
             self._fatal_error(exc, 'Fatal write error on socket transport')
         else:
@@ -739,7 +793,7 @@ class _SelectorSocketTransport(_SelectorTransport):
                 del self._buffer[:n]
             self._maybe_resume_protocol()  # May append to buffer.
             if not self._buffer:
-                self._loop.remove_writer(self._sock_fd)
+                self._loop._remove_writer(self._sock_fd)
                 if self._closing:
                     self._call_connection_lost(None)
                 elif self._eof:
@@ -810,19 +864,19 @@ class _SelectorSslTransport(_SelectorTransport):
         try:
             self._sock.do_handshake()
         except ssl.SSLWantReadError:
-            self._loop.add_reader(self._sock_fd,
-                                  self._on_handshake, start_time)
+            self._loop._add_reader(self._sock_fd,
+                                   self._on_handshake, start_time)
             return
         except ssl.SSLWantWriteError:
-            self._loop.add_writer(self._sock_fd,
-                                  self._on_handshake, start_time)
+            self._loop._add_writer(self._sock_fd,
+                                   self._on_handshake, start_time)
             return
         except BaseException as exc:
             if self._loop.get_debug():
                 logger.warning("%r: SSL handshake failed",
                                self, exc_info=True)
-            self._loop.remove_reader(self._sock_fd)
-            self._loop.remove_writer(self._sock_fd)
+            self._loop._remove_reader(self._sock_fd)
+            self._loop._remove_writer(self._sock_fd)
             self._sock.close()
             self._wakeup_waiter(exc)
             if isinstance(exc, Exception):
@@ -830,8 +884,8 @@ class _SelectorSslTransport(_SelectorTransport):
             else:
                 raise
 
-        self._loop.remove_reader(self._sock_fd)
-        self._loop.remove_writer(self._sock_fd)
+        self._loop._remove_reader(self._sock_fd)
+        self._loop._remove_writer(self._sock_fd)
 
         peercert = self._sock.getpeercert()
         if not hasattr(self._sslcontext, 'check_hostname'):
@@ -859,7 +913,7 @@ class _SelectorSslTransport(_SelectorTransport):
 
         self._read_wants_write = False
         self._write_wants_read = False
-        self._loop.add_reader(self._sock_fd, self._read_ready)
+        self._loop._add_reader(self._sock_fd, self._read_ready)
         self._protocol_connected = True
         self._loop.call_soon(self._protocol.connection_made, self)
         # only wake up the waiter when connection_made() has been called
@@ -881,7 +935,7 @@ class _SelectorSslTransport(_SelectorTransport):
         if self._paused:
             raise RuntimeError('Already paused')
         self._paused = True
-        self._loop.remove_reader(self._sock_fd)
+        self._loop._remove_reader(self._sock_fd)
         if self._loop.get_debug():
             logger.debug("%r pauses reading", self)
 
@@ -891,7 +945,7 @@ class _SelectorSslTransport(_SelectorTransport):
         self._paused = False
         if self._closing:
             return
-        self._loop.add_reader(self._sock_fd, self._read_ready)
+        self._loop._add_reader(self._sock_fd, self._read_ready)
         if self._loop.get_debug():
             logger.debug("%r resumes reading", self)
 
@@ -903,7 +957,7 @@ class _SelectorSslTransport(_SelectorTransport):
             self._write_ready()
 
             if self._buffer:
-                self._loop.add_writer(self._sock_fd, self._write_ready)
+                self._loop._add_writer(self._sock_fd, self._write_ready)
 
         try:
             data = self._sock.recv(self.max_size)
@@ -911,8 +965,8 @@ class _SelectorSslTransport(_SelectorTransport):
             pass
         except ssl.SSLWantWriteError:
             self._read_wants_write = True
-            self._loop.remove_reader(self._sock_fd)
-            self._loop.add_writer(self._sock_fd, self._write_ready)
+            self._loop._remove_reader(self._sock_fd)
+            self._loop._add_writer(self._sock_fd, self._write_ready)
         except Exception as exc:
             self._fatal_error(exc, 'Fatal read error on SSL transport')
         else:
@@ -937,7 +991,7 @@ class _SelectorSslTransport(_SelectorTransport):
             self._read_ready()
 
             if not (self._paused or self._closing):
-                self._loop.add_reader(self._sock_fd, self._read_ready)
+                self._loop._add_reader(self._sock_fd, self._read_ready)
 
         if self._buffer:
             try:
@@ -946,10 +1000,10 @@ class _SelectorSslTransport(_SelectorTransport):
                 n = 0
             except ssl.SSLWantReadError:
                 n = 0
-                self._loop.remove_writer(self._sock_fd)
+                self._loop._remove_writer(self._sock_fd)
                 self._write_wants_read = True
             except Exception as exc:
-                self._loop.remove_writer(self._sock_fd)
+                self._loop._remove_writer(self._sock_fd)
                 self._buffer.clear()
                 self._fatal_error(exc, 'Fatal write error on SSL transport')
                 return
@@ -960,7 +1014,7 @@ class _SelectorSslTransport(_SelectorTransport):
         self._maybe_resume_protocol()  # May append to buffer.
 
         if not self._buffer:
-            self._loop.remove_writer(self._sock_fd)
+            self._loop._remove_writer(self._sock_fd)
             if self._closing:
                 self._call_connection_lost(None)
 
@@ -978,7 +1032,7 @@ class _SelectorSslTransport(_SelectorTransport):
             return
 
         if not self._buffer:
-            self._loop.add_writer(self._sock_fd, self._write_ready)
+            self._loop._add_writer(self._sock_fd, self._write_ready)
 
         # Add it to the buffer.
         self._buffer.extend(data)
@@ -998,7 +1052,7 @@ class _SelectorDatagramTransport(_SelectorTransport):
         self._address = address
         self._loop.call_soon(self._protocol.connection_made, self)
         # only start reading when connection_made() has been called
-        self._loop.call_soon(self._loop.add_reader,
+        self._loop.call_soon(self._loop._add_reader,
                              self._sock_fd, self._read_ready)
         if waiter is not None:
             # only wake up the waiter when connection_made() has been called
@@ -1048,7 +1102,7 @@ class _SelectorDatagramTransport(_SelectorTransport):
                     self._sock.sendto(data, addr)
                 return
             except (BlockingIOError, InterruptedError):
-                self._loop.add_writer(self._sock_fd, self._sendto_ready)
+                self._loop._add_writer(self._sock_fd, self._sendto_ready)
             except OSError as exc:
                 self._protocol.error_received(exc)
                 return
@@ -1082,6 +1136,6 @@ class _SelectorDatagramTransport(_SelectorTransport):
 
         self._maybe_resume_protocol()  # May append to buffer.
         if not self._buffer:
-            self._loop.remove_writer(self._sock_fd)
+            self._loop._remove_writer(self._sock_fd)
             if self._closing:
                 self._call_connection_lost(None)
index f58b5ac..c2c4b95 100644 (file)
@@ -5,6 +5,7 @@ try:
 except ImportError:  # pragma: no cover
     ssl = None
 
+from . import base_events
 from . import compat
 from . import protocols
 from . import transports
@@ -304,6 +305,12 @@ class _SSLProtocolTransport(transports._FlowControlMixin,
         """Get optional transport information."""
         return self._ssl_protocol._get_extra_info(name, default)
 
+    def set_protocol(self, protocol):
+        self._app_protocol = protocol
+
+    def get_protocol(self):
+        return self._app_protocol
+
     def is_closing(self):
         return self._closed
 
@@ -403,7 +410,8 @@ class SSLProtocol(protocols.Protocol):
     """
 
     def __init__(self, loop, app_protocol, sslcontext, waiter,
-                 server_side=False, server_hostname=None):
+                 server_side=False, server_hostname=None,
+                 call_connection_made=True):
         if ssl is None:
             raise RuntimeError('stdlib ssl module not available')
 
@@ -436,6 +444,7 @@ class SSLProtocol(protocols.Protocol):
         self._in_shutdown = False
         # transport, ex: SelectorSocketTransport
         self._transport = None
+        self._call_connection_made = call_connection_made
 
     def _wakeup_waiter(self, exc=None):
         if self._waiter is None:
@@ -470,6 +479,7 @@ class SSLProtocol(protocols.Protocol):
             self._loop.call_soon(self._app_protocol.connection_lost, exc)
         self._transport = None
         self._app_transport = None
+        self._wakeup_waiter(exc)
 
     def pause_writing(self):
         """Called when the low-level transport's buffer goes over
@@ -599,7 +609,8 @@ class SSLProtocol(protocols.Protocol):
                            compression=sslobj.compression(),
                            ssl_object=sslobj,
                            )
-        self._app_protocol.connection_made(self._app_transport)
+        if self._call_connection_made:
+            self._app_protocol.connection_made(self._app_transport)
         self._wakeup_waiter()
         self._session_established = True
         # In case transport.write() was already called. Don't call
index c88a87c..a82cc79 100644 (file)
@@ -448,6 +448,7 @@ class StreamReader:
         assert not self._eof, '_wait_for_data after EOF'
 
         # Waiting for data while paused will make deadlock, so prevent it.
+        # This is essential for readexactly(n) for case when n > self._limit.
         if self._paused:
             self._paused = False
             self._transport.resume_reading()
@@ -590,7 +591,7 @@ class StreamReader:
         bytes. If the EOF was received and the internal buffer is empty, return
         an empty bytes object.
 
-        If n is zero, return empty bytes object immediatelly.
+        If n is zero, return empty bytes object immediately.
 
         If n is positive, this function try to read `n` bytes, and may return
         less or equal bytes than requested, but at least one byte. If EOF was
@@ -658,25 +659,22 @@ class StreamReader:
         if n == 0:
             return b''
 
-        # There used to be "optimized" code here.  It created its own
-        # Future and waited until self._buffer had at least the n
-        # bytes, then called read(n).  Unfortunately, this could pause
-        # the transport if the argument was larger than the pause
-        # limit (which is twice self._limit).  So now we just read()
-        # into a local buffer.
-
-        blocks = []
-        while n > 0:
-            block = yield from self.read(n)
-            if not block:
-                partial = b''.join(blocks)
-                raise IncompleteReadError(partial, len(partial) + n)
-            blocks.append(block)
-            n -= len(block)
-
-        assert n == 0
-
-        return b''.join(blocks)
+        while len(self._buffer) < n:
+            if self._eof:
+                incomplete = bytes(self._buffer)
+                self._buffer.clear()
+                raise IncompleteReadError(incomplete, n)
+
+            yield from self._wait_for_data('readexactly')
+
+        if len(self._buffer) == n:
+            data = bytes(self._buffer)
+            self._buffer.clear()
+        else:
+            data = bytes(self._buffer[:n])
+            del self._buffer[:n]
+        self._maybe_resume_transport()
+        return data
 
     if compat.PY35:
         @coroutine
index 0cca8e3..8852aa5 100644 (file)
@@ -241,7 +241,7 @@ class Task(futures.Future):
                 result = coro.throw(exc)
         except StopIteration as exc:
             self.set_result(exc.value)
-        except futures.CancelledError as exc:
+        except futures.CancelledError:
             super().cancel()  # I.e., Future.cancel(self).
         except Exception as exc:
             self.set_exception(exc)
@@ -249,7 +249,8 @@ class Task(futures.Future):
             self.set_exception(exc)
             raise
         else:
-            if isinstance(result, futures.Future):
+            blocking = getattr(result, '_asyncio_future_blocking', None)
+            if blocking is not None:
                 # Yielded Future must come from Future.__iter__().
                 if result._loop is not self._loop:
                     self._loop.call_soon(
@@ -257,13 +258,20 @@ class Task(futures.Future):
                         RuntimeError(
                             'Task {!r} got Future {!r} attached to a '
                             'different loop'.format(self, result)))
-                elif result._blocking:
-                    result._blocking = False
-                    result.add_done_callback(self._wakeup)
-                    self._fut_waiter = result
-                    if self._must_cancel:
-                        if self._fut_waiter.cancel():
-                            self._must_cancel = False
+                elif blocking:
+                    if result is self:
+                        self._loop.call_soon(
+                            self._step,
+                            RuntimeError(
+                                'Task cannot await on itself: {!r}'.format(
+                                    self)))
+                    else:
+                        result._asyncio_future_blocking = False
+                        result.add_done_callback(self._wakeup)
+                        self._fut_waiter = result
+                        if self._must_cancel:
+                            if self._fut_waiter.cancel():
+                                self._must_cancel = False
                 else:
                     self._loop.call_soon(
                         self._step,
@@ -332,7 +340,7 @@ def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
     Note: This does not raise TimeoutError! Futures that aren't done
     when the timeout occurs are returned in the second set.
     """
-    if isinstance(fs, futures.Future) or coroutines.iscoroutine(fs):
+    if futures.isfuture(fs) or coroutines.iscoroutine(fs):
         raise TypeError("expect a list of futures, not %s" % type(fs).__name__)
     if not fs:
         raise ValueError('Set of coroutines/Futures is empty.')
@@ -461,7 +469,7 @@ def as_completed(fs, *, loop=None, timeout=None):
 
     Note: The futures 'f' are not necessarily members of fs.
     """
-    if isinstance(fs, futures.Future) or coroutines.iscoroutine(fs):
+    if futures.isfuture(fs) or coroutines.iscoroutine(fs):
         raise TypeError("expect a list of futures, not %s" % type(fs).__name__)
     loop = loop if loop is not None else events.get_event_loop()
     todo = {ensure_future(f, loop=loop) for f in set(fs)}
@@ -518,7 +526,7 @@ def sleep(delay, result=None, *, loop=None):
         h.cancel()
 
 
-def async(coro_or_future, *, loop=None):
+def async_(coro_or_future, *, loop=None):
     """Wrap a coroutine in a future.
 
     If the argument is a Future, it is returned directly.
@@ -531,13 +539,18 @@ def async(coro_or_future, *, loop=None):
 
     return ensure_future(coro_or_future, loop=loop)
 
+# Silence DeprecationWarning:
+globals()['async'] = async_
+async_.__name__ = 'async'
+del async_
+
 
 def ensure_future(coro_or_future, *, loop=None):
     """Wrap a coroutine or an awaitable in a future.
 
     If the argument is a Future, it is returned directly.
     """
-    if isinstance(coro_or_future, futures.Future):
+    if futures.isfuture(coro_or_future):
         if loop is not None and loop is not coro_or_future._loop:
             raise ValueError('loop argument must agree with Future')
         return coro_or_future
@@ -579,15 +592,21 @@ class _GatheringFuture(futures.Future):
     def cancel(self):
         if self.done():
             return False
+        ret = False
         for child in self._children:
-            child.cancel()
-        return True
+            if child.cancel():
+                ret = True
+        return ret
 
 
 def gather(*coros_or_futures, loop=None, return_exceptions=False):
     """Return a future aggregating results from the given coroutines
     or futures.
 
+    Coroutines will be wrapped in a future and scheduled in the event
+    loop. They will not necessarily be scheduled in the same order as
+    passed in.
+
     All futures must share the same event loop.  If all the tasks are
     done successfully, the returned future's result is the list of
     results (in the order of the original sequence, not necessarily
@@ -613,7 +632,7 @@ def gather(*coros_or_futures, loop=None, return_exceptions=False):
 
     arg_to_fut = {}
     for arg in set(coros_or_futures):
-        if not isinstance(arg, futures.Future):
+        if not futures.isfuture(arg):
             fut = ensure_future(arg, loop=loop)
             if loop is None:
                 loop = fut._loop
index 396e6ae..9d32822 100644 (file)
@@ -13,6 +13,8 @@ import tempfile
 import threading
 import time
 import unittest
+import weakref
+
 from unittest import mock
 
 from http.server import HTTPServer
@@ -300,6 +302,8 @@ class TestLoop(base_events.BaseEventLoop):
         self.writers = {}
         self.reset_counters()
 
+        self._transports = weakref.WeakValueDictionary()
+
     def time(self):
         return self._time
 
@@ -318,10 +322,10 @@ class TestLoop(base_events.BaseEventLoop):
             else:  # pragma: no cover
                 raise AssertionError("Time generator is not finished")
 
-    def add_reader(self, fd, callback, *args):
+    def _add_reader(self, fd, callback, *args):
         self.readers[fd] = events.Handle(callback, args, self)
 
-    def remove_reader(self, fd):
+    def _remove_reader(self, fd):
         self.remove_reader_count[fd] += 1
         if fd in self.readers:
             del self.readers[fd]
@@ -337,10 +341,10 @@ class TestLoop(base_events.BaseEventLoop):
         assert handle._args == args, '{!r} != {!r}'.format(
             handle._args, args)
 
-    def add_writer(self, fd, callback, *args):
+    def _add_writer(self, fd, callback, *args):
         self.writers[fd] = events.Handle(callback, args, self)
 
-    def remove_writer(self, fd):
+    def _remove_writer(self, fd):
         self.remove_writer_count[fd] += 1
         if fd in self.writers:
             del self.writers[fd]
@@ -356,6 +360,36 @@ class TestLoop(base_events.BaseEventLoop):
         assert handle._args == args, '{!r} != {!r}'.format(
             handle._args, args)
 
+    def _ensure_fd_no_transport(self, fd):
+        try:
+            transport = self._transports[fd]
+        except KeyError:
+            pass
+        else:
+            raise RuntimeError(
+                'File descriptor {!r} is used by transport {!r}'.format(
+                    fd, transport))
+
+    def add_reader(self, fd, callback, *args):
+        """Add a reader callback."""
+        self._ensure_fd_no_transport(fd)
+        return self._add_reader(fd, callback, *args)
+
+    def remove_reader(self, fd):
+        """Remove a reader callback."""
+        self._ensure_fd_no_transport(fd)
+        return self._remove_reader(fd)
+
+    def add_writer(self, fd, callback, *args):
+        """Add a writer callback.."""
+        self._ensure_fd_no_transport(fd)
+        return self._add_writer(fd, callback, *args)
+
+    def remove_writer(self, fd):
+        """Remove a writer callback."""
+        self._ensure_fd_no_transport(fd)
+        return self._remove_writer(fd)
+
     def reset_counters(self):
         self.remove_reader_count = collections.defaultdict(int)
         self.remove_writer_count = collections.defaultdict(int)
@@ -415,7 +449,13 @@ class TestCase(unittest.TestCase):
         self.set_event_loop(loop)
         return loop
 
+    def setUp(self):
+        self._get_running_loop = events._get_running_loop
+        events._get_running_loop = lambda: None
+
     def tearDown(self):
+        events._get_running_loop = self._get_running_loop
+
         events.set_event_loop(None)
 
         # Detect CPython bug #23353: ensure that yield/yield-from is not used
index 9a6d919..0db0875 100644 (file)
@@ -33,6 +33,14 @@ class BaseTransport:
         """
         raise NotImplementedError
 
+    def set_protocol(self, protocol):
+        """Set a new protocol."""
+        raise NotImplementedError
+
+    def get_protocol(self):
+        """Return the current protocol."""
+        raise NotImplementedError
+
 
 class ReadTransport(BaseTransport):
     """Interface for read-only transports."""
index d712749..7790534 100644 (file)
@@ -39,6 +39,13 @@ def _sighandler_noop(signum, frame):
     pass
 
 
+try:
+    _fspath = os.fspath
+except AttributeError:
+    # Python 3.5 or earlier
+    _fspath = lambda path: path
+
+
 class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
     """Unix event loop.
 
@@ -234,6 +241,11 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
         else:
             if sock is None:
                 raise ValueError('no path and sock were specified')
+            if (sock.family != socket.AF_UNIX or
+                    not base_events._is_stream_socket(sock)):
+                raise ValueError(
+                    'A UNIX Domain Stream Socket was expected, got {!r}'
+                    .format(sock))
             sock.setblocking(False)
 
         transport, protocol = yield from self._create_connection_transport(
@@ -251,8 +263,20 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
                 raise ValueError(
                     'path and sock can not be specified at the same time')
 
+            path = _fspath(path)
             sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
 
+            # Check for abstract socket. `str` and `bytes` paths are supported.
+            if path[0] not in (0, '\x00'):
+                try:
+                    if stat.S_ISSOCK(os.stat(path).st_mode):
+                        os.remove(path)
+                except FileNotFoundError:
+                    pass
+                except OSError as err:
+                    # Directory may have permissions only to create socket.
+                    logger.error('Unable to check or remove stale UNIX socket %r: %r', path, err)
+
             try:
                 sock.bind(path)
             except OSError as exc:
@@ -272,9 +296,11 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
                 raise ValueError(
                     'path was not specified, and no sock specified')
 
-            if sock.family != socket.AF_UNIX:
+            if (sock.family != socket.AF_UNIX or
+                    not base_events._is_stream_socket(sock)):
                 raise ValueError(
-                    'A UNIX Domain Socket was expected, got {!r}'.format(sock))
+                    'A UNIX Domain Stream Socket was expected, got {!r}'
+                    .format(sock))
 
         server = base_events.Server(self, [sock])
         sock.listen(backlog)
@@ -305,17 +331,23 @@ class _UnixReadPipeTransport(transports.ReadTransport):
         self._loop = loop
         self._pipe = pipe
         self._fileno = pipe.fileno()
+        self._protocol = protocol
+        self._closing = False
+
         mode = os.fstat(self._fileno).st_mode
         if not (stat.S_ISFIFO(mode) or
                 stat.S_ISSOCK(mode) or
                 stat.S_ISCHR(mode)):
+            self._pipe = None
+            self._fileno = None
+            self._protocol = None
             raise ValueError("Pipe transport is for pipes/sockets only.")
+
         _set_nonblocking(self._fileno)
-        self._protocol = protocol
-        self._closing = False
+
         self._loop.call_soon(self._protocol.connection_made, self)
         # only start reading when connection_made() has been called
-        self._loop.call_soon(self._loop.add_reader,
+        self._loop.call_soon(self._loop._add_reader,
                              self._fileno, self._read_ready)
         if waiter is not None:
             # only wake up the waiter when connection_made() has been called
@@ -358,15 +390,21 @@ class _UnixReadPipeTransport(transports.ReadTransport):
                 if self._loop.get_debug():
                     logger.info("%r was closed by peer", self)
                 self._closing = True
-                self._loop.remove_reader(self._fileno)
+                self._loop._remove_reader(self._fileno)
                 self._loop.call_soon(self._protocol.eof_received)
                 self._loop.call_soon(self._call_connection_lost, None)
 
     def pause_reading(self):
-        self._loop.remove_reader(self._fileno)
+        self._loop._remove_reader(self._fileno)
 
     def resume_reading(self):
-        self._loop.add_reader(self._fileno, self._read_ready)
+        self._loop._add_reader(self._fileno, self._read_ready)
+
+    def set_protocol(self, protocol):
+        self._protocol = protocol
+
+    def get_protocol(self):
+        return self._protocol
 
     def is_closing(self):
         return self._closing
@@ -400,7 +438,7 @@ class _UnixReadPipeTransport(transports.ReadTransport):
 
     def _close(self, exc):
         self._closing = True
-        self._loop.remove_reader(self._fileno)
+        self._loop._remove_reader(self._fileno)
         self._loop.call_soon(self._call_connection_lost, exc)
 
     def _call_connection_lost(self, exc):
@@ -421,27 +459,31 @@ class _UnixWritePipeTransport(transports._FlowControlMixin,
         self._extra['pipe'] = pipe
         self._pipe = pipe
         self._fileno = pipe.fileno()
+        self._protocol = protocol
+        self._buffer = bytearray()
+        self._conn_lost = 0
+        self._closing = False  # Set when close() or write_eof() called.
+
         mode = os.fstat(self._fileno).st_mode
+        is_char = stat.S_ISCHR(mode)
+        is_fifo = stat.S_ISFIFO(mode)
         is_socket = stat.S_ISSOCK(mode)
-        if not (is_socket or
-                stat.S_ISFIFO(mode) or
-                stat.S_ISCHR(mode)):
+        if not (is_char or is_fifo or is_socket):
+            self._pipe = None
+            self._fileno = None
+            self._protocol = None
             raise ValueError("Pipe transport is only for "
                              "pipes, sockets and character devices")
-        _set_nonblocking(self._fileno)
-        self._protocol = protocol
-        self._buffer = []
-        self._conn_lost = 0
-        self._closing = False  # Set when close() or write_eof() called.
 
+        _set_nonblocking(self._fileno)
         self._loop.call_soon(self._protocol.connection_made, self)
 
         # On AIX, the reader trick (to be notified when the read end of the
         # socket is closed) only works for sockets. On other platforms it
         # works for pipes and sockets. (Exception: OS X 10.4?  Issue #19294.)
-        if is_socket or not sys.platform.startswith("aix"):
+        if is_socket or (is_fifo and not sys.platform.startswith("aix")):
             # only start reading when connection_made() has been called
-            self._loop.call_soon(self._loop.add_reader,
+            self._loop.call_soon(self._loop._add_reader,
                                  self._fileno, self._read_ready)
 
         if waiter is not None:
@@ -475,7 +517,7 @@ class _UnixWritePipeTransport(transports._FlowControlMixin,
         return '<%s>' % ' '.join(info)
 
     def get_write_buffer_size(self):
-        return sum(len(data) for data in self._buffer)
+        return len(self._buffer)
 
     def _read_ready(self):
         # Pipe was closed by peer.
@@ -513,39 +555,37 @@ class _UnixWritePipeTransport(transports._FlowControlMixin,
             if n == len(data):
                 return
             elif n > 0:
-                data = data[n:]
-            self._loop.add_writer(self._fileno, self._write_ready)
+                data = memoryview(data)[n:]
+            self._loop._add_writer(self._fileno, self._write_ready)
 
-        self._buffer.append(data)
+        self._buffer += data
         self._maybe_pause_protocol()
 
     def _write_ready(self):
-        data = b''.join(self._buffer)
-        assert data, 'Data should not be empty'
+        assert self._buffer, 'Data should not be empty'
 
-        self._buffer.clear()
         try:
-            n = os.write(self._fileno, data)
+            n = os.write(self._fileno, self._buffer)
         except (BlockingIOError, InterruptedError):
-            self._buffer.append(data)
+            pass
         except Exception as exc:
+            self._buffer.clear()
             self._conn_lost += 1
             # Remove writer here, _fatal_error() doesn't it
             # because _buffer is empty.
-            self._loop.remove_writer(self._fileno)
+            self._loop._remove_writer(self._fileno)
             self._fatal_error(exc, 'Fatal write error on pipe transport')
         else:
-            if n == len(data):
-                self._loop.remove_writer(self._fileno)
+            if n == len(self._buffer):
+                self._buffer.clear()
+                self._loop._remove_writer(self._fileno)
                 self._maybe_resume_protocol()  # May append to buffer.
-                if not self._buffer and self._closing:
-                    self._loop.remove_reader(self._fileno)
+                if self._closing:
+                    self._loop._remove_reader(self._fileno)
                     self._call_connection_lost(None)
                 return
             elif n > 0:
-                data = data[n:]
-
-            self._buffer.append(data)  # Try again later.
+                del self._buffer[:n]
 
     def can_write_eof(self):
         return True
@@ -556,9 +596,15 @@ class _UnixWritePipeTransport(transports._FlowControlMixin,
         assert self._pipe
         self._closing = True
         if not self._buffer:
-            self._loop.remove_reader(self._fileno)
+            self._loop._remove_reader(self._fileno)
             self._loop.call_soon(self._call_connection_lost, None)
 
+    def set_protocol(self, protocol):
+        self._protocol = protocol
+
+    def get_protocol(self):
+        return self._protocol
+
     def is_closing(self):
         return self._closing
 
@@ -596,9 +642,9 @@ class _UnixWritePipeTransport(transports._FlowControlMixin,
     def _close(self, exc=None):
         self._closing = True
         if self._buffer:
-            self._loop.remove_writer(self._fileno)
+            self._loop._remove_writer(self._fileno)
         self._buffer.clear()
-        self._loop.remove_reader(self._fileno)
+        self._loop._remove_reader(self._fileno)
         self._loop.call_soon(self._call_connection_lost, exc)
 
     def _call_connection_lost(self, exc):
@@ -726,6 +772,7 @@ class BaseChildWatcher(AbstractChildWatcher):
 
     def __init__(self):
         self._loop = None
+        self._callbacks = {}
 
     def close(self):
         self.attach_loop(None)
@@ -739,6 +786,12 @@ class BaseChildWatcher(AbstractChildWatcher):
     def attach_loop(self, loop):
         assert loop is None or isinstance(loop, events.AbstractEventLoop)
 
+        if self._loop is not None and loop is None and self._callbacks:
+            warnings.warn(
+                'A loop is being detached '
+                'from a child watcher with pending handlers',
+                RuntimeWarning)
+
         if self._loop is not None:
             self._loop.remove_signal_handler(signal.SIGCHLD)
 
@@ -787,10 +840,6 @@ class SafeChildWatcher(BaseChildWatcher):
     big number of children (O(n) each time SIGCHLD is raised)
     """
 
-    def __init__(self):
-        super().__init__()
-        self._callbacks = {}
-
     def close(self):
         self._callbacks.clear()
         super().close()
@@ -802,6 +851,11 @@ class SafeChildWatcher(BaseChildWatcher):
         pass
 
     def add_child_handler(self, pid, callback, *args):
+        if self._loop is None:
+            raise RuntimeError(
+                "Cannot add child handler, "
+                "the child watcher does not have a loop attached")
+
         self._callbacks[pid] = (callback, args)
 
         # Prevent a race condition in case the child is already terminated.
@@ -866,7 +920,6 @@ class FastChildWatcher(BaseChildWatcher):
     """
     def __init__(self):
         super().__init__()
-        self._callbacks = {}
         self._lock = threading.Lock()
         self._zombies = {}
         self._forks = 0
@@ -898,6 +951,12 @@ class FastChildWatcher(BaseChildWatcher):
 
     def add_child_handler(self, pid, callback, *args):
         assert self._forks, "Must use the context manager"
+
+        if self._loop is None:
+            raise RuntimeError(
+                "Cannot add child handler, "
+                "the child watcher does not have a loop attached")
+
         with self._lock:
             try:
                 returncode = self._zombies.pop(pid)
index 5244b8d..76cf8de 100644 (file)
@@ -8,6 +8,7 @@ set the first day of the week (0=Monday, 6=Sunday)."""
 import sys
 import datetime
 import locale as _locale
+from itertools import repeat
 
 __all__ = ["IllegalMonthError", "IllegalWeekdayError", "setfirstweekday",
            "firstweekday", "isleap", "leapdays", "weekday", "monthrange",
@@ -174,22 +175,20 @@ class Calendar(object):
         Like itermonthdates(), but will yield (day number, weekday number)
         tuples. For days outside the specified month the day number is 0.
         """
-        for date in self.itermonthdates(year, month):
-            if date.month != month:
-                yield (0, date.weekday())
-            else:
-                yield (date.day, date.weekday())
+        for i, d in enumerate(self.itermonthdays(year, month), self.firstweekday):
+            yield d, i % 7
 
     def itermonthdays(self, year, month):
         """
         Like itermonthdates(), but will yield day numbers. For days outside
         the specified month the day number is 0.
         """
-        for date in self.itermonthdates(year, month):
-            if date.month != month:
-                yield 0
-            else:
-                yield date.day
+        day1, ndays = monthrange(year, month)
+        days_before = (day1 - self.firstweekday) % 7
+        yield from repeat(0, days_before)
+        yield from range(1, ndays + 1)
+        days_after = (self.firstweekday - day1 - ndays) % 7
+        yield from repeat(0, days_after)
 
     def monthdatescalendar(self, year, month):
         """
@@ -313,7 +312,7 @@ class TextCalendar(Calendar):
         """
         Print a month's calendar.
         """
-        print(self.formatmonth(theyear, themonth, w, l), end=' ')
+        print(self.formatmonth(theyear, themonth, w, l), end='')
 
     def formatmonth(self, theyear, themonth, w=0, l=0):
         """
index ebe8ee7..bea811d 100644 (file)
@@ -189,6 +189,7 @@ class OrderedDict(dict):
         link = self.__map[key]
         link_prev = link.prev
         link_next = link.next
+        soft_link = link_next.prev
         link_prev.next = link_next
         link_next.prev = link_prev
         root = self.__root
@@ -196,12 +197,14 @@ class OrderedDict(dict):
             last = root.prev
             link.prev = last
             link.next = root
-            last.next = root.prev = link
+            root.prev = soft_link
+            last.next = link
         else:
             first = root.next
             link.prev = root
             link.next = first
-            root.next = first.prev = link
+            first.prev = soft_link
+            root.next = link
 
     def __sizeof__(self):
         sizeof = _sys.getsizeof
index 0cc0c1d..2d4c523 100644 (file)
@@ -66,13 +66,13 @@ def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
     optimize:  optimization level or -1 for level of the interpreter
     workers:   maximum number of parallel workers
     """
+    if workers is not None and workers < 0:
+        raise ValueError('workers must be greater or equal to 0')
+
     files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
                       ddir=ddir)
     success = 1
     if workers is not None and workers != 1 and ProcessPoolExecutor is not None:
-        if workers < 0:
-            raise ValueError('workers must be greater or equal to 0')
-
         workers = workers or None
         with ProcessPoolExecutor(max_workers=workers) as executor:
             results = executor.map(partial(compile_file,
index 590edba..8f1d714 100644 (file)
@@ -63,7 +63,7 @@ import traceback
 # interpreter to exit when there are still idle processes in a
 # ProcessPoolExecutor's process pool (i.e. shutdown() was not called). However,
 # allowing workers to die with the interpreter has two undesirable properties:
-#   - The workers would still be running during interpretor shutdown,
+#   - The workers would still be running during interpreter shutdown,
 #     meaning that they would fail in unpredictable ways.
 #   - The workers could be killed while evaluating a work item, which could
 #     be bad if the callable being evaluated has external side-effects e.g.
index 3ae442d..9c3aec9 100644 (file)
@@ -16,7 +16,7 @@ import os
 # to exit when there are still idle threads in a ThreadPoolExecutor's thread
 # pool (i.e. shutdown() was not called). However, allowing workers to die with
 # the interpreter has two undesirable properties:
-#   - The workers would still be running during interpretor shutdown,
+#   - The workers would still be running during interpreter shutdown,
 #     meaning that they would fail in unpredictable ways.
 #   - The workers could be killed while evaluating a work item, which could
 #     be bad if the callable being evaluated has external side-effects e.g.
index 3a9fb56..af5aca1 100644 (file)
@@ -1102,10 +1102,10 @@ class RawConfigParser(MutableMapping):
                         # raised at the end of the file and will contain a
                         # list of all bogus lines
                         e = self._handle_error(e, fpname, lineno, line)
+        self._join_multiline_values()
         # if any parsing errors occurred, raise an exception
         if e:
             raise e
-        self._join_multiline_values()
 
     def _join_multiline_values(self):
         defaults = self.default_section, self._defaults
index 5377987..d44edd6 100644 (file)
@@ -82,6 +82,9 @@ class _GeneratorContextManager(ContextDecorator):
                 # raised inside the "with" statement from being suppressed.
                 return exc is not value
             except RuntimeError as exc:
+                # Don't re-raise the passed in exception. (issue27112)
+                if exc is value:
+                    return False
                 # Likewise, avoid suppressing if a StopIteration exception
                 # was passed to throw() and later wrapped into a RuntimeError
                 # (see PEP 479).
index dc7052e..c158e67 100644 (file)
@@ -135,10 +135,11 @@ def framework_find(fn, executable_path=None, env=None):
         Python.framework
         Python.framework/Versions/Current
     """
+    error = None
     try:
         return dyld_find(fn, executable_path=executable_path, env=env)
     except ValueError as e:
-        pass
+        error = e
     fmwk_index = fn.rfind('.framework')
     if fmwk_index == -1:
         fmwk_index = len(fn)
@@ -147,7 +148,7 @@ def framework_find(fn, executable_path=None, env=None):
     try:
         return dyld_find(fn, executable_path=executable_path, env=env)
     except ValueError:
-        raise e
+        raise error
 
 def test_dyld_find():
     env = {}
index 3824f7c..8eac58f 100644 (file)
@@ -1,3 +1,4 @@
+import functools
 import unittest
 from ctypes import *
 from ctypes.test import need_symbol
@@ -240,6 +241,40 @@ class SampleCallbacksTestCase(unittest.TestCase):
         self.assertEqual(result,
                          callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
 
+    def test_callback_large_struct(self):
+        class Check: pass
+
+        class X(Structure):
+            _fields_ = [
+                ('first', c_ulong),
+                ('second', c_ulong),
+                ('third', c_ulong),
+            ]
+
+        def callback(check, s):
+            check.first = s.first
+            check.second = s.second
+            check.third = s.third
+
+        check = Check()
+        s = X()
+        s.first = 0xdeadbeef
+        s.second = 0xcafebabe
+        s.third = 0x0bad1dea
+
+        CALLBACK = CFUNCTYPE(None, X)
+        dll = CDLL(_ctypes_test.__file__)
+        func = dll._testfunc_cbk_large_struct
+        func.argtypes = (X, CALLBACK)
+        func.restype = None
+        # the function just calls the callback with the passed structure
+        func(s, CALLBACK(functools.partial(callback, check)))
+        self.assertEqual(check.first, s.first)
+        self.assertEqual(check.second, s.second)
+        self.assertEqual(check.third, s.third)
+        self.assertEqual(check.first, 0xdeadbeef)
+        self.assertEqual(check.second, 0xcafebabe)
+        self.assertEqual(check.third, 0x0bad1dea)
 
 ################################################################
 
index e6bc19d..94b0b89 100644 (file)
@@ -1,5 +1,5 @@
 import unittest
-import os
+import os.path
 import sys
 import test.support
 from ctypes import *
@@ -64,28 +64,10 @@ class Test_OpenGL_libs(unittest.TestCase):
             self.skipTest('lib_gle not available')
         self.gle.gleGetJoinStyle
 
-# On platforms where the default shared library suffix is '.so',
-# at least some libraries can be loaded as attributes of the cdll
-# object, since ctypes now tries loading the lib again
-# with '.so' appended of the first try fails.
-#
-# Won't work for libc, unfortunately.  OTOH, it isn't
-# needed for libc since this is already mapped into the current
-# process (?)
-#
-# On MAC OSX, it won't work either, because dlopen() needs a full path,
-# and the default suffix is either none or '.dylib'.
-@unittest.skip('test disabled')
-@unittest.skipUnless(os.name=="posix" and sys.platform != "darwin",
-                     'test not suitable for this platform')
-class LoadLibs(unittest.TestCase):
-    def test_libm(self):
-        import math
-        libm = cdll.libm
-        sqrt = libm.sqrt
-        sqrt.argtypes = (c_double,)
-        sqrt.restype = c_double
-        self.assertEqual(sqrt(2), math.sqrt(2))
+    def test_shell_injection(self):
+        result = find_library('; echo Hello shell > ' + test.support.TESTFN)
+        self.assertFalse(os.path.lexists(test.support.TESTFN))
+        self.assertIsNone(result)
 
 if __name__ == "__main__":
     unittest.main()
index 29c5a19..7ab38f1 100644 (file)
@@ -120,5 +120,13 @@ class Test(unittest.TestCase):
         with self.assertRaises(ValueError):
             (c_int * 1).from_buffer_copy(a, 16 * sizeof(c_int))
 
+    def test_abstract(self):
+        self.assertRaises(TypeError, Array.from_buffer, bytearray(10))
+        self.assertRaises(TypeError, Structure.from_buffer, bytearray(10))
+        self.assertRaises(TypeError, Union.from_buffer, bytearray(10))
+        self.assertRaises(TypeError, Array.from_buffer_copy, b"123")
+        self.assertRaises(TypeError, Structure.from_buffer_copy, b"123")
+        self.assertRaises(TypeError, Union.from_buffer_copy, b"123")
+
 if __name__ == '__main__':
     unittest.main()
index 2afca26..ba4f563 100644 (file)
@@ -76,7 +76,7 @@ class NumberTestCase(unittest.TestCase):
             self.assertEqual(t(v).value, truth(v))
 
     def test_typeerror(self):
-        # Only numbers are allowed in the contructor,
+        # Only numbers are allowed in the constructor,
         # otherwise TypeError is raised
         for t in signed_types + unsigned_types + float_types:
             self.assertRaises(TypeError, t, "")
index 84d456c..c4a651c 100644 (file)
@@ -106,7 +106,7 @@ class StructureTestCase(unittest.TestCase):
         self.assertEqual(alignment(XX), alignment(X))
         self.assertEqual(sizeof(XX), calcsize("3s 3s 0s"))
 
-    def test_emtpy(self):
+    def test_empty(self):
         # I had problems with these
         #
         # Although these are pathological cases: Empty Structures!
@@ -227,10 +227,10 @@ class StructureTestCase(unittest.TestCase):
 
     def test_conflicting_initializers(self):
         class POINT(Structure):
-            _fields_ = [("x", c_int), ("y", c_int)]
+            _fields_ = [("phi", c_float), ("rho", c_float)]
         # conflicting positional and keyword args
-        self.assertRaises(TypeError, POINT, 2, 3, x=4)
-        self.assertRaises(TypeError, POINT, 2, 3, y=4)
+        self.assertRaisesRegex(TypeError, "phi", POINT, 2, 3, phi=4)
+        self.assertRaisesRegex(TypeError, "rho", POINT, 2, 3, rho=4)
 
         # too many initializers
         self.assertRaises(TypeError, POINT, 2, 3, 4)
index 8ff4aff..7684eab 100644 (file)
@@ -1,6 +1,7 @@
-import sys, os
-import contextlib
+import os
+import shutil
 import subprocess
+import sys
 
 # find_library(name) returns the pathname of a library, or None.
 if os.name == "nt":
@@ -94,28 +95,46 @@ elif os.name == "posix":
     import re, tempfile
 
     def _findLib_gcc(name):
-        expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
-        fdout, ccout = tempfile.mkstemp()
-        os.close(fdout)
-        cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; elif type cc >/dev/null 2>&1; then CC=cc;else exit 10; fi;' \
-              'LANG=C LC_ALL=C $CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name
+        # Run GCC's linker with the -t (aka --trace) option and examine the
+        # library name it prints out. The GCC command will fail because we
+        # haven't supplied a proper program with main(), but that does not
+        # matter.
+        expr = os.fsencode(r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name))
+
+        c_compiler = shutil.which('gcc')
+        if not c_compiler:
+            c_compiler = shutil.which('cc')
+        if not c_compiler:
+            # No C compiler available, give up
+            return None
+
+        temp = tempfile.NamedTemporaryFile()
         try:
-            f = os.popen(cmd)
+            args = [c_compiler, '-Wl,-t', '-o', temp.name, '-l' + name]
+
+            env = dict(os.environ)
+            env['LC_ALL'] = 'C'
+            env['LANG'] = 'C'
             try:
-                trace = f.read()
-            finally:
-                rv = f.close()
+                proc = subprocess.Popen(args,
+                                        stdout=subprocess.PIPE,
+                                        stderr=subprocess.STDOUT,
+                                        env=env)
+            except OSError:  # E.g. bad executable
+                return None
+            with proc:
+                trace = proc.stdout.read()
         finally:
             try:
-                os.unlink(ccout)
+                temp.close()
             except FileNotFoundError:
+                # Raised if the file was already removed, which is the normal
+                # behaviour of GCC if linking fails
                 pass
-        if rv == 10:
-            raise OSError('gcc or cc command not found')
         res = re.search(expr, trace)
         if not res:
             return None
-        return res.group(0)
+        return os.fsdecode(res.group(0))
 
 
     if sys.platform == "sunos5":
@@ -123,55 +142,75 @@ elif os.name == "posix":
         def _get_soname(f):
             if not f:
                 return None
-            cmd = "/usr/ccs/bin/dump -Lpv 2>/dev/null " + f
-            with contextlib.closing(os.popen(cmd)) as f:
-                data = f.read()
-            res = re.search(r'\[.*\]\sSONAME\s+([^\s]+)', data)
+
+            try:
+                proc = subprocess.Popen(("/usr/ccs/bin/dump", "-Lpv", f),
+                                        stdout=subprocess.PIPE,
+                                        stderr=subprocess.DEVNULL)
+            except OSError:  # E.g. command not found
+                return None
+            with proc:
+                data = proc.stdout.read()
+            res = re.search(br'\[.*\]\sSONAME\s+([^\s]+)', data)
             if not res:
                 return None
-            return res.group(1)
+            return os.fsdecode(res.group(1))
     else:
         def _get_soname(f):
             # assuming GNU binutils / ELF
             if not f:
                 return None
-            cmd = 'if ! type objdump >/dev/null 2>&1; then exit 10; fi;' \
-                  "objdump -p -j .dynamic 2>/dev/null " + f
-            f = os.popen(cmd)
+            objdump = shutil.which('objdump')
+            if not objdump:
+                # objdump is not available, give up
+                return None
+
             try:
-                dump = f.read()
-            finally:
-                rv = f.close()
-            if rv == 10:
-                raise OSError('objdump command not found')
-            res = re.search(r'\sSONAME\s+([^\s]+)', dump)
+                proc = subprocess.Popen((objdump, '-p', '-j', '.dynamic', f),
+                                        stdout=subprocess.PIPE,
+                                        stderr=subprocess.DEVNULL)
+            except OSError:  # E.g. bad executable
+                return None
+            with proc:
+                dump = proc.stdout.read()
+            res = re.search(br'\sSONAME\s+([^\s]+)', dump)
             if not res:
                 return None
-            return res.group(1)
+            return os.fsdecode(res.group(1))
 
     if sys.platform.startswith(("freebsd", "openbsd", "dragonfly")):
 
         def _num_version(libname):
             # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ]
-            parts = libname.split(".")
+            parts = libname.split(b".")
             nums = []
             try:
                 while parts:
                     nums.insert(0, int(parts.pop()))
             except ValueError:
                 pass
-            return nums or [ sys.maxsize ]
+            return nums or [sys.maxsize]
 
         def find_library(name):
             ename = re.escape(name)
             expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename)
-            with contextlib.closing(os.popen('/sbin/ldconfig -r 2>/dev/null')) as f:
-                data = f.read()
+            expr = os.fsencode(expr)
+
+            try:
+                proc = subprocess.Popen(('/sbin/ldconfig', '-r'),
+                                        stdout=subprocess.PIPE,
+                                        stderr=subprocess.DEVNULL)
+            except OSError:  # E.g. command not found
+                data = b''
+            else:
+                with proc:
+                    data = proc.stdout.read()
+
             res = re.findall(expr, data)
             if not res:
                 return _get_soname(_findLib_gcc(name))
             res.sort(key=_num_version)
-            return res[-1]
+            return os.fsdecode(res[-1])
 
     elif sys.platform == "sunos5":
 
@@ -179,17 +218,27 @@ elif os.name == "posix":
             if not os.path.exists('/usr/bin/crle'):
                 return None
 
+            env = dict(os.environ)
+            env['LC_ALL'] = 'C'
+
             if is64:
-                cmd = 'env LC_ALL=C /usr/bin/crle -64 2>/dev/null'
+                args = ('/usr/bin/crle', '-64')
             else:
-                cmd = 'env LC_ALL=C /usr/bin/crle 2>/dev/null'
+                args = ('/usr/bin/crle',)
 
             paths = None
-            with contextlib.closing(os.popen(cmd)) as f:
-                for line in f.readlines():
+            try:
+                proc = subprocess.Popen(args,
+                                        stdout=subprocess.PIPE,
+                                        stderr=subprocess.DEVNULL,
+                                        env=env)
+            except OSError:  # E.g. bad executable
+                return None
+            with proc:
+                for line in proc.stdout:
                     line = line.strip()
-                    if line.startswith('Default Library Path (ELF):'):
-                        paths = line.split()[4]
+                    if line.startswith(b'Default Library Path (ELF):'):
+                        paths = os.fsdecode(line).split()[4]
 
             if not paths:
                 return None
index 800fd8b..5b243be 100644 (file)
@@ -53,19 +53,19 @@ def _ctoi(c):
 
 def isalnum(c): return isalpha(c) or isdigit(c)
 def isalpha(c): return isupper(c) or islower(c)
-def isascii(c): return _ctoi(c) <= 127          # ?
-def isblank(c): return _ctoi(c) in (8,32)
-def iscntrl(c): return _ctoi(c) <= 31
-def isdigit(c): return _ctoi(c) >= 48 and _ctoi(c) <= 57
-def isgraph(c): return _ctoi(c) >= 33 and _ctoi(c) <= 126
-def islower(c): return _ctoi(c) >= 97 and _ctoi(c) <= 122
-def isprint(c): return _ctoi(c) >= 32 and _ctoi(c) <= 126
-def ispunct(c): return _ctoi(c) != 32 and not isalnum(c)
+def isascii(c): return 0 <= _ctoi(c) <= 127          # ?
+def isblank(c): return _ctoi(c) in (9, 32)
+def iscntrl(c): return 0 <= _ctoi(c) <= 31 or _ctoi(c) == 127
+def isdigit(c): return 48 <= _ctoi(c) <= 57
+def isgraph(c): return 33 <= _ctoi(c) <= 126
+def islower(c): return 97 <= _ctoi(c) <= 122
+def isprint(c): return 32 <= _ctoi(c) <= 126
+def ispunct(c): return isgraph(c) and not isalnum(c)
 def isspace(c): return _ctoi(c) in (9, 10, 11, 12, 13, 32)
-def isupper(c): return _ctoi(c) >= 65 and _ctoi(c) <= 90
+def isupper(c): return 65 <= _ctoi(c) <= 90
 def isxdigit(c): return isdigit(c) or \
-    (_ctoi(c) >= 65 and _ctoi(c) <= 70) or (_ctoi(c) >= 97 and _ctoi(c) <= 102)
-def isctrl(c): return _ctoi(c) < 32
+    (65 <= _ctoi(c) <= 70) or (97 <= _ctoi(c) <= 102)
+def isctrl(c): return 0 <= _ctoi(c) < 32
 def ismeta(c): return _ctoi(c) > 127
 
 def ascii(c):
index 2b4b4cb..2079953 100644 (file)
@@ -43,16 +43,20 @@ class Textbox:
     def __init__(self, win, insert_mode=False):
         self.win = win
         self.insert_mode = insert_mode
-        (self.maxy, self.maxx) = win.getmaxyx()
-        self.maxy = self.maxy - 1
-        self.maxx = self.maxx - 1
+        self._update_max_yx()
         self.stripspaces = 1
         self.lastcmd = None
         win.keypad(1)
 
+    def _update_max_yx(self):
+        maxy, maxx = self.win.getmaxyx()
+        self.maxy = maxy - 1
+        self.maxx = maxx - 1
+
     def _end_of_line(self, y):
         """Go to the location of the first blank on the given line,
         returning the index of the last non-blank character."""
+        self._update_max_yx()
         last = self.maxx
         while True:
             if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP:
@@ -64,8 +68,10 @@ class Textbox:
         return last
 
     def _insert_printable_char(self, ch):
+        self._update_max_yx()
         (y, x) = self.win.getyx()
-        if y < self.maxy or x < self.maxx:
+        backyx = None
+        while y < self.maxy or x < self.maxx:
             if self.insert_mode:
                 oldch = self.win.inch()
             # The try-catch ignores the error we trigger from some curses
@@ -75,14 +81,20 @@ class Textbox:
                 self.win.addch(ch)
             except curses.error:
                 pass
-            if self.insert_mode:
-                (backy, backx) = self.win.getyx()
-                if curses.ascii.isprint(oldch):
-                    self._insert_printable_char(oldch)
-                    self.win.move(backy, backx)
+            if not self.insert_mode or not curses.ascii.isprint(oldch):
+                break
+            ch = oldch
+            (y, x) = self.win.getyx()
+            # Remember where to put the cursor back since we are in insert_mode
+            if backyx is None:
+                backyx = y, x
+
+        if backyx is not None:
+            self.win.move(*backyx)
 
     def do_command(self, ch):
         "Process a single editing command."
+        self._update_max_yx()
         (y, x) = self.win.getyx()
         self.lastcmd = ch
         if curses.ascii.isprint(ch):
@@ -148,6 +160,7 @@ class Textbox:
     def gather(self):
         "Collect and return the contents of the window."
         result = ""
+        self._update_max_yx()
         for y in range(self.maxy+1):
             self.win.move(y, 0)
             stop = self._end_of_line(y)
index 2f94218..a2178c7 100644 (file)
@@ -706,7 +706,7 @@ class date:
 
     @classmethod
     def fromordinal(cls, n):
-        """Contruct a date from a proleptic Gregorian ordinal.
+        """Construct a date from a proleptic Gregorian ordinal.
 
         January 1 of year 1 is day 1.  Only the year, month and day are
         non-zero in the result.
index 7777a7c..e6d6505 100644 (file)
@@ -47,6 +47,7 @@ class _Database(collections.MutableMapping):
 
     def __init__(self, filebasename, mode, flag='c'):
         self._mode = mode
+        self._readonly = (flag == 'r')
 
         # The directory file is a text file.  Each line looks like
         #    "%r, (%d, %d)\n" % (key, pos, siz)
@@ -91,8 +92,9 @@ class _Database(collections.MutableMapping):
         try:
             f = _io.open(self._dirfile, 'r', encoding="Latin-1")
         except OSError:
-            pass
+            self._modified = not self._readonly
         else:
+            self._modified = False
             with f:
                 for line in f:
                     line = line.rstrip()
@@ -107,7 +109,7 @@ class _Database(collections.MutableMapping):
         # CAUTION:  It's vital that _commit() succeed, and _commit() can
         # be called from __del__().  Therefore we must never reference a
         # global in this routine.
-        if self._index is None:
+        if self._index is None or not self._modified:
             return  # nothing to do
 
         try:
@@ -187,6 +189,7 @@ class _Database(collections.MutableMapping):
         elif not isinstance(val, (bytes, bytearray)):
             raise TypeError("values must be bytes or strings")
         self._verify_open()
+        self._modified = True
         if key not in self._index:
             self._addkey(key, self._addval(val))
         else:
@@ -215,6 +218,7 @@ class _Database(collections.MutableMapping):
         if isinstance(key, str):
             key = key.encode('utf-8')
         self._verify_open()
+        self._modified = True
         # The blocks used by the associated value are lost.
         del self._index[key]
         # XXX It's unclear why we do a _commit() here (the code always
index d0ba7d6..b120273 100644 (file)
@@ -86,11 +86,9 @@ def _get_vc_env(plat_spec):
 
     try:
         out = subprocess.check_output(
-            '"{}" {} && set'.format(vcvarsall, plat_spec),
-            shell=True,
+            'cmd /u /c "{}" {} && set'.format(vcvarsall, plat_spec),
             stderr=subprocess.STDOUT,
-            universal_newlines=True,
-        )
+        ).decode('utf-16le', errors='replace')
     except subprocess.CalledProcessError as exc:
         log.error(exc.output)
         raise DistutilsPlatformError("Error executing {}"
index f03a4e3..7c278ef 100644 (file)
@@ -166,6 +166,7 @@ class build_ext(Command):
             self.include_dirs.append(plat_py_include)
 
         self.ensure_string_list('libraries')
+        self.ensure_string_list('link_objects')
 
         # Life is easier if we're not forever checking for None, so
         # simplify these options to empty lists if unset
index 0afcbf2..1fd574a 100644 (file)
@@ -91,7 +91,7 @@ class upload(PyPIRCCommand):
         data = {
             # action
             ':action': 'file_upload',
-            'protcol_version': '1',
+            'protocol_version': '1',
 
             # identify release
             'name': meta.get_name(),
index 2229954..253c2e2 100644 (file)
Binary files a/Lib/distutils/command/wininst-14.0-amd64.exe and b/Lib/distutils/command/wininst-14.0-amd64.exe differ
index 0dac110..46f5f35 100644 (file)
Binary files a/Lib/distutils/command/wininst-14.0.exe and b/Lib/distutils/command/wininst-14.0.exe differ
index f0c7373..bf8d8dd 100644 (file)
@@ -21,7 +21,7 @@ password:%s
 class PyPIRCCommand(Command):
     """Base command that knows how to handle the .pypirc file
     """
-    DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi'
+    DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'
     DEFAULT_REALM = 'pypi'
     repository = None
     realm = None
index db3f7a9..6522e69 100644 (file)
@@ -6,6 +6,7 @@ and building lists of files.
 
 import os, re
 import fnmatch
+import functools
 from distutils.util import convert_path
 from distutils.errors import DistutilsTemplateError, DistutilsInternalError
 from distutils import log
@@ -242,35 +243,28 @@ class FileList:
 # ----------------------------------------------------------------------
 # Utility functions
 
+def _find_all_simple(path):
+    """
+    Find all files under 'path'
+    """
+    results = (
+        os.path.join(base, file)
+        for base, dirs, files in os.walk(path, followlinks=True)
+        for file in files
+    )
+    return filter(os.path.isfile, results)
+
+
 def findall(dir=os.curdir):
-    """Find all files under 'dir' and return the list of full filenames
-    (relative to 'dir').
     """
-    from stat import ST_MODE, S_ISREG, S_ISDIR, S_ISLNK
-
-    list = []
-    stack = [dir]
-    pop = stack.pop
-    push = stack.append
-
-    while stack:
-        dir = pop()
-        names = os.listdir(dir)
-
-        for name in names:
-            if dir != os.curdir:        # avoid the dreaded "./" syndrome
-                fullname = os.path.join(dir, name)
-            else:
-                fullname = name
-
-            # Avoid excess stat calls -- just one will do, thank you!
-            stat = os.stat(fullname)
-            mode = stat[ST_MODE]
-            if S_ISREG(mode):
-                list.append(fullname)
-            elif S_ISDIR(mode) and not S_ISLNK(mode):
-                push(fullname)
-    return list
+    Find all files under 'dir' and return the list of full filenames.
+    Unless dir is '.', return full filenames with dir prepended.
+    """
+    files = _find_all_simple(dir)
+    if dir == os.curdir:
+        make_rel = functools.partial(os.path.relpath, start=dir)
+        files = map(make_rel, files)
+    return list(files)
 
 
 def glob_to_re(pattern):
index 25c14ab..c5962dd 100644 (file)
@@ -3,9 +3,7 @@
 import unittest
 import sys
 import os
-import tempfile
-import shutil
-from test.support import run_unittest
+from test.support import run_unittest, requires_zlib
 
 from distutils.core import Distribution
 from distutils.command.bdist_rpm import bdist_rpm
@@ -48,6 +46,7 @@ class BuildRpmTestCase(support.TempdirManager,
     # spurious sdtout/stderr output under Mac OS X
     @unittest.skipUnless(sys.platform.startswith('linux'),
                          'spurious sdtout/stderr output under Mac OS X')
+    @requires_zlib
     @unittest.skipIf(find_executable('rpm') is None,
                      'the rpm command is not found')
     @unittest.skipIf(find_executable('rpmbuild') is None,
@@ -90,13 +89,14 @@ class BuildRpmTestCase(support.TempdirManager,
     # spurious sdtout/stderr output under Mac OS X
     @unittest.skipUnless(sys.platform.startswith('linux'),
                          'spurious sdtout/stderr output under Mac OS X')
+    @requires_zlib
     # http://bugs.python.org/issue1533164
     @unittest.skipIf(find_executable('rpm') is None,
                      'the rpm command is not found')
     @unittest.skipIf(find_executable('rpmbuild') is None,
                      'the rpmbuild command is not found')
     def test_no_optimize_flag(self):
-        # let's create a package that brakes bdist_rpm
+        # let's create a package that breaks bdist_rpm
         tmp_dir = self.mkdtemp()
         os.environ['HOME'] = tmp_dir   # to confine dir '.rpmdb' creation
         pkg_dir = os.path.join(tmp_dir, 'foo')
index 8f62b1a..f3df564 100644 (file)
@@ -195,6 +195,13 @@ class BuildExtTestCase(TempdirManager,
         cmd.finalize_options()
         self.assertEqual(cmd.rpath, ['one', 'two'])
 
+        # make sure cmd.link_objects is turned into a list
+        # if it's a string
+        cmd = build_ext(dist)
+        cmd.link_objects = 'one two,three'
+        cmd.finalize_options()
+        self.assertEqual(cmd.link_objects, ['one', 'two', 'three'])
+
         # XXX more tests to perform for win32
 
         # make sure define is turned into 2-tuples
@@ -243,7 +250,7 @@ class BuildExtTestCase(TempdirManager,
         self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts)
 
         # second element of each tuple in 'ext_modules'
-        # must be a ary (build info)
+        # must be a dictionary (build info)
         exts = [('foo.bar', '')]
         self.assertRaises(DistutilsSetupError, cmd.check_extensions_list, exts)
 
index 959fa90..3d22868 100644 (file)
@@ -7,6 +7,12 @@ from distutils.command.check import check, HAS_DOCUTILS
 from distutils.tests import support
 from distutils.errors import DistutilsSetupError
 
+try:
+    import pygments
+except ImportError:
+    pygments = None
+
+
 class CheckTestCase(support.LoggingSilencer,
                     support.TempdirManager,
                     unittest.TestCase):
@@ -119,9 +125,15 @@ class CheckTestCase(support.LoggingSilencer,
             pkg_info, dist = self.create_dist(long_description=rest_with_code)
             cmd = check(dist)
             cmd.check_restructuredtext()
-            self.assertEqual(cmd._warnings, 0)
             msgs = cmd._check_rst_data(rest_with_code)
-            self.assertEqual(len(msgs), 0)
+            if pygments is not None:
+                self.assertEqual(len(msgs), 0)
+            else:
+                self.assertEqual(len(msgs), 1)
+                self.assertEqual(
+                    str(msgs[0][1]),
+                    'Cannot analyze code. Pygments package not found.'
+                )
 
     def test_check_all(self):
 
index 4de825a..a384497 100644 (file)
@@ -18,6 +18,7 @@ PYPIRC = """\
 index-servers =
     server1
     server2
+    server3
 
 [server1]
 username:me
@@ -28,6 +29,10 @@ username:meagain
 password: secret
 realm:acme
 repository:http://another.pypi/
+
+[server3]
+username:cbiggles
+password:yh^%#rest-of-my-password
 """
 
 PYPIRC_OLD = """\
@@ -47,14 +52,14 @@ password:xxx
 """
 
 
-class PyPIRCCommandTestCase(support.TempdirManager,
+class BasePyPIRCCommandTestCase(support.TempdirManager,
                             support.LoggingSilencer,
                             support.EnvironGuard,
                             unittest.TestCase):
 
     def setUp(self):
         """Patches the environment."""
-        super(PyPIRCCommandTestCase, self).setUp()
+        super(BasePyPIRCCommandTestCase, self).setUp()
         self.tmp_dir = self.mkdtemp()
         os.environ['HOME'] = self.tmp_dir
         self.rc = os.path.join(self.tmp_dir, '.pypirc')
@@ -73,7 +78,10 @@ class PyPIRCCommandTestCase(support.TempdirManager,
     def tearDown(self):
         """Removes the patch."""
         set_threshold(self.old_threshold)
-        super(PyPIRCCommandTestCase, self).tearDown()
+        super(BasePyPIRCCommandTestCase, self).tearDown()
+
+
+class PyPIRCCommandTestCase(BasePyPIRCCommandTestCase):
 
     def test_server_registration(self):
         # This test makes sure PyPIRCCommand knows how to:
@@ -87,7 +95,7 @@ class PyPIRCCommandTestCase(support.TempdirManager,
 
         config = list(sorted(config.items()))
         waited = [('password', 'secret'), ('realm', 'pypi'),
-                  ('repository', 'https://pypi.python.org/pypi'),
+                  ('repository', 'https://upload.pypi.org/legacy/'),
                   ('server', 'server1'), ('username', 'me')]
         self.assertEqual(config, waited)
 
@@ -96,7 +104,7 @@ class PyPIRCCommandTestCase(support.TempdirManager,
         config = cmd._read_pypirc()
         config = list(sorted(config.items()))
         waited = [('password', 'secret'), ('realm', 'pypi'),
-                  ('repository', 'https://pypi.python.org/pypi'),
+                  ('repository', 'https://upload.pypi.org/legacy/'),
                   ('server', 'server-login'), ('username', 'tarek')]
         self.assertEqual(config, waited)
 
@@ -113,6 +121,20 @@ class PyPIRCCommandTestCase(support.TempdirManager,
         finally:
             f.close()
 
+    def test_config_interpolation(self):
+        # using the % character in .pypirc should not raise an error (#20120)
+        self.write_file(self.rc, PYPIRC)
+        cmd = self._cmd(self.dist)
+        cmd.repository = 'server3'
+        config = cmd._read_pypirc()
+
+        config = list(sorted(config.items()))
+        waited = [('password', 'yh^%#rest-of-my-password'), ('realm', 'pypi'),
+                  ('repository', 'https://upload.pypi.org/legacy/'),
+                  ('server', 'server3'), ('username', 'cbiggles')]
+        self.assertEqual(config, waited)
+
+
 def test_suite():
     return unittest.makeSuite(PyPIRCCommandTestCase)
 
index e82bc3d..391af3c 100644 (file)
@@ -6,7 +6,9 @@ from distutils import debug
 from distutils.log import WARN
 from distutils.errors import DistutilsTemplateError
 from distutils.filelist import glob_to_re, translate_pattern, FileList
+from distutils import filelist
 
+import test.support
 from test.support import captured_stdout, run_unittest
 from distutils.tests import support
 
@@ -292,8 +294,47 @@ class FileListTestCase(support.LoggingSilencer,
         self.assertWarnings()
 
 
+class FindAllTestCase(unittest.TestCase):
+    @test.support.skip_unless_symlink
+    def test_missing_symlink(self):
+        with test.support.temp_cwd():
+            os.symlink('foo', 'bar')
+            self.assertEqual(filelist.findall(), [])
+
+    def test_basic_discovery(self):
+        """
+        When findall is called with no parameters or with
+        '.' as the parameter, the dot should be omitted from
+        the results.
+        """
+        with test.support.temp_cwd():
+            os.mkdir('foo')
+            file1 = os.path.join('foo', 'file1.txt')
+            test.support.create_empty_file(file1)
+            os.mkdir('bar')
+            file2 = os.path.join('bar', 'file2.txt')
+            test.support.create_empty_file(file2)
+            expected = [file2, file1]
+            self.assertEqual(sorted(filelist.findall()), expected)
+
+    def test_non_local_discovery(self):
+        """
+        When findall is called with another path, the full
+        path name should be returned.
+        """
+        with test.support.temp_dir() as temp_dir:
+            file1 = os.path.join(temp_dir, 'file1.txt')
+            test.support.create_empty_file(file1)
+            expected = [file1]
+            self.assertEqual(filelist.findall(temp_dir), expected)
+
+
 def test_suite():
-    return unittest.makeSuite(FileListTestCase)
+    return unittest.TestSuite([
+        unittest.makeSuite(FileListTestCase),
+        unittest.makeSuite(FindAllTestCase),
+    ])
+
 
 if __name__ == "__main__":
     run_unittest(test_suite())
index 5e18c61..77a07ef 100644 (file)
@@ -125,7 +125,7 @@ class msvc9compilerTestCase(support.TempdirManager,
         self.assertRaises(KeyError, Reg.get_value, 'xxx', 'xxx')
 
         # looking for values that should exist on all
-        # windows registeries versions.
+        # windows registry versions.
         path = r'Control Panel\Desktop'
         v = Reg.get_value(path, 'dragfullwindows')
         self.assertIn(v, ('0', '1', '2'))
index c4d911f..4dc2488 100644 (file)
@@ -83,6 +83,24 @@ class msvccompilerTestCase(support.TempdirManager,
         self.assertFalse(os.path.isfile(os.path.join(
             tempdir, os.path.basename(dll))))
 
+    def test_get_vc_env_unicode(self):
+        import distutils._msvccompiler as _msvccompiler
+
+        test_var = 'ṰḖṤṪ┅ṼẨṜ'
+        test_value = '₃⁴₅'
+
+        # Ensure we don't early exit from _get_vc_env
+        old_distutils_use_sdk = os.environ.pop('DISTUTILS_USE_SDK', None)
+        os.environ[test_var] = test_value
+        try:
+            env = _msvccompiler._get_vc_env('x86')
+            self.assertIn(test_var.lower(), env)
+            self.assertEqual(test_value, env[test_var.lower()])
+        finally:
+            os.environ.pop(test_var)
+            if old_distutils_use_sdk:
+                os.environ['DISTUTILS_USE_SDK'] = old_distutils_use_sdk
+
 def test_suite():
     return unittest.makeSuite(msvccompilerTestCase)
 
index 01acf23..e68b0af 100644 (file)
@@ -12,7 +12,7 @@ from distutils.command.register import register
 from distutils.errors import DistutilsSetupError
 from distutils.log import INFO
 
-from distutils.tests.test_config import PyPIRCCommandTestCase
+from distutils.tests.test_config import BasePyPIRCCommandTestCase
 
 try:
     import docutils
@@ -72,7 +72,7 @@ class FakeOpener(object):
             }.get(name.lower(), default)
 
 
-class RegisterTestCase(PyPIRCCommandTestCase):
+class RegisterTestCase(BasePyPIRCCommandTestCase):
 
     def setUp(self):
         super(RegisterTestCase, self).setUp()
index 5a04e0d..5444b81 100644 (file)
@@ -23,7 +23,7 @@ except ImportError:
 
 from distutils.command.sdist import sdist, show_formats
 from distutils.core import Distribution
-from distutils.tests.test_config import PyPIRCCommandTestCase
+from distutils.tests.test_config import BasePyPIRCCommandTestCase
 from distutils.errors import DistutilsOptionError
 from distutils.spawn import find_executable
 from distutils.log import WARN
@@ -52,7 +52,7 @@ somecode%(sep)sdoc.dat
 somecode%(sep)sdoc.txt
 """
 
-class SDistTestCase(PyPIRCCommandTestCase):
+class SDistTestCase(BasePyPIRCCommandTestCase):
 
     def setUp(self):
         # PyPIRCCommandTestCase creates a temp dir already
index 964aac7..2cb2f6c 100644 (file)
@@ -12,7 +12,7 @@ from distutils.core import Distribution
 from distutils.errors import DistutilsError
 from distutils.log import ERROR, INFO
 
-from distutils.tests.test_config import PYPIRC, PyPIRCCommandTestCase
+from distutils.tests.test_config import PYPIRC, BasePyPIRCCommandTestCase
 
 PYPIRC_LONG_PASSWORD = """\
 [distutils]
@@ -66,7 +66,7 @@ class FakeOpen(object):
         return self.code
 
 
-class uploadTestCase(PyPIRCCommandTestCase):
+class uploadTestCase(BasePyPIRCCommandTestCase):
 
     def setUp(self):
         super(uploadTestCase, self).setUp()
@@ -93,7 +93,7 @@ class uploadTestCase(PyPIRCCommandTestCase):
         cmd.finalize_options()
         for attr, waited in (('username', 'me'), ('password', 'secret'),
                              ('realm', 'pypi'),
-                             ('repository', 'https://pypi.python.org/pypi')):
+                             ('repository', 'https://upload.pypi.org/legacy/')):
             self.assertEqual(getattr(cmd, attr), waited)
 
     def test_saved_password(self):
@@ -130,13 +130,14 @@ class uploadTestCase(PyPIRCCommandTestCase):
 
         # what did we send ?
         headers = dict(self.last_open.req.headers)
-        self.assertEqual(headers['Content-length'], '2161')
+        self.assertEqual(headers['Content-length'], '2162')
         content_type = headers['Content-type']
         self.assertTrue(content_type.startswith('multipart/form-data'))
         self.assertEqual(self.last_open.req.get_method(), 'POST')
-        expected_url = 'https://pypi.python.org/pypi'
+        expected_url = 'https://upload.pypi.org/legacy/'
         self.assertEqual(self.last_open.req.get_full_url(), expected_url)
         self.assertTrue(b'xxx' in self.last_open.req.data)
+        self.assertIn(b'protocol_version', self.last_open.req.data)
 
         # The PyPI response body was echoed
         results = self.get_logs(INFO)
index 92d14df..3f321c2 100644 (file)
@@ -227,6 +227,8 @@ class UnixCCompiler(CCompiler):
         if sys.platform[:6] == "darwin":
             # MacOSX's linker doesn't understand the -R flag at all
             return "-L" + dir
+        elif sys.platform[:7] == "freebsd":
+            return "-Wl,-rpath=" + dir
         elif sys.platform[:5] == "hp-ux":
             if self._is_gcc(compiler):
                 return ["-Wl,+s", "-L" + dir]
index 2226e13..5df9511 100644 (file)
@@ -439,7 +439,7 @@ class UnstructuredTokenList(TokenList):
                 if folded.append_if_fits(part):
                     continue
             if part.has_fws:
-                part.fold(folded)
+                part._fold(folded)
                 continue
             # It can't be split...we just have to put it on its own line.
             folded.append(tstr)
@@ -460,7 +460,7 @@ class UnstructuredTokenList(TokenList):
                     last_ew = len(res)
                 else:
                     tl = get_unstructured(''.join(res[last_ew:] + [spart]))
-                    res.append(tl.as_encoded_word())
+                    res.append(tl.as_encoded_word(charset))
         return ''.join(res)
 
 
index f3bbac1..17f0818 100644 (file)
@@ -103,7 +103,7 @@ def decode(string):
     """Decode a raw base64 string, returning a bytes object.
 
     This function does not parse a full MIME header value encoded with
-    base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
+    base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high
     level email.header class for that functionality.
     """
     if not string:
index d363652..b98ce27 100644 (file)
@@ -126,12 +126,13 @@ def _finalize_set(msg, disposition, filename, cid, params):
             msg.set_param(key, value)
 
 
-# XXX: This is a cleaned-up version of base64mime.body_encode.  It would
-# be nice to drop both this and quoprimime.body_encode in favor of
-# enhanced binascii routines that accepted a max_line_length parameter.
+# XXX: This is a cleaned-up version of base64mime.body_encode (including a bug
+# fix in the calculation of unencoded_bytes_per_line).  It would be nice to
+# drop both this and quoprimime.body_encode in favor of enhanced binascii
+# routines that accepted a max_line_length parameter.
 def _encode_base64(data, max_line_length):
     encoded_lines = []
-    unencoded_bytes_per_line = max_line_length * 3 // 4
+    unencoded_bytes_per_line = max_line_length // 4 * 3
     for i in range(0, len(data), unencoded_bytes_per_line):
         thisline = data[i:i+unencoded_bytes_per_line]
         encoded_lines.append(binascii.b2a_base64(thisline).decode('ascii'))
index e2e3e96..0b312e5 100644 (file)
@@ -27,6 +27,7 @@ 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)')
@@ -51,8 +52,9 @@ class BufferedSubFile(object):
     simple abstraction -- it parses until EOF closes the current message.
     """
     def __init__(self):
-        # Chunks of the last partial line pushed into this object.
-        self._partial = []
+        # Text stream of the last partial line pushed into this object.
+        # See issue 22233 for why this is a text stream and not a list.
+        self._partial = StringIO(newline='')
         # A deque of full, pushed lines
         self._lines = deque()
         # The stack of false-EOF checking predicates.
@@ -68,8 +70,10 @@ class BufferedSubFile(object):
 
     def close(self):
         # Don't forget any trailing partial line.
-        self.pushlines(''.join(self._partial).splitlines(True))
-        self._partial = []
+        self._partial.seek(0)
+        self.pushlines(self._partial.readlines())
+        self._partial.seek(0)
+        self._partial.truncate()
         self._closed = True
 
     def readline(self):
@@ -97,26 +101,23 @@ class BufferedSubFile(object):
 
     def push(self, data):
         """Push some new data into this object."""
-        # Crack into lines, but preserve the linesep characters on the end of each
-        parts = data.splitlines(True)
-
-        if not parts or not parts[0].endswith(('\n', '\r')):
-            # No new complete lines, so just accumulate partials
-            self._partial += parts
+        self._partial.write(data)
+        if '\n' not in data and '\r' not in data:
+            # No new complete lines, wait for more.
             return
 
-        if self._partial:
-            # If there are previous leftovers, complete them now
-            self._partial.append(parts[0])
-            parts[0:1] = ''.join(self._partial).splitlines(True)
-            del self._partial[:]
+        # Crack into lines, preserving the linesep characters.
+        self._partial.seek(0)
+        parts = self._partial.readlines()
+        self._partial.seek(0)
+        self._partial.truncate()
 
         # If the last element of the list does not end in a newline, then treat
         # it as a partial line.  We only check for '\n' here because a line
         # ending with '\r' might be a line that was split in the middle of a
         # '\r\n' sequence (see bugs 1555570 and 1721862).
         if not parts[-1].endswith('\n'):
-            self._partial = [parts.pop()]
+            self._partial.write(parts.pop())
         self.pushlines(parts)
 
     def pushlines(self, lines):
@@ -145,7 +146,7 @@ class FeedParser:
 
         """
         self.policy = policy
-        self._factory_kwds = lambda: {'policy': self.policy}
+        self._old_style_factory = False
         if _factory is None:
             # What this should be:
             #self._factory = policy.default_message_factory
@@ -160,7 +161,7 @@ class FeedParser:
                 _factory(policy=self.policy)
             except TypeError:
                 # Assume this is an old-style factory
-                self._factory_kwds = lambda: {}
+                self._old_style_factory = True
         self._input = BufferedSubFile()
         self._msgstack = []
         self._parse = self._parsegen().__next__
@@ -197,7 +198,10 @@ class FeedParser:
         return root
 
     def _new_message(self):
-        msg = self._factory(**self._factory_kwds())
+        if self._old_style_factory:
+            msg = self._factory()
+        else:
+            msg = self._factory(policy=self.policy)
         if self._cur and self._cur.get_content_type() == 'multipart/digest':
             msg.set_default_type('message/rfc822')
         if self._msgstack:
index 11ff16d..256278d 100644 (file)
@@ -18,6 +18,7 @@ from email.utils import _has_surrogates
 UNDERSCORE = '_'
 NL = '\n'  # XXX: no longer used by the code below.
 
+NLCRE = re.compile(r'\r\n|\r|\n')
 fcre = re.compile(r'^From ', re.MULTILINE)
 
 
@@ -97,7 +98,7 @@ class Generator:
         self._NL = policy.linesep
         self._encoded_NL = self._encode(self._NL)
         self._EMPTY = ''
-        self._encoded_EMTPY = self._encode('')
+        self._encoded_EMPTY = self._encode(self._EMPTY)
         # Because we use clone (below) when we recursively process message
         # subparts, and because clone uses the computed policy (not None),
         # submessages will automatically get set to the computed policy when
@@ -137,10 +138,6 @@ class Generator:
     # it has already transformed the input; but, since this whole thing is a
     # hack anyway this seems good enough.
 
-    # Similarly, we have _XXX and _encoded_XXX attributes that are used on
-    # source and buffer data, respectively.
-    _encoded_EMPTY = ''
-
     def _new_buffer(self):
         # BytesGenerator overrides this to return BytesIO.
         return StringIO()
@@ -153,14 +150,17 @@ class Generator:
         # We have to transform the line endings.
         if not lines:
             return
-        lines = lines.splitlines(True)
+        lines = NLCRE.split(lines)
         for line in lines[:-1]:
-            self.write(line.rstrip('\r\n'))
-            self.write(self._NL)
-        laststripped = lines[-1].rstrip('\r\n')
-        self.write(laststripped)
-        if len(lines[-1]) != len(laststripped):
+            self.write(line)
             self.write(self._NL)
+        if lines[-1]:
+            self.write(lines[-1])
+        # XXX logic tells me this else should be needed, but the tests fail
+        # with it and pass without it.  (NLCRE.split ends with a blank element
+        # if and only if there was a trailing newline.)
+        #else:
+        #    self.write(self._NL)
 
     def _write(self, msg):
         # We can't write the headers yet because of the following scenario:
@@ -402,10 +402,6 @@ class BytesGenerator(Generator):
     The outfp object must accept bytes in its write method.
     """
 
-    # Bytes versions of this constant for use in manipulating data from
-    # the BytesIO buffer.
-    _encoded_EMPTY = b''
-
     def write(self, s):
         self._fp.write(s.encode('ascii', 'surrogateescape'))
 
index aefaf57..4b04283 100644 (file)
@@ -1022,7 +1022,7 @@ class MIMEPart(Message):
         maintype, subtype = self.get_content_type().split('/')
         if maintype != 'multipart' or subtype == 'alternative':
             return
-        parts = self.get_payload()
+        parts = self.get_payload().copy()
         if maintype == 'multipart' and subtype == 'related':
             # For related, we treat everything but the root as an attachment.
             # The root may be indicated by 'start'; if there's no start or we
@@ -1043,7 +1043,7 @@ class MIMEPart(Message):
             yield from parts
             return
         # Otherwise we more or less invert the remaining logic in get_body.
-        # This only really works in edge cases (ex: non-text relateds or
+        # This only really works in edge cases (ex: non-text related or
         # alternatives) if the sending agent sets content-disposition.
         seen = []   # Only skip the first example of each candidate type.
         for part in parts:
index 479928e..da03086 100644 (file)
@@ -35,10 +35,8 @@ class MIMEText(MIMENonMultipart):
                 _charset = 'us-ascii'
             except UnicodeEncodeError:
                 _charset = 'utf-8'
-        if isinstance(_charset, Charset):
-            _charset = str(_charset)
 
         MIMENonMultipart.__init__(self, 'text', _subtype,
-                                  **{'charset': _charset})
+                                  **{'charset': str(_charset)})
 
         self.set_payload(_text, _charset)
index 6ac64a5..35d0e69 100644 (file)
@@ -2,6 +2,7 @@
 code that adds all the email6 features.
 """
 
+import re
 from email._policybase import Policy, Compat32, compat32, _extend_docstrings
 from email.utils import _has_surrogates
 from email.headerregistry import HeaderRegistry as HeaderRegistry
@@ -18,6 +19,8 @@ __all__ = [
     'HTTP',
     ]
 
+linesep_splitter = re.compile(r'\n|\r')
+
 @_extend_docstrings
 class EmailPolicy(Policy):
 
@@ -135,6 +138,8 @@ class EmailPolicy(Policy):
         if hasattr(value, 'name') and value.name.lower() == name.lower():
             return (name, value)
         if isinstance(value, str) and len(value.splitlines())>1:
+            # XXX this error message isn't quite right when we use splitlines
+            # (see issue 22233), but I'm not sure what should happen here.
             raise ValueError("Header values may not contain linefeed "
                              "or carriage return characters")
         return (name, self.header_factory(name, value))
@@ -150,7 +155,9 @@ class EmailPolicy(Policy):
         """
         if hasattr(value, 'name'):
             return value
-        return self.header_factory(name, ''.join(value.splitlines()))
+        # We can't use splitlines here because it splits on more than \r and \n.
+        value = ''.join(linesep_splitter.split(value))
+        return self.header_factory(name, value)
 
     def fold(self, name, value):
         """+
index c1fe2b4..c543eb5 100644 (file)
@@ -292,7 +292,7 @@ def header_decode(s):
     """Decode a string encoded with RFC 2045 MIME header `Q' encoding.
 
     This function does not parse a full MIME header value encoded with
-    quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use
+    quoted-printable (like =?iso-8859-1?q?Hello_World?=) -- please use
     the high level email.header class for that functionality.
     """
     s = s.replace('_', ' ')
index 08aedf9..25c5567 100644 (file)
@@ -8,9 +8,9 @@ import tempfile
 __all__ = ["version", "bootstrap"]
 
 
-_SETUPTOOLS_VERSION = "20.10.1"
+_SETUPTOOLS_VERSION = "28.8.0"
 
-_PIP_VERSION = "8.1.1"
+_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)
diff --git a/Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl b/Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl
deleted file mode 100644 (file)
index 8632eb7..0000000
Binary files a/Lib/ensurepip/_bundled/pip-8.1.1-py2.py3-none-any.whl and /dev/null differ
diff --git a/Lib/ensurepip/_bundled/pip-9.0.1-py2.py3-none-any.whl b/Lib/ensurepip/_bundled/pip-9.0.1-py2.py3-none-any.whl
new file mode 100644 (file)
index 0000000..4b8ecc6
Binary files /dev/null and b/Lib/ensurepip/_bundled/pip-9.0.1-py2.py3-none-any.whl differ
similarity index 51%
rename from Lib/ensurepip/_bundled/setuptools-20.10.1-py2.py3-none-any.whl
rename to Lib/ensurepip/_bundled/setuptools-28.8.0-py2.py3-none-any.whl
index 9d1319a..502e3cb 100644 (file)
Binary files a/Lib/ensurepip/_bundled/setuptools-20.10.1-py2.py3-none-any.whl and b/Lib/ensurepip/_bundled/setuptools-28.8.0-py2.py3-none-any.whl differ
index 60b0728..9aabab3 100644 (file)
@@ -484,10 +484,14 @@ class Fraction(numbers.Rational):
                     return Fraction(a._numerator ** power,
                                     a._denominator ** power,
                                     _normalize=False)
-                else:
+                elif a._numerator >= 0:
                     return Fraction(a._denominator ** -power,
                                     a._numerator ** -power,
                                     _normalize=False)
+                else:
+                    return Fraction((-a._denominator) ** -power,
+                                    (-a._numerator) ** -power,
+                                    _normalize=False)
             else:
                 # A fractional power will generally produce an
                 # irrational number.
index 214523c..60cf3c4 100644 (file)
@@ -516,14 +516,16 @@ def _lru_cache_wrapper(user_function, maxsize, typed, _CacheInfo):
                     last = root[PREV]
                     link = [last, root, key, result]
                     last[NEXT] = root[PREV] = cache[key] = link
-                    full = (len(cache) >= maxsize)
+                    # Use the __len__() method instead of the len() function
+                    # which could potentially be wrapped in an lru_cache itself.
+                    full = (cache.__len__() >= maxsize)
                 misses += 1
             return result
 
     def cache_info():
         """Report cache statistics"""
         with lock:
-            return _CacheInfo(hits, misses, maxsize, len(cache))
+            return _CacheInfo(hits, misses, maxsize, cache.__len__())
 
     def cache_clear():
         """Clear the cache and cache statistics"""
index 101378f..57d2c74 100644 (file)
@@ -59,55 +59,147 @@ __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
 
 _default_localedir = os.path.join(sys.base_prefix, 'share', 'locale')
 
+# Expression parsing for plural form selection.
+#
+# The gettext library supports a small subset of C syntax.  The only
+# incompatible difference is that integer literals starting with zero are
+# decimal.
+#
+# https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
+# http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y
+
+_token_pattern = re.compile(r"""
+        (?P<WHITESPACES>[ \t]+)                    | # spaces and horizontal tabs
+        (?P<NUMBER>[0-9]+\b)                       | # decimal integer
+        (?P<NAME>n\b)                              | # only n is allowed
+        (?P<PARENTHESIS>[()])                      |
+        (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >,
+                                                     # <=, >=, ==, !=, &&, ||,
+                                                     # ? :
+                                                     # unary and bitwise ops
+                                                     # not allowed
+        (?P<INVALID>\w+|.)                           # invalid token
+    """, re.VERBOSE|re.DOTALL)
+
+def _tokenize(plural):
+    for mo in re.finditer(_token_pattern, plural):
+        kind = mo.lastgroup
+        if kind == 'WHITESPACES':
+            continue
+        value = mo.group(kind)
+        if kind == 'INVALID':
+            raise ValueError('invalid token in plural form: %s' % value)
+        yield value
+    yield ''
+
+def _error(value):
+    if value:
+        return ValueError('unexpected token in plural form: %s' % value)
+    else:
+        return ValueError('unexpected end of plural form')
+
+_binary_ops = (
+    ('||',),
+    ('&&',),
+    ('==', '!='),
+    ('<', '>', '<=', '>='),
+    ('+', '-'),
+    ('*', '/', '%'),
+)
+_binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops}
+_c2py_ops = {'||': 'or', '&&': 'and', '/': '//'}
+
+def _parse(tokens, priority=-1):
+    result = ''
+    nexttok = next(tokens)
+    while nexttok == '!':
+        result += 'not '
+        nexttok = next(tokens)
+
+    if nexttok == '(':
+        sub, nexttok = _parse(tokens)
+        result = '%s(%s)' % (result, sub)
+        if nexttok != ')':
+            raise ValueError('unbalanced parenthesis in plural form')
+    elif nexttok == 'n':
+        result = '%s%s' % (result, nexttok)
+    else:
+        try:
+            value = int(nexttok, 10)
+        except ValueError:
+            raise _error(nexttok) from None
+        result = '%s%d' % (result, value)
+    nexttok = next(tokens)
+
+    j = 100
+    while nexttok in _binary_ops:
+        i = _binary_ops[nexttok]
+        if i < priority:
+            break
+        # Break chained comparisons
+        if i in (3, 4) and j in (3, 4):  # '==', '!=', '<', '>', '<=', '>='
+            result = '(%s)' % result
+        # Replace some C operators by their Python equivalents
+        op = _c2py_ops.get(nexttok, nexttok)
+        right, nexttok = _parse(tokens, i + 1)
+        result = '%s %s %s' % (result, op, right)
+        j = i
+    if j == priority == 4:  # '<', '>', '<=', '>='
+        result = '(%s)' % result
+
+    if nexttok == '?' and priority <= 0:
+        if_true, nexttok = _parse(tokens, 0)
+        if nexttok != ':':
+            raise _error(nexttok)
+        if_false, nexttok = _parse(tokens)
+        result = '%s if %s else %s' % (if_true, result, if_false)
+        if priority == 0:
+            result = '(%s)' % result
+
+    return result, nexttok
+
+def _as_int(n):
+    try:
+        i = round(n)
+    except TypeError:
+        raise TypeError('Plural value must be an integer, got %s' %
+                        (n.__class__.__name__,)) from None
+    return n
 
 def c2py(plural):
     """Gets a C expression as used in PO files for plural forms and returns a
-    Python lambda function that implements an equivalent expression.
+    Python function that implements an equivalent expression.
     """
-    # Security check, allow only the "n" identifier
-    import token, tokenize
-    tokens = tokenize.generate_tokens(io.StringIO(plural).readline)
-    try:
-        danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
-    except tokenize.TokenError:
-        raise ValueError('plural forms expression error, maybe unbalanced parenthesis')
-    else:
-        if danger:
-            raise ValueError('plural forms expression could be dangerous')
-
-    # Replace some C operators by their Python equivalents
-    plural = plural.replace('&&', ' and ')
-    plural = plural.replace('||', ' or ')
-
-    expr = re.compile(r'\!([^=])')
-    plural = expr.sub(' not \\1', plural)
-
-    # Regular expression and replacement function used to transform
-    # "a?b:c" to "b if a else c".
-    expr = re.compile(r'(.*?)\?(.*?):(.*)')
-    def repl(x):
-        return "(%s if %s else %s)" % (x.group(2), x.group(1),
-                                       expr.sub(repl, x.group(3)))
-
-    # Code to transform the plural expression, taking care of parentheses
-    stack = ['']
-    for c in plural:
-        if c == '(':
-            stack.append('')
-        elif c == ')':
-            if len(stack) == 1:
-                # Actually, we never reach this code, because unbalanced
-                # parentheses get caught in the security check at the
-                # beginning.
-                raise ValueError('unbalanced parenthesis in plural form')
-            s = expr.sub(repl, stack.pop())
-            stack[-1] += '(%s)' % s
-        else:
-            stack[-1] += c
-    plural = expr.sub(repl, stack.pop())
-
-    return eval('lambda n: int(%s)' % plural)
 
+    if len(plural) > 1000:
+        raise ValueError('plural form expression is too long')
+    try:
+        result, nexttok = _parse(_tokenize(plural))
+        if nexttok:
+            raise _error(nexttok)
+
+        depth = 0
+        for c in result:
+            if c == '(':
+                depth += 1
+                if depth > 20:
+                    # Python compiler limit is about 90.
+                    # The most complex example has 2.
+                    raise ValueError('plural form expression is too complex')
+            elif c == ')':
+                depth -= 1
+
+        ns = {'_as_int': _as_int}
+        exec('''if True:
+            def func(n):
+                if not isinstance(n, int):
+                    n = _as_int(n)
+                return int(%s)
+            ''' % result, ns)
+        return ns['func']
+    except RecursionError:
+        # Recursion error can be raised in _parse() or exec().
+        raise ValueError('plural form expression is too complex')
 
 
 def _expand_lang(loc):
index 350313e..352c101 100644 (file)
@@ -136,7 +136,7 @@ _MAXHEADERS = 100
 #
 # VCHAR defined in http://tools.ietf.org/html/rfc5234#appendix-B.1
 
-# the patterns for both name and value are more leniant than RFC
+# the patterns for both name and value are more lenient than RFC
 # definitions to allow for backwards compatibility
 _is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
 _is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
@@ -935,7 +935,8 @@ class HTTPConnection:
         if message_body is not None:
             self.send(message_body)
 
-    def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
+    def putrequest(self, method, url, skip_host=False,
+                   skip_accept_encoding=False):
         """Send a request to the server.
 
         `method' specifies an HTTP request method, e.g. 'GET'.
index 265ccf9..6d4572a 100644 (file)
@@ -120,7 +120,7 @@ def time2netscape(t=None):
         dt = datetime.datetime.utcnow()
     else:
         dt = datetime.datetime.utcfromtimestamp(t)
-    return "%s %02d-%s-%04d %02d:%02d:%02d GMT" % (
+    return "%s, %02d-%s-%04d %02d:%02d:%02d GMT" % (
         DAYS[dt.weekday()], dt.day, MONTHS[dt.month-1],
         dt.year, dt.hour, dt.minute, dt.second)
 
@@ -833,7 +833,7 @@ class CookiePolicy:
     May also modify cookies, though this is probably a bad idea.
 
     The subclass DefaultCookiePolicy defines the standard rules for Netscape
-    and RFC 2965 cookies -- override that if you want a customised policy.
+    and RFC 2965 cookies -- override that if you want a customized policy.
 
     """
     def set_ok(self, cookie, request):
index ab25ff1..e19a279 100644 (file)
@@ -69,6 +69,8 @@ menudefs = [
  ('shell', [
    ('_View Last Restart', '<<view-restart>>'),
    ('_Restart Shell', '<<restart-shell>>'),
+   None,
+   ('_Interrupt Execution', '<<interrupt-execution>>'),
    ]),
  ('debug', [
    ('_Go to File/Line', '<<goto-file-line>>'),
index 8e68a76..9eec175 100644 (file)
@@ -9,7 +9,7 @@ HIDE_VIRTUAL_EVENT_NAME = "<<calltipwindow-hide>>"
 HIDE_SEQUENCES = ("<Key-Escape>", "<FocusOut>")
 CHECKHIDE_VIRTUAL_EVENT_NAME = "<<calltipwindow-checkhide>>"
 CHECKHIDE_SEQUENCES = ("<KeyRelease>", "<ButtonRelease>")
-CHECKHIDE_TIME = 100 # miliseconds
+CHECKHIDE_TIME = 100 # milliseconds
 
 MARK_RIGHT = "calltipwindowregion_right"
 
index 00d5005..72905c1 100644 (file)
@@ -1,6 +1,36 @@
+What's New in IDLE 3.5.3?
+=========================
+*Release date: 2017-01-01?*
+
+- 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.
+
+- 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 #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 #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 #27452: add line counter and crc to IDLE configHandler test dump.
+
+- 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.
+
+
 What's New in IDLE 3.5.2?
 =========================
-*Release date: 2016-06-30?*
+*Release date: 2016-06-26*
 
 - Issue #5124: Paste with text selected now replaces the selection on X11.
   This matches how paste works on Windows, Mac, most modern Linux apps,
@@ -184,7 +214,7 @@ What's New in IDLE 3.5.0?
   Changes are written to HOME/.idlerc/config-extensions.cfg.
   Original patch by Tal Einat.
 
-- Issue #16233: A module browser (File : Class Browser, Alt+C) requires a
+- Issue #16233: A module browser (File : Class Browser, Alt+C) requires an
   editor window with a filename.  When Class Browser is requested otherwise,
   from a shell, output window, or 'Untitled' editor, Idle no longer displays
   an error box.  It now pops up an  Open Module box (Alt+M). If a valid name
@@ -285,7 +315,7 @@ What's New in IDLE 3.3.0?
 - Issue # 12510: Attempt to get certain tool tips no longer crashes IDLE.
   Erroneous tool tips have been corrected. Default added for callables.
 
-- Issue10365: File open dialog now works instead of crashing even when
+- Issue #10365: File open dialog now works instead of crashing even when
   parent window is closed while dialog is open.
 
 - Issue 14876: use user-selected font for highlight configuration.
@@ -321,18 +351,18 @@ What's New in IDLE 3.2.1?
 - Issue #1028: Ctrl-space binding to show completions was causing IDLE to exit.
   Tk < 8.5 was sending invalid Unicode null; replaced with valid null.
 
-- <Home> toggle failing on Tk 8.5, causing IDLE exits and strange selection
-  behavior. Issue 4676.  Improve selection extension behaviour.
+- Issue #4676: <Home> toggle failing on Tk 8.5, causing IDLE exits and strange selection
+  behavior. Improve selection extension behaviour.
 
-- <Home> toggle non-functional when NumLock set on Windows.  Issue 3851.
+- Issue #3851: <Home> toggle non-functional when NumLock set on Windows.
 
 
 What's New in IDLE 3.1b1?
 =========================
 *Release date: 06-May-09*
 
-- Use of 'filter' in keybindingDialog.py was causing custom key assignment to
-  fail.  Patch 5707 amaury.forgeotdarc.
+- Issue #5707: Use of 'filter' in keybindingDialog.py was causing custom key assignment to
+  fail.  Patch by Amaury Forgeot d'Arc.
 
 - Issue #4815: Offer conversion to UTF-8 if source files have
   no encoding declaration and are not encoded in UTF-8.
@@ -347,664 +377,6 @@ What's New in IDLE 3.1b1?
 - Issue #2665: On Windows, an IDLE installation upgraded from an old version
   would not start if a custom theme was defined.
 
-
-What's New in IDLE 2.7? (UNRELEASED, but merged into 3.1 releases above.)
-=======================
-*Release date: XX-XXX-2010*
-
-- idle.py modified and simplified to better support developing experimental
-  versions of IDLE which are not installed in the standard location.
-
-- OutputWindow/PyShell right click menu "Go to file/line" wasn't working with
-  file paths containing spaces.  Bug 5559.
-
-- Windows: Version string for the .chm help file changed, file not being
-  accessed  Patch 5783 Guilherme Polo
-
-- Allow multiple IDLE GUI/subprocess pairs to exist simultaneously. Thanks to
-  David Scherer for suggesting the use of an ephemeral port for the GUI.
-  Patch 1529142 Weeble.
-
-- Remove port spec from run.py and fix bug where subprocess fails to
-  extract port from command line when warnings are present.
-
-- Tk 8.5 Text widget requires 'wordprocessor' tabstyle attr to handle
-  mixed space/tab properly. Issue 5129, patch by Guilherme Polo.
-
-- Issue #3549: On MacOS the preferences menu was not present
-
-- IDLE would print a "Unhandled server exception!" message when internal
-  debugging is enabled.
-
-- Issue #4455: IDLE failed to display the windows list when two windows have
-  the same title.
-
-- Issue #4383: When IDLE cannot make the connection to its subprocess, it would
-  fail to properly display the error message.
-
-- help() was not paging to the shell.  Issue1650.
-
-- CodeContext was not importing.
-
-- Corrected two 3.0 compatibility errors reported by Mark Summerfield:
-  http://mail.python.org/pipermail/python-3000/2007-December/011491.html
-
-- Shell was not colorizing due to bug introduced at r57998,  Bug 1586.
-
-- Issue #1585: IDLE uses non-existent xrange() function.
-
-- Windows EOL sequence not converted correctly, encoding error.
-  Caused file save to fail. Bug 1130.
-
-- IDLE converted to Python 3000 syntax.
-
-- Strings became Unicode.
-
-- CallTips module now uses the inspect module to produce the argspec.
-
-- IDLE modules now use absolute import instead of implied relative import.
-
-- atexit call replaces sys.exitfunc.  The functionality of delete-exitfunc flag
-  in config-main.cfg remains unchanged: if set, registered exit functions will
-  be cleared before IDLE exits.
-
-
-What's New in IDLE 2.6
-======================
-*Release date: 01-Oct-2008*, merged into 3.0 releases detailed above (3.0rc2)
-
-- Issue #2665: On Windows, an IDLE installation upgraded from an old version
-  would not start if a custom theme was defined.
-
-- Home / Control-A toggles between left margin and end of leading white
-  space.  issue1196903, patch by Jeff Shute.
-
-- Improved AutoCompleteWindow logic.  issue2062, patch by Tal Einat.
-
-- Autocompletion of filenames now support alternate separators, e.g. the
-  '/' char on Windows.  issue2061 Patch by Tal Einat.
-
-- Configured selection highlighting colors were ignored; updating highlighting
-  in the config dialog would cause non-Python files to be colored as if they
-  were Python source; improve use of ColorDelagator.  Patch 1334. Tal Einat.
-
-- ScriptBinding event handlers weren't returning 'break'. Patch 2050, Tal Einat
-
-- There was an error on exit if no sys.exitfunc was defined. Issue 1647.
-
-- Could not open files in .idlerc directory if latter was hidden on Windows.
-  Issue 1743, Issue 1862.
-
-- Configure Dialog: improved layout for keybinding.  Patch 1457 Tal Einat.
-
-- tabpage.py updated: tabbedPages.py now supports multiple dynamic rows
-  of tabs.  Patch 1612746 Tal Einat.
-
-- Add confirmation dialog before printing.  Patch 1717170 Tal Einat.
-
-- Show paste position if > 80 col.  Patch 1659326 Tal Einat.
-
-- Update cursor color without restarting.  Patch 1725576 Tal Einat.
-
-- Allow keyboard interrupt only when user code is executing in subprocess.
-  Patch 1225 Tal Einat (reworked from IDLE-Spoon).
-
-- configDialog cleanup. Patch 1730217 Tal Einat.
-
-- textView cleanup. Patch 1718043 Tal Einat.
-
-- Clean up EditorWindow close.
-
-- Patch 1693258: Fix for duplicate "preferences" menu-OS X. Backport of r56204.
-
-- OSX: Avoid crash for those versions of Tcl/Tk which don't have a console
-
-- Bug in idlelib.MultiCall: Options dialog was crashing IDLE if there was an
-  option in config-extensions w/o a value. Patch #1672481, Tal Einat
-
-- Corrected some bugs in AutoComplete.  Also, Page Up/Down in ACW implemented;
-  mouse and cursor selection in ACWindow implemented; double Tab inserts
-  current selection and closes ACW (similar to double-click and Return); scroll
-  wheel now works in ACW.  Added AutoComplete instructions to IDLE Help.
-
-- AutoCompleteWindow moved below input line, will move above if there
-  isn't enough space.  Patch 1621265 Tal Einat
-
-- Calltips now 'handle' tuples in the argument list (display '<tuple>' :)
-  Suggested solution by Christos Georgiou, Bug 791968.
-
-- Add 'raw' support to configHandler. Patch 1650174 Tal Einat.
-
-- Avoid hang when encountering a duplicate in a completion list. Bug 1571112.
-
-- Patch #1362975: Rework CodeContext indentation algorithm to
-  avoid hard-coding pixel widths.
-
-- Bug #813342: Start the IDLE subprocess with -Qnew if the parent
-  is started with that option.
-
-- Honor the "Cancel" action in the save dialog (Debian bug #299092)
-
-- Some syntax errors were being caught by tokenize during the tabnanny
-  check, resulting in obscure error messages.  Do the syntax check
-  first.  Bug 1562716, 1562719
-
-- IDLE's version number takes a big jump to match the version number of
-  the Python release of which it's a part.
-
-
-What's New in IDLE 1.2?
-=======================
-*Release date: 19-SEP-2006*
-
-- File menu hotkeys: there were three 'p' assignments.  Reassign the
-  'Save Copy As' and 'Print' hotkeys to 'y' and 't'.  Change the
-  Shell hotkey from 's' to 'l'.
-
-- IDLE honors new quit() and exit() commands from site.py Quitter() object.
-  Patch 1540892, Jim Jewett
-
-- The 'with' statement is now a Code Context block opener.
-  Patch 1540851, Jim Jewett
-
-- Retrieval of previous shell command was not always preserving indentation
-  (since 1.2a1) Patch 1528468 Tal Einat.
-
-- Changing tokenize (39046) to detect dedent broke tabnanny check (since 1.2a1)
-
-- ToggleTab dialog was setting indent to 8 even if cancelled (since 1.2a1).
-
-- When used w/o subprocess, all exceptions were preceded by an error
-  message claiming they were IDLE internal errors (since 1.2a1).
-
-- Bug #1525817: Don't truncate short lines in IDLE's tool tips.
-
-- Bug #1517990: IDLE keybindings on MacOS X now work correctly
-
-- Bug #1517996: IDLE now longer shows the default Tk menu when a
-  path browser, class browser or debugger is the frontmost window on MacOS X
-
-- EditorWindow.test() was failing.  Bug 1417598
-
-- EditorWindow failed when used stand-alone if sys.ps1 not set.
-  Bug 1010370 Dave Florek
-
-- Tooltips failed on new-syle class __init__ args.  Bug 1027566 Loren Guthrie
-
-- Avoid occasional failure to detect closing paren properly.
-  Patch 1407280 Tal Einat
-
-- Rebinding Tab key was inserting 'tab' instead of 'Tab'.  Bug 1179168.
-
-- Colorizer now handles #<builtin> correctly, also unicode strings and
-  'as' keyword in comment directly following import command. Closes 1325071.
-  Patch 1479219 Tal Einat
-
-- Patch #1162825: Support non-ASCII characters in IDLE window titles.
-
-- Source file f.flush() after writing; trying to avoid lossage if user
-  kills GUI.
-
-- Options / Keys / Advanced dialog made functional.  Also, allow binding
-  of 'movement' keys.
-
-- 'syntax' patch adds improved calltips and a new class attribute listbox.
-  MultiCall module allows binding multiple actions to an event.
-  Patch 906702 Noam Raphael
-
-- Better indentation after first line of string continuation.
-  IDLEfork Patch 681992, Noam Raphael
-
-- Fixed CodeContext alignment problem, following suggestion from Tal Einat.
-
-- Increased performance in CodeContext extension  Patch 936169 Noam Raphael
-
-- Mac line endings were incorrect when pasting code from some browsers
-  when using X11 and the Fink distribution.  Python Bug 1263656.
-
-- <Enter> when cursor is on a previous command retrieves that command.  Instead
-  of replacing the input line, the previous command is now appended to the
-  input line. Indentation is preserved, and undo is enabled.
-  Patch 1196917  Jeff Shute
-
-- Clarify "tab/space" Error Dialog and "Tab Width" Dialog associated with
-  the Untabify command.
-
-- Corrected "tab/space" Error Dialog to show correct menu for Untabify.
-  Patch 1196980 Jeff Shute
-
-- New files are colorized by default, and colorizing is removed when
-  saving as non-Python files. Patch 1196895 Jeff Shute
-  Closes Python Bugs 775012 and 800432, partial fix IDLEfork 763524
-
-- Improve subprocess link error notification.
-
-- run.py: use Queue's blocking feature instead of sleeping in the main
-  loop.  Patch # 1190163 Michiel de Hoon
-
-- Add config-main option to make the 'history' feature non-cyclic.
-  Default remains cyclic.  Python Patch 914546 Noam Raphael.
-
-- Removed ability to configure tabs indent from Options dialog.  This 'feature'
-  has never worked and no one has complained.  It is still possible to set a
-  default tabs (v. spaces) indent 'manually' via config-main.def (or to turn on
-  tabs for the current EditorWindow via the Format menu) but IDLE will
-  encourage indentation via spaces.
-
-- Enable setting the indentation width using the Options dialog.
-  Bug # 783877
-
-- Add keybindings for del-word-left and del-word-right.
-
-- Discourage using an indent width other than 8 when using tabs to indent
-  Python code.
-
-- Restore use of EditorWindow.set_indentation_params(), was dead code since
-  Autoindent was merged into EditorWindow.  This allows IDLE to conform to the
-  indentation width of a loaded file.  (But it still will not switch to tabs
-  even if the file uses tabs.)  Any change in indent width is local to that
-  window.
-
-- Add Tabnanny check before Run/F5, not just when Checking module.
-
-- If an extension can't be loaded, print warning and skip it instead of
-  erroring out.
-
-- Improve error handling when .idlerc can't be created (warn and exit).
-
-- The GUI was hanging if the shell window was closed while a raw_input()
-  was pending.  Restored the quit() of the readline() mainloop().
-  http://mail.python.org/pipermail/idle-dev/2004-December/002307.html
-
-- The remote procedure call module rpc.py can now access data attributes of
-  remote registered objects.  Changes to these attributes are local, however.
-
-
-What's New in IDLE 1.1?
-=======================
-*Release date: 30-NOV-2004*
-
-- On OpenBSD, terminating IDLE with ctrl-c from the command line caused a
-  stuck subprocess MainThread because only the SocketThread was exiting.
-
-- Saving a Keyset w/o making changes (by using the "Save as New Custom Key Set"
-  button) caused IDLE to fail on restart (no new keyset was created in
-  config-keys.cfg).  Also true for Theme/highlights.  Python Bug 1064535.
-
-- A change to the linecache.py API caused IDLE to exit when an exception was
-  raised while running without the subprocess (-n switch).  Python Bug 1063840.
-
-- When paragraph reformat width was made configurable, a bug was
-  introduced that caused reformatting of comment blocks to ignore how
-  far the block was indented, effectively adding the indentation width
-  to the reformat width.  This has been repaired, and the reformat
-  width is again a bound on the total width of reformatted lines.
-
-- Improve keyboard focus binding, especially in Windows menu.  Improve
-  window raising, especially in the Windows menu and in the debugger.
-  IDLEfork 763524.
-
-- If user passes a non-existent filename on the commandline, just
-  open a new file, don't raise a dialog.  IDLEfork 854928.
-
-- EditorWindow.py was not finding the .chm help file on Windows.  Typo
-  at Rev 1.54.  Python Bug 990954
-
-- checking sys.platform for substring 'win' was breaking IDLE docs on Mac
-  (darwin).  Also, Mac Safari browser requires full file:// URIs.  SF 900580.
-
-- Redirect the warning stream to the shell during the ScriptBinding check of
-  user code and format the warning similarly to an exception for both that
-  check and for runtime warnings raised in the subprocess.
-
-- CodeContext hint pane visibility state is now persistent across sessions.
-  The pane no longer appears in the shell window.  Added capability to limit
-  extensions to shell window or editor windows.  Noam Raphael addition
-  to Patch 936169.
-
-- Paragraph reformat width is now a configurable parameter in the
-  Options GUI.
-
-- New Extension: CodeContext.  Provides block structuring hints for code
-  which has scrolled above an edit window. Patch 936169 Noam Raphael.
-
-- If nulls somehow got into the strings in recent-files.lst
-  EditorWindow.update_recent_files_list() was failing.  Python Bug 931336.
-
-- If the normal background is changed via Configure/Highlighting, it will
-  update immediately, thanks to the previously mentioned patch by Nigel Rowe.
-
-- Add a highlight theme for builtin keywords.  Python Patch 805830 Nigel Rowe
-  This also fixed IDLEfork bug [ 693418 ] Normal text background color not
-  refreshed and Python bug [897872 ] Unknown color name on HP-UX
-
-- rpc.py:SocketIO - Large modules were generating large pickles when downloaded
-  to the execution server.  The return of the OK response from the subprocess
-  initialization was interfering and causing the sending socket to be not
-  ready.  Add an IO ready test to fix this.  Moved the polling IO ready test
-  into pollpacket().
-
-- Fix typo in rpc.py, s/b "pickle.PicklingError" not "pickle.UnpicklingError".
-
-- Added a Tk error dialog to run.py inform the user if the subprocess can't
-  connect to the user GUI process.  Added a timeout to the GUI's listening
-  socket.  Added Tk error dialogs to PyShell.py to announce a failure to bind
-  the port or connect to the subprocess.  Clean up error handling during
-  connection initiation phase.  This is an update of Python Patch 778323.
-
-- Print correct exception even if source file changed since shell was
-  restarted.  IDLEfork Patch 869012 Noam Raphael
-
-- Keybindings with the Shift modifier now work correctly.  So do bindings which
-  use the Space key.  Limit unmodified user keybindings to the function keys.
-  Python Bug 775353, IDLEfork Bugs 755647, 761557
-
-- After an exception, run.py was not setting the exception vector. Noam
-  Raphael suggested correcting this so pdb's postmortem pm() would work.
-  IDLEfork Patch 844675
-
-- IDLE now does not fail to save the file anymore if the Tk buffer is not a
-  Unicode string, yet eol_convention is.  Python Bugs 774680, 788378
-
-- IDLE didn't start correctly when Python was installed in "Program Files" on
-  W2K and XP.  Python Bugs 780451, 784183
-
-- config-main.def documentation incorrectly referred to idle- instead of
-  config-  filenames.  SF 782759  Also added note about .idlerc location.
-
-
-What's New in IDLE 1.0?
-=======================
-*Release date: 29-Jul-2003*
-
-- Added a banner to the shell discussing warnings possibly raised by personal
-  firewall software.  Added same comment to README.txt.
-
-- Calltip error when docstring was None  Python Bug 775541
-
-- Updated extend.txt, help.txt, and config-extensions.def to correctly
-  reflect the current status of the configuration system.  Python Bug 768469
-
-- Fixed: Call Tip Trimming May Loop Forever. Python Patch 769142 (Daniels)
-
-- Replaced apply(f, args, kwds) with f(*args, **kwargs) to improve performance
-  Python Patch 768187
-
-- Break or continue statements outside a loop were causing IDLE crash
-  Python Bug 767794
-
-- Convert Unicode strings from readline to IOBinding.encoding.  Also set
-  sys.std{in|out|err}.encoding, for both the local and the subprocess case.
-  SF IDLEfork patch 682347.
-
-- Extend AboutDialog.ViewFile() to support file encodings.  Make the CREDITS
-  file Latin-1.
-
-- Updated the About dialog to reflect re-integration into Python.  Provide
-  buttons to display Python's NEWS, License, and Credits, plus additional
-  buttons for IDLE's README and NEWS.
-
-- TextViewer() now has a third parameter which allows inserting text into the
-  viewer instead of reading from a file.
-
-- (Created the .../Lib/idlelib directory in the Python CVS, which is a clone of
-  IDLEfork modified to install in the Python environment.  The code in the
-  interrupt module has been moved to thread.interrupt_main(). )
-
-- Printing the Shell window was failing if it was not saved first SF 748975
-
-- When using the Search in Files dialog, if the user had a selection
-  highlighted in his Editor window, insert it into the dialog search field.
-
-- The Python Shell entry was disappearing from the Windows menu.
-
-- Update the Windows file list when a file name change occurs
-
-- Change to File / Open Module: always pop up the dialog, using the current
-  selection as the default value.  This is easier to use habitually.
-
-- Avoided a problem with starting the subprocess when 'localhost' doesn't
-  resolve to the user's loopback interface.  SF 747772
-
-- Fixed an issue with highlighted errors never de-colorizing.  SF 747677.  Also
-  improved notification of Tabnanny Token Error.
-
-- File / New will by default save in the directory of the Edit window from
-  which it was initiated.  SF 748973 Guido van Rossum patch.
-
-
-What's New in IDLEfork 0.9b1?
-=============================
-*Release date: 02-Jun-2003*
-
-- The current working directory of the execution environment (and shell
-  following completion of execution) is now that of the module being run.
-
-- Added the delete-exitfunc option to config-main.def.  (This option is not
-  included in the Options dialog.)  Setting this to True (the default) will
-  cause IDLE to not run sys.exitfunc/atexit when the subprocess exits.
-
-- IDLE now preserves the line ending codes when editing a file produced on
-  a different platform. SF 661759,  SF 538584
-
-- Reduced default editor font size to 10 point and increased window height
-  to provide a better initial impression on Windows.
-
-- Options / Fonts/Tabs / Set Base Editor Font: List box was not highlighting
-  the default font when first installed on Windows.  SF 661676
-
-- Added Autosave feature: when user runs code from edit window, if the file
-  has been modified IDLE will silently save it if Autosave is enabled.  The
-  option is set in the Options dialog, and the default is to prompt the
-  user to save the file.   SF 661318 Bruce Sherwood patch.
-
-- Improved the RESTART annotation in the shell window when the user restarts
-  the shell while it is generating output.  Also improved annotation when user
-  repeatedly hammers the Ctrl-F6 restart.
-
-- Allow IDLE to run when not installed and cwd is not the IDLE directory
-  SF Patch 686254 "Run IDLEfork from any directory without set-up" - Raphael
-
-- When a module is run from an EditorWindow: if its directory is not in
-  sys.path, prepend it.  This allows the module to import other modules in
-  the same directory.  Do the same for a script run from the command line.
-
-- Correctly restart the subprocess if it is running user code and the user
-  attempts to run some other module or restarts the shell.  Do the same if
-  the link is broken and it is possible to restart the subprocess and re-
-  connect to the GUI.   SF RFE 661321.
-
-- Improved exception reporting when running commands or scripts from the
-  command line.
-
-- Added a -n command line switch to start IDLE without the subprocess.
-  Removed the Shell menu when running in that mode.  Updated help messages.
-
-- Added a comment to the shell startup header to indicate when IDLE is not
-  using the subprocess.
-
-- Restore the ability to run without the subprocess.  This can be important for
-  some platforms or configurations.  (Running without the subprocess allows the
-  debugger to trace through parts of IDLE itself, which may or may not be
-  desirable, depending on your point of view.  In addition, the traditional
-  reload/import tricks must be use if user source code is changed.)  This is
-  helpful for developing IDLE using IDLE, because one instance can be used to
-  edit the code and a separate instance run to test changes.  (Multiple
-  concurrent IDLE instances with subprocesses is a future feature)
-
-- Improve the error message a user gets when saving a file with non-ASCII
-  characters and no source encoding is specified.  Done by adding a dialog
-  'EncodingMessage', which contains the line to add in a fixed-font entry
-  widget, and which has a button to add that line to the file automatically.
-  Also, add a configuration option 'EditorWindow/encoding', which has three
-  possible values: none, utf-8, and locale. None is the default: IDLE will show
-  this dialog when non-ASCII characters are encountered. utf-8 means that files
-  with non-ASCII characters are saved as utf-8-with-bom. locale means that
-  files are saved in the locale's encoding; the dialog is only displayed if the
-  source contains characters outside the locale's charset.  SF 710733 - Loewis
-
-- Improved I/O response by tweaking the wait parameter in various
-  calls to signal.signal().
-
-- Implemented a threaded subprocess which allows interrupting a pass
-  loop in user code using the 'interrupt' extension.  User code runs
-  in MainThread, while the RPCServer is handled by SockThread.  This is
-  necessary because Windows doesn't support signals.
-
-- Implemented the 'interrupt' extension module, which allows a subthread
-  to raise a KeyboardInterrupt in the main thread.
-
-- Attempting to save the shell raised an error related to saving
-  breakpoints, which are not implemented in the shell
-
-- Provide a correct message when 'exit' or 'quit' are entered at the
-  IDLE command prompt  SF 695861
-
-- Eliminate extra blank line in shell output caused by not flushing
-  stdout when user code ends with an unterminated print. SF 695861
-
-- Moved responsibility for exception formatting (i.e. pruning IDLE internal
-  calls) out of rpc.py into the client and server.
-
-- Exit IDLE cleanly even when doing subprocess I/O
-
-- Handle subprocess interrupt with an RPC message.
-
-- Restart the subprocess if it terminates itself. (VPython programs do that)
-
-- Support subclassing of exceptions, including in the shell, by moving the
-  exception formatting to the subprocess.
-
-
-What's New in IDLEfork 0.9 Alpha 2?
-===================================
-*Release date: 27-Jan-2003*
-
-- Updated INSTALL.txt to claify use of the python2 rpm.
-
-- Improved formatting in IDLE Help.
-
-- Run menu: Replace "Run Script" with "Run Module".
-
-- Code encountering an unhandled exception under the debugger now shows
-  the correct traceback, with IDLE internal levels pruned out.
-
-- If an exception occurs entirely in IDLE, don't prune the IDLE internal
-  modules from the traceback displayed.
-
-- Class Browser and Path Browser now use Alt-Key-2 for vertical zoom.
-
-- IDLE icons will now install correctly even when setup.py is run from the
-  build directory
-
-- Class Browser now compatible with Python2.3 version of pyclbr.py
-
-- Left cursor move in presence of selected text now moves from left end
-  of the selection.
-
-- Add Meta keybindings to "IDLE Classic Windows" to handle reversed
-  Alt/Meta on some Linux distros.
-
-- Change default: IDLE now starts with Python Shell.
-
-- Removed the File Path from the Additional Help Sources scrolled list.
-
-- Add capability to access Additional Help Sources on the web if the
-  Help File Path begins with //http or www.  (Otherwise local path is
-  validated, as before.)
-
-- Additional Help Sources were not being posted on the Help menu in the
-  order entered.  Implement sorting the list by [HelpFiles] 'option'
-  number.
-
-- Add Browse button to New Help Source dialog.  Arrange to start in
-  Python/Doc if platform is Windows, otherwise start in current directory.
-
-- Put the Additional Help Sources directly on the Help menu instead of in
-  an Extra Help cascade menu.  Rearrange the Help menu so the Additional
-  Help Sources come last.  Update help.txt appropriately.
-
-- Fix Tk root pop-ups in configSectionNameDialog.py  and configDialog.py
-
-- Uniform capitalization in General tab of ConfigDialog, update the doc string.
-
-- Fix bug in ConfigDialog where SaveAllChangedConfig() was unexpectedly
-  deleting Additional Help Sources from the user's config file.
-
-- Make configHelpSourceEdit OK button the default and bind <Return>
-
-- Fix Tk root pop-ups in configHelpSourceEdit: error dialogs not attached
-  to parents.
-
-- Use os.startfile() to open both Additional Help and Python Help on the
-  Windows platform.  The application associated with the file type will act as
-  the viewer.  Windows help files (.chm) are now supported via the
-  Settings/General/Additional Help facility.
-
-- If Python Help files are installed locally on Linux, use them instead of
-  accessing python.org.
-
-- Make the methods for finding the Python help docs more robust, and make
-  them work in the installed configuration, also.
-
-- On the Save Before Run dialog, make the OK button the default.  One
-  less mouse action!
-
-- Add a method: EditorWindow.get_geometry() for future use in implementing
-  window location persistence.
-
-- Removed the "Help/Advice" menu entry.  Thanks, David!  We'll remember!
-
-- Change the "Classic Windows" theme's paste key to be <ctrl-v>.
-
-- Rearrange the Shell menu to put Stack Viewer entries adjacent.
-
-- Add the ability to restart the subprocess interpreter from the shell window;
-  add an associated menu entry "Shell/Restart" with binding Control-F6.  Update
-  IDLE help.
-
-- Upon a restart, annotate the shell window with a "restart boundary".  Add a
-  shell window menu "Shell/View Restart" with binding F6 to jump to the most
-  recent restart boundary.
-
-- Add Shell menu to Python Shell; change "Settings" to "Options".
-
-- Remove incorrect comment in setup.py: IDLEfork is now installed as a package.
-
-- Add INSTALL.txt, HISTORY.txt, NEWS.txt to installed configuration.
-
-- In installer text, fix reference to Visual Python, should be VPython.
-  Properly credit David Scherer.
-
-- Modified idle, idle.py, idle.pyw to improve exception handling.
-
-
-What's New in IDLEfork 0.9 Alpha 1?
-===================================
-*Release date: 31-Dec-2002*
-
-- First release of major new functionality.  For further details refer to
-  Idle-dev and/or the Sourceforge CVS.
-
-- Adapted to the Mac platform.
-
-- Overhauled the IDLE startup options and revised the idle -h help message,
-  which provides details of command line usage.
-
-- Multiple bug fixes and usability enhancements.
-
-- Introduced the new RPC implementation, which includes a debugger.  The output
-  of user code is to the shell, and the shell may be used to inspect the
-  environment after the run has finished.  (In version 0.8.1 the shell
-  environment was separate from the environment of the user code.)
-
-- Introduced the configuration GUI and a new About dialog.
-
-- Removed David Scherer's Remote Procedure Call code and replaced with Guido
-  van Rossum's.  GvR code has support for the IDLE debugger and uses the shell
-  to inspect the environment of code Run from an Edit window.  Files removed:
-  ExecBinding.py, loader.py, protocol.py, Remote.py, spawn.py
-
---------------------------------------------------------------------
-Refer to HISTORY.txt for additional information on earlier releases.
---------------------------------------------------------------------
+------------------------------------------------------------------------
+Refer to NEWS2x.txt and HISTORY.txt for information on earlier releases.
+------------------------------------------------------------------------
diff --git a/Lib/idlelib/NEWS2x.txt b/Lib/idlelib/NEWS2x.txt
new file mode 100644 (file)
index 0000000..6751ca5
--- /dev/null
@@ -0,0 +1,660 @@
+What's New in IDLE 2.7? (Merged into 3.1 before 2.7 release.)
+=======================
+*Release date: XX-XXX-2010*
+
+- idle.py modified and simplified to better support developing experimental
+  versions of IDLE which are not installed in the standard location.
+
+- OutputWindow/PyShell right click menu "Go to file/line" wasn't working with
+  file paths containing spaces.  Bug 5559.
+
+- Windows: Version string for the .chm help file changed, file not being
+  accessed  Patch 5783 Guilherme Polo
+
+- Allow multiple IDLE GUI/subprocess pairs to exist simultaneously. Thanks to
+  David Scherer for suggesting the use of an ephemeral port for the GUI.
+  Patch 1529142 Weeble.
+
+- Remove port spec from run.py and fix bug where subprocess fails to
+  extract port from command line when warnings are present.
+
+- Tk 8.5 Text widget requires 'wordprocessor' tabstyle attr to handle
+  mixed space/tab properly. Issue 5129, patch by Guilherme Polo.
+
+- Issue #3549: On MacOS the preferences menu was not present
+
+- IDLE would print a "Unhandled server exception!" message when internal
+  debugging is enabled.
+
+- Issue #4455: IDLE failed to display the windows list when two windows have
+  the same title.
+
+- Issue #4383: When IDLE cannot make the connection to its subprocess, it would
+  fail to properly display the error message.
+
+- help() was not paging to the shell.  Issue1650.
+
+- CodeContext was not importing.
+
+- Corrected two 3.0 compatibility errors reported by Mark Summerfield:
+  http://mail.python.org/pipermail/python-3000/2007-December/011491.html
+
+- Shell was not colorizing due to bug introduced at r57998,  Bug 1586.
+
+- Issue #1585: IDLE uses non-existent xrange() function.
+
+- Windows EOL sequence not converted correctly, encoding error.
+  Caused file save to fail. Bug 1130.
+
+- IDLE converted to Python 3000 syntax.
+
+- Strings became Unicode.
+
+- CallTips module now uses the inspect module to produce the argspec.
+
+- IDLE modules now use absolute import instead of implied relative import.
+
+- atexit call replaces sys.exitfunc.  The functionality of delete-exitfunc flag
+  in config-main.cfg remains unchanged: if set, registered exit functions will
+  be cleared before IDLE exits.
+
+
+What's New in IDLE 2.6
+======================
+*Release date: 01-Oct-2008*, merged into 3.0 releases detailed above (3.0rc2)
+
+- Issue #2665: On Windows, an IDLE installation upgraded from an old version
+  would not start if a custom theme was defined.
+
+- Home / Control-A toggles between left margin and end of leading white
+  space.  issue1196903, patch by Jeff Shute.
+
+- Improved AutoCompleteWindow logic.  issue2062, patch by Tal Einat.
+
+- Autocompletion of filenames now support alternate separators, e.g. the
+  '/' char on Windows.  issue2061 Patch by Tal Einat.
+
+- Configured selection highlighting colors were ignored; updating highlighting
+  in the config dialog would cause non-Python files to be colored as if they
+  were Python source; improve use of ColorDelagator.  Patch 1334. Tal Einat.
+
+- ScriptBinding event handlers weren't returning 'break'. Patch 2050, Tal Einat
+
+- There was an error on exit if no sys.exitfunc was defined. Issue 1647.
+
+- Could not open files in .idlerc directory if latter was hidden on Windows.
+  Issue 1743, Issue 1862.
+
+- Configure Dialog: improved layout for keybinding.  Patch 1457 Tal Einat.
+
+- tabpage.py updated: tabbedPages.py now supports multiple dynamic rows
+  of tabs.  Patch 1612746 Tal Einat.
+
+- Add confirmation dialog before printing.  Patch 1717170 Tal Einat.
+
+- Show paste position if > 80 col.  Patch 1659326 Tal Einat.
+
+- Update cursor color without restarting.  Patch 1725576 Tal Einat.
+
+- Allow keyboard interrupt only when user code is executing in subprocess.
+  Patch 1225 Tal Einat (reworked from IDLE-Spoon).
+
+- configDialog cleanup. Patch 1730217 Tal Einat.
+
+- textView cleanup. Patch 1718043 Tal Einat.
+
+- Clean up EditorWindow close.
+
+- Patch 1693258: Fix for duplicate "preferences" menu-OS X. Backport of r56204.
+
+- OSX: Avoid crash for those versions of Tcl/Tk which don't have a console
+
+- Bug in idlelib.MultiCall: Options dialog was crashing IDLE if there was an
+  option in config-extensions w/o a value. Patch #1672481, Tal Einat
+
+- Corrected some bugs in AutoComplete.  Also, Page Up/Down in ACW implemented;
+  mouse and cursor selection in ACWindow implemented; double Tab inserts
+  current selection and closes ACW (similar to double-click and Return); scroll
+  wheel now works in ACW.  Added AutoComplete instructions to IDLE Help.
+
+- AutoCompleteWindow moved below input line, will move above if there
+  isn't enough space.  Patch 1621265 Tal Einat
+
+- Calltips now 'handle' tuples in the argument list (display '<tuple>' :)
+  Suggested solution by Christos Georgiou, Bug 791968.
+
+- Add 'raw' support to configHandler. Patch 1650174 Tal Einat.
+
+- Avoid hang when encountering a duplicate in a completion list. Bug 1571112.
+
+- Patch #1362975: Rework CodeContext indentation algorithm to
+  avoid hard-coding pixel widths.
+
+- Bug #813342: Start the IDLE subprocess with -Qnew if the parent
+  is started with that option.
+
+- Honor the "Cancel" action in the save dialog (Debian bug #299092)
+
+- Some syntax errors were being caught by tokenize during the tabnanny
+  check, resulting in obscure error messages.  Do the syntax check
+  first.  Bug 1562716, 1562719
+
+- IDLE's version number takes a big jump to match the version number of
+  the Python release of which it's a part.
+
+
+What's New in IDLE 1.2?
+=======================
+*Release date: 19-SEP-2006*
+
+- File menu hotkeys: there were three 'p' assignments.  Reassign the
+  'Save Copy As' and 'Print' hotkeys to 'y' and 't'.  Change the
+  Shell hotkey from 's' to 'l'.
+
+- IDLE honors new quit() and exit() commands from site.py Quitter() object.
+  Patch 1540892, Jim Jewett
+
+- The 'with' statement is now a Code Context block opener.
+  Patch 1540851, Jim Jewett
+
+- Retrieval of previous shell command was not always preserving indentation
+  (since 1.2a1) Patch 1528468 Tal Einat.
+
+- Changing tokenize (39046) to detect dedent broke tabnanny check (since 1.2a1)
+
+- ToggleTab dialog was setting indent to 8 even if cancelled (since 1.2a1).
+
+- When used w/o subprocess, all exceptions were preceded by an error
+  message claiming they were IDLE internal errors (since 1.2a1).
+
+- Bug #1525817: Don't truncate short lines in IDLE's tool tips.
+
+- Bug #1517990: IDLE keybindings on MacOS X now work correctly
+
+- Bug #1517996: IDLE now longer shows the default Tk menu when a
+  path browser, class browser or debugger is the frontmost window on MacOS X
+
+- EditorWindow.test() was failing.  Bug 1417598
+
+- EditorWindow failed when used stand-alone if sys.ps1 not set.
+  Bug 1010370 Dave Florek
+
+- Tooltips failed on new-syle class __init__ args.  Bug 1027566 Loren Guthrie
+
+- Avoid occasional failure to detect closing paren properly.
+  Patch 1407280 Tal Einat
+
+- Rebinding Tab key was inserting 'tab' instead of 'Tab'.  Bug 1179168.
+
+- Colorizer now handles #<builtin> correctly, also unicode strings and
+  'as' keyword in comment directly following import command. Closes 1325071.
+  Patch 1479219 Tal Einat
+
+- Patch #1162825: Support non-ASCII characters in IDLE window titles.
+
+- Source file f.flush() after writing; trying to avoid lossage if user
+  kills GUI.
+
+- Options / Keys / Advanced dialog made functional.  Also, allow binding
+  of 'movement' keys.
+
+- 'syntax' patch adds improved calltips and a new class attribute listbox.
+  MultiCall module allows binding multiple actions to an event.
+  Patch 906702 Noam Raphael
+
+- Better indentation after first line of string continuation.
+  IDLEfork Patch 681992, Noam Raphael
+
+- Fixed CodeContext alignment problem, following suggestion from Tal Einat.
+
+- Increased performance in CodeContext extension  Patch 936169 Noam Raphael
+
+- Mac line endings were incorrect when pasting code from some browsers
+  when using X11 and the Fink distribution.  Python Bug 1263656.
+
+- <Enter> when cursor is on a previous command retrieves that command.  Instead
+  of replacing the input line, the previous command is now appended to the
+  input line. Indentation is preserved, and undo is enabled.
+  Patch 1196917  Jeff Shute
+
+- Clarify "tab/space" Error Dialog and "Tab Width" Dialog associated with
+  the Untabify command.
+
+- Corrected "tab/space" Error Dialog to show correct menu for Untabify.
+  Patch 1196980 Jeff Shute
+
+- New files are colorized by default, and colorizing is removed when
+  saving as non-Python files. Patch 1196895 Jeff Shute
+  Closes Python Bugs 775012 and 800432, partial fix IDLEfork 763524
+
+- Improve subprocess link error notification.
+
+- run.py: use Queue's blocking feature instead of sleeping in the main
+  loop.  Patch # 1190163 Michiel de Hoon
+
+- Add config-main option to make the 'history' feature non-cyclic.
+  Default remains cyclic.  Python Patch 914546 Noam Raphael.
+
+- Removed ability to configure tabs indent from Options dialog.  This 'feature'
+  has never worked and no one has complained.  It is still possible to set a
+  default tabs (v. spaces) indent 'manually' via config-main.def (or to turn on
+  tabs for the current EditorWindow via the Format menu) but IDLE will
+  encourage indentation via spaces.
+
+- Enable setting the indentation width using the Options dialog.
+  Bug # 783877
+
+- Add keybindings for del-word-left and del-word-right.
+
+- Discourage using an indent width other than 8 when using tabs to indent
+  Python code.
+
+- Restore use of EditorWindow.set_indentation_params(), was dead code since
+  Autoindent was merged into EditorWindow.  This allows IDLE to conform to the
+  indentation width of a loaded file.  (But it still will not switch to tabs
+  even if the file uses tabs.)  Any change in indent width is local to that
+  window.
+
+- Add Tabnanny check before Run/F5, not just when Checking module.
+
+- If an extension can't be loaded, print warning and skip it instead of
+  erroring out.
+
+- Improve error handling when .idlerc can't be created (warn and exit).
+
+- The GUI was hanging if the shell window was closed while a raw_input()
+  was pending.  Restored the quit() of the readline() mainloop().
+  http://mail.python.org/pipermail/idle-dev/2004-December/002307.html
+
+- The remote procedure call module rpc.py can now access data attributes of
+  remote registered objects.  Changes to these attributes are local, however.
+
+
+What's New in IDLE 1.1?
+=======================
+*Release date: 30-NOV-2004*
+
+- On OpenBSD, terminating IDLE with ctrl-c from the command line caused a
+  stuck subprocess MainThread because only the SocketThread was exiting.
+
+- Saving a Keyset w/o making changes (by using the "Save as New Custom Key Set"
+  button) caused IDLE to fail on restart (no new keyset was created in
+  config-keys.cfg).  Also true for Theme/highlights.  Python Bug 1064535.
+
+- A change to the linecache.py API caused IDLE to exit when an exception was
+  raised while running without the subprocess (-n switch).  Python Bug 1063840.
+
+- When paragraph reformat width was made configurable, a bug was
+  introduced that caused reformatting of comment blocks to ignore how
+  far the block was indented, effectively adding the indentation width
+  to the reformat width.  This has been repaired, and the reformat
+  width is again a bound on the total width of reformatted lines.
+
+- Improve keyboard focus binding, especially in Windows menu.  Improve
+  window raising, especially in the Windows menu and in the debugger.
+  IDLEfork 763524.
+
+- If user passes a non-existent filename on the commandline, just
+  open a new file, don't raise a dialog.  IDLEfork 854928.
+
+- EditorWindow.py was not finding the .chm help file on Windows.  Typo
+  at Rev 1.54.  Python Bug 990954
+
+- checking sys.platform for substring 'win' was breaking IDLE docs on Mac
+  (darwin).  Also, Mac Safari browser requires full file:// URIs.  SF 900580.
+
+- Redirect the warning stream to the shell during the ScriptBinding check of
+  user code and format the warning similarly to an exception for both that
+  check and for runtime warnings raised in the subprocess.
+
+- CodeContext hint pane visibility state is now persistent across sessions.
+  The pane no longer appears in the shell window.  Added capability to limit
+  extensions to shell window or editor windows.  Noam Raphael addition
+  to Patch 936169.
+
+- Paragraph reformat width is now a configurable parameter in the
+  Options GUI.
+
+- New Extension: CodeContext.  Provides block structuring hints for code
+  which has scrolled above an edit window. Patch 936169 Noam Raphael.
+
+- If nulls somehow got into the strings in recent-files.lst
+  EditorWindow.update_recent_files_list() was failing.  Python Bug 931336.
+
+- If the normal background is changed via Configure/Highlighting, it will
+  update immediately, thanks to the previously mentioned patch by Nigel Rowe.
+
+- Add a highlight theme for builtin keywords.  Python Patch 805830 Nigel Rowe
+  This also fixed IDLEfork bug [ 693418 ] Normal text background color not
+  refreshed and Python bug [897872 ] Unknown color name on HP-UX
+
+- rpc.py:SocketIO - Large modules were generating large pickles when downloaded
+  to the execution server.  The return of the OK response from the subprocess
+  initialization was interfering and causing the sending socket to be not
+  ready.  Add an IO ready test to fix this.  Moved the polling IO ready test
+  into pollpacket().
+
+- Fix typo in rpc.py, s/b "pickle.PicklingError" not "pickle.UnpicklingError".
+
+- Added a Tk error dialog to run.py inform the user if the subprocess can't
+  connect to the user GUI process.  Added a timeout to the GUI's listening
+  socket.  Added Tk error dialogs to PyShell.py to announce a failure to bind
+  the port or connect to the subprocess.  Clean up error handling during
+  connection initiation phase.  This is an update of Python Patch 778323.
+
+- Print correct exception even if source file changed since shell was
+  restarted.  IDLEfork Patch 869012 Noam Raphael
+
+- Keybindings with the Shift modifier now work correctly.  So do bindings which
+  use the Space key.  Limit unmodified user keybindings to the function keys.
+  Python Bug 775353, IDLEfork Bugs 755647, 761557
+
+- After an exception, run.py was not setting the exception vector. Noam
+  Raphael suggested correcting this so pdb's postmortem pm() would work.
+  IDLEfork Patch 844675
+
+- IDLE now does not fail to save the file anymore if the Tk buffer is not a
+  Unicode string, yet eol_convention is.  Python Bugs 774680, 788378
+
+- IDLE didn't start correctly when Python was installed in "Program Files" on
+  W2K and XP.  Python Bugs 780451, 784183
+
+- config-main.def documentation incorrectly referred to idle- instead of
+  config-  filenames.  SF 782759  Also added note about .idlerc location.
+
+
+What's New in IDLE 1.0?
+=======================
+*Release date: 29-Jul-2003*
+
+- Added a banner to the shell discussing warnings possibly raised by personal
+  firewall software.  Added same comment to README.txt.
+
+- Calltip error when docstring was None  Python Bug 775541
+
+- Updated extend.txt, help.txt, and config-extensions.def to correctly
+  reflect the current status of the configuration system.  Python Bug 768469
+
+- Fixed: Call Tip Trimming May Loop Forever. Python Patch 769142 (Daniels)
+
+- Replaced apply(f, args, kwds) with f(*args, **kwargs) to improve performance
+  Python Patch 768187
+
+- Break or continue statements outside a loop were causing IDLE crash
+  Python Bug 767794
+
+- Convert Unicode strings from readline to IOBinding.encoding.  Also set
+  sys.std{in|out|err}.encoding, for both the local and the subprocess case.
+  SF IDLEfork patch 682347.
+
+- Extend AboutDialog.ViewFile() to support file encodings.  Make the CREDITS
+  file Latin-1.
+
+- Updated the About dialog to reflect re-integration into Python.  Provide
+  buttons to display Python's NEWS, License, and Credits, plus additional
+  buttons for IDLE's README and NEWS.
+
+- TextViewer() now has a third parameter which allows inserting text into the
+  viewer instead of reading from a file.
+
+- (Created the .../Lib/idlelib directory in the Python CVS, which is a clone of
+  IDLEfork modified to install in the Python environment.  The code in the
+  interrupt module has been moved to thread.interrupt_main(). )
+
+- Printing the Shell window was failing if it was not saved first SF 748975
+
+- When using the Search in Files dialog, if the user had a selection
+  highlighted in his Editor window, insert it into the dialog search field.
+
+- The Python Shell entry was disappearing from the Windows menu.
+
+- Update the Windows file list when a file name change occurs
+
+- Change to File / Open Module: always pop up the dialog, using the current
+  selection as the default value.  This is easier to use habitually.
+
+- Avoided a problem with starting the subprocess when 'localhost' doesn't
+  resolve to the user's loopback interface.  SF 747772
+
+- Fixed an issue with highlighted errors never de-colorizing.  SF 747677.  Also
+  improved notification of Tabnanny Token Error.
+
+- File / New will by default save in the directory of the Edit window from
+  which it was initiated.  SF 748973 Guido van Rossum patch.
+
+
+What's New in IDLEfork 0.9b1?
+=============================
+*Release date: 02-Jun-2003*
+
+- The current working directory of the execution environment (and shell
+  following completion of execution) is now that of the module being run.
+
+- Added the delete-exitfunc option to config-main.def.  (This option is not
+  included in the Options dialog.)  Setting this to True (the default) will
+  cause IDLE to not run sys.exitfunc/atexit when the subprocess exits.
+
+- IDLE now preserves the line ending codes when editing a file produced on
+  a different platform. SF 661759,  SF 538584
+
+- Reduced default editor font size to 10 point and increased window height
+  to provide a better initial impression on Windows.
+
+- Options / Fonts/Tabs / Set Base Editor Font: List box was not highlighting
+  the default font when first installed on Windows.  SF 661676
+
+- Added Autosave feature: when user runs code from edit window, if the file
+  has been modified IDLE will silently save it if Autosave is enabled.  The
+  option is set in the Options dialog, and the default is to prompt the
+  user to save the file.   SF 661318 Bruce Sherwood patch.
+
+- Improved the RESTART annotation in the shell window when the user restarts
+  the shell while it is generating output.  Also improved annotation when user
+  repeatedly hammers the Ctrl-F6 restart.
+
+- Allow IDLE to run when not installed and cwd is not the IDLE directory
+  SF Patch 686254 "Run IDLEfork from any directory without set-up" - Raphael
+
+- When a module is run from an EditorWindow: if its directory is not in
+  sys.path, prepend it.  This allows the module to import other modules in
+  the same directory.  Do the same for a script run from the command line.
+
+- Correctly restart the subprocess if it is running user code and the user
+  attempts to run some other module or restarts the shell.  Do the same if
+  the link is broken and it is possible to restart the subprocess and re-
+  connect to the GUI.   SF RFE 661321.
+
+- Improved exception reporting when running commands or scripts from the
+  command line.
+
+- Added a -n command line switch to start IDLE without the subprocess.
+  Removed the Shell menu when running in that mode.  Updated help messages.
+
+- Added a comment to the shell startup header to indicate when IDLE is not
+  using the subprocess.
+
+- Restore the ability to run without the subprocess.  This can be important for
+  some platforms or configurations.  (Running without the subprocess allows the
+  debugger to trace through parts of IDLE itself, which may or may not be
+  desirable, depending on your point of view.  In addition, the traditional
+  reload/import tricks must be use if user source code is changed.)  This is
+  helpful for developing IDLE using IDLE, because one instance can be used to
+  edit the code and a separate instance run to test changes.  (Multiple
+  concurrent IDLE instances with subprocesses is a future feature)
+
+- Improve the error message a user gets when saving a file with non-ASCII
+  characters and no source encoding is specified.  Done by adding a dialog
+  'EncodingMessage', which contains the line to add in a fixed-font entry
+  widget, and which has a button to add that line to the file automatically.
+  Also, add a configuration option 'EditorWindow/encoding', which has three
+  possible values: none, utf-8, and locale. None is the default: IDLE will show
+  this dialog when non-ASCII characters are encountered. utf-8 means that files
+  with non-ASCII characters are saved as utf-8-with-bom. locale means that
+  files are saved in the locale's encoding; the dialog is only displayed if the
+  source contains characters outside the locale's charset.  SF 710733 - Loewis
+
+- Improved I/O response by tweaking the wait parameter in various
+  calls to signal.signal().
+
+- Implemented a threaded subprocess which allows interrupting a pass
+  loop in user code using the 'interrupt' extension.  User code runs
+  in MainThread, while the RPCServer is handled by SockThread.  This is
+  necessary because Windows doesn't support signals.
+
+- Implemented the 'interrupt' extension module, which allows a subthread
+  to raise a KeyboardInterrupt in the main thread.
+
+- Attempting to save the shell raised an error related to saving
+  breakpoints, which are not implemented in the shell
+
+- Provide a correct message when 'exit' or 'quit' are entered at the
+  IDLE command prompt  SF 695861
+
+- Eliminate extra blank line in shell output caused by not flushing
+  stdout when user code ends with an unterminated print. SF 695861
+
+- Moved responsibility for exception formatting (i.e. pruning IDLE internal
+  calls) out of rpc.py into the client and server.
+
+- Exit IDLE cleanly even when doing subprocess I/O
+
+- Handle subprocess interrupt with an RPC message.
+
+- Restart the subprocess if it terminates itself. (VPython programs do that)
+
+- Support subclassing of exceptions, including in the shell, by moving the
+  exception formatting to the subprocess.
+
+
+What's New in IDLEfork 0.9 Alpha 2?
+===================================
+*Release date: 27-Jan-2003*
+
+- Updated INSTALL.txt to claify use of the python2 rpm.
+
+- Improved formatting in IDLE Help.
+
+- Run menu: Replace "Run Script" with "Run Module".
+
+- Code encountering an unhandled exception under the debugger now shows
+  the correct traceback, with IDLE internal levels pruned out.
+
+- If an exception occurs entirely in IDLE, don't prune the IDLE internal
+  modules from the traceback displayed.
+
+- Class Browser and Path Browser now use Alt-Key-2 for vertical zoom.
+
+- IDLE icons will now install correctly even when setup.py is run from the
+  build directory
+
+- Class Browser now compatible with Python2.3 version of pyclbr.py
+
+- Left cursor move in presence of selected text now moves from left end
+  of the selection.
+
+- Add Meta keybindings to "IDLE Classic Windows" to handle reversed
+  Alt/Meta on some Linux distros.
+
+- Change default: IDLE now starts with Python Shell.
+
+- Removed the File Path from the Additional Help Sources scrolled list.
+
+- Add capability to access Additional Help Sources on the web if the
+  Help File Path begins with //http or www.  (Otherwise local path is
+  validated, as before.)
+
+- Additional Help Sources were not being posted on the Help menu in the
+  order entered.  Implement sorting the list by [HelpFiles] 'option'
+  number.
+
+- Add Browse button to New Help Source dialog.  Arrange to start in
+  Python/Doc if platform is Windows, otherwise start in current directory.
+
+- Put the Additional Help Sources directly on the Help menu instead of in
+  an Extra Help cascade menu.  Rearrange the Help menu so the Additional
+  Help Sources come last.  Update help.txt appropriately.
+
+- Fix Tk root pop-ups in configSectionNameDialog.py  and configDialog.py
+
+- Uniform capitalization in General tab of ConfigDialog, update the doc string.
+
+- Fix bug in ConfigDialog where SaveAllChangedConfig() was unexpectedly
+  deleting Additional Help Sources from the user's config file.
+
+- Make configHelpSourceEdit OK button the default and bind <Return>
+
+- Fix Tk root pop-ups in configHelpSourceEdit: error dialogs not attached
+  to parents.
+
+- Use os.startfile() to open both Additional Help and Python Help on the
+  Windows platform.  The application associated with the file type will act as
+  the viewer.  Windows help files (.chm) are now supported via the
+  Settings/General/Additional Help facility.
+
+- If Python Help files are installed locally on Linux, use them instead of
+  accessing python.org.
+
+- Make the methods for finding the Python help docs more robust, and make
+  them work in the installed configuration, also.
+
+- On the Save Before Run dialog, make the OK button the default.  One
+  less mouse action!
+
+- Add a method: EditorWindow.get_geometry() for future use in implementing
+  window location persistence.
+
+- Removed the "Help/Advice" menu entry.  Thanks, David!  We'll remember!
+
+- Change the "Classic Windows" theme's paste key to be <ctrl-v>.
+
+- Rearrange the Shell menu to put Stack Viewer entries adjacent.
+
+- Add the ability to restart the subprocess interpreter from the shell window;
+  add an associated menu entry "Shell/Restart" with binding Control-F6.  Update
+  IDLE help.
+
+- Upon a restart, annotate the shell window with a "restart boundary".  Add a
+  shell window menu "Shell/View Restart" with binding F6 to jump to the most
+  recent restart boundary.
+
+- Add Shell menu to Python Shell; change "Settings" to "Options".
+
+- Remove incorrect comment in setup.py: IDLEfork is now installed as a package.
+
+- Add INSTALL.txt, HISTORY.txt, NEWS.txt to installed configuration.
+
+- In installer text, fix reference to Visual Python, should be VPython.
+  Properly credit David Scherer.
+
+- Modified idle, idle.py, idle.pyw to improve exception handling.
+
+
+What's New in IDLEfork 0.9 Alpha 1?
+===================================
+*Release date: 31-Dec-2002*
+
+- First release of major new functionality.  For further details refer to
+  Idle-dev and/or the Sourceforge CVS.
+
+- Adapted to the Mac platform.
+
+- Overhauled the IDLE startup options and revised the idle -h help message,
+  which provides details of command line usage.
+
+- Multiple bug fixes and usability enhancements.
+
+- Introduced the new RPC implementation, which includes a debugger.  The output
+  of user code is to the shell, and the shell may be used to inspect the
+  environment after the run has finished.  (In version 0.8.1 the shell
+  environment was separate from the environment of the user code.)
+
+- Introduced the configuration GUI and a new About dialog.
+
+- Removed David Scherer's Remote Procedure Call code and replaced with Guido
+  van Rossum's.  GvR code has support for the IDLE debugger and uses the shell
+  to inspect the environment of code Run from an Edit window.  Files removed:
+  ExecBinding.py, loader.py, protocol.py, Remote.py, spawn.py
+
+--------------------------------------------------------------------
+Refer to HISTORY.txt for additional information on earlier releases.
+--------------------------------------------------------------------
index 19bad8c..47e10f3 100644 (file)
@@ -9,7 +9,7 @@ from idlelib.HyperParser import HyperParser
 from idlelib.configHandler import idleConf
 
 _openers = {')':'(',']':'[','}':'{'}
-CHECK_DELAY = 100 # miliseconds
+CHECK_DELAY = 100 # milliseconds
 
 class ParenMatch:
     """Highlight matching parentheses
index 7bf74c0..ff44504 100644 (file)
@@ -16,7 +16,7 @@ and omissions and lag behind changes in idlelib.
 
 
 IDLELIB FILES
-Implemetation files not in IDLE MENU are marked (nim).
+Implementation files not in IDLE MENU are marked (nim).
 Deprecated files and objects are listed separately as the end.
 
 Startup
@@ -161,14 +161,15 @@ Edit
   Show surrounding parens  # ParenMatch (& Hyperparser)
 
 Shell  # PyShell
-  View Last Restart  # PyShell.?
-  Restart 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
-  Stack Viewer  # StackViewer
-  Auto-open Stack Viewer  # StackViewer
+  Debugger               # Debugger, RemoteDebugger, PyShell.toggle_debuger
+  Stack Viewer           # StackViewer, PyShell.open_stack_viewer
+  Auto-open Stack Viewer # StackViewer
 
 Format (Editor only)
   Indent Region
index 0457c43..a8f75d2 100644 (file)
@@ -145,5 +145,7 @@ class AboutDialog(Toplevel):
         self.destroy()
 
 if __name__ == '__main__':
+    import unittest
+    unittest.main('idlelib.idle_test.test_helpabout', verbosity=2, exit=False)
     from idlelib.idle_test.htest import run
     run(AboutDialog)
index b702253..5f5bd36 100644 (file)
@@ -751,6 +751,7 @@ class ConfigDialog(Toplevel):
         if not tkMessageBox.askyesno(
                 'Delete Key Set',  delmsg % keySetName, parent=self):
             return
+        self.DeactivateCurrentConfig()
         #remove key set from config
         idleConf.userCfg['keys'].remove_section(keySetName)
         if keySetName in self.changedItems['keys']:
@@ -769,7 +770,8 @@ class ConfigDialog(Toplevel):
         self.keysAreBuiltin.set(idleConf.defaultCfg['main'].Get('Keys', 'default'))
         self.builtinKeys.set(idleConf.defaultCfg['main'].Get('Keys', 'name'))
         #user can't back out of these changes, they must be applied now
-        self.Apply()
+        self.SaveAllChangedConfigs()
+        self.ActivateConfigChanges()
         self.SetKeysType()
 
     def DeleteCustomTheme(self):
@@ -778,6 +780,7 @@ class ConfigDialog(Toplevel):
         if not tkMessageBox.askyesno(
                 'Delete Theme',  delmsg % themeName, parent=self):
             return
+        self.DeactivateCurrentConfig()
         #remove theme from config
         idleConf.userCfg['highlight'].remove_section(themeName)
         if themeName in self.changedItems['highlight']:
@@ -796,7 +799,8 @@ class ConfigDialog(Toplevel):
         self.themeIsBuiltin.set(idleConf.defaultCfg['main'].Get('Theme', 'default'))
         self.builtinTheme.set(idleConf.defaultCfg['main'].Get('Theme', 'name'))
         #user can't back out of these changes, they must be applied now
-        self.Apply()
+        self.SaveAllChangedConfigs()
+        self.ActivateConfigChanges()
         self.SetThemeType()
 
     def GetColour(self):
index 8ac1f60..8954488 100644 (file)
@@ -740,21 +740,32 @@ class IdleConf:
 idleConf = IdleConf()
 
 # TODO Revise test output, write expanded unittest
-### module test
+#
 if __name__ == '__main__':
+    from zlib import crc32
+    line, crc = 0, 0
+
+    def sprint(obj):
+        global line, crc
+        txt = str(obj)
+        line += 1
+        crc = crc32(txt.encode(encoding='utf-8'), crc)
+        print(txt)
+        #print('***', line, crc, '***')  # uncomment for diagnosis
+
     def dumpCfg(cfg):
-        print('\n', cfg, '\n')
-        for key in cfg:
+        print('\n', cfg, '\n')  # has variable '0xnnnnnnnn' addresses
+        for key in sorted(cfg.keys()):
             sections = cfg[key].sections()
-            print(key)
-            print(sections)
+            sprint(key)
+            sprint(sections)
             for section in sections:
                 options = cfg[key].options(section)
-                print(section)
-                print(options)
+                sprint(section)
+                sprint(options)
                 for option in options:
-                    print(option, '=', cfg[key].Get(section, option))
+                    sprint(option + ' = ' + cfg[key].Get(section, option))
+
     dumpCfg(idleConf.defaultCfg)
     dumpCfg(idleConf.userCfg)
-    print(idleConf.userCfg['main'].Get('Theme', 'name'))
-    #print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal')
+    print('\nlines = ', line, ', crc = ', crc, sep='')
index 6f739c4..ffc03c4 100644 (file)
@@ -6,7 +6,7 @@
   <head>
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
-    <title>25.5. IDLE &mdash; Python 3.5.1 documentation</title>
+    <title>25.5. IDLE &mdash; Python 3.5.2 documentation</title>
 
     <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
     <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
@@ -14,7 +14,7 @@
     <script type="text/javascript">
       var DOCUMENTATION_OPTIONS = {
         URL_ROOT:    '../',
-        VERSION:     '3.5.1',
+        VERSION:     '3.5.2',
         COLLAPSE_INDEX: false,
         FILE_SUFFIX: '.html',
         HAS_SOURCE:  true
     <script type="text/javascript" src="../_static/doctools.js"></script>
     <script type="text/javascript" src="../_static/sidebar.js"></script>
     <link rel="search" type="application/opensearchdescription+xml"
-          title="Search within Python 3.5.1 documentation"
+          title="Search within Python 3.5.2 documentation"
           href="../_static/opensearch.xml"/>
     <link rel="author" title="About these documents" href="../about.html" />
     <link rel="copyright" title="Copyright" href="../copyright.html" />
-    <link rel="top" title="Python 3.5.1 documentation" href="../contents.html" />
+    <link rel="top" title="Python 3.5.2 documentation" href="../contents.html" />
     <link rel="up" title="25. Graphical User Interfaces with Tk" href="tk.html" />
     <link rel="next" title="25.6. Other Graphical User Interface Packages" href="othergui.html" />
     <link rel="prev" title="25.4. tkinter.scrolledtext — Scrolled Text Widget" href="tkinter.scrolledtext.html" />
                  style="vertical-align: middle; margin-top: -1px"/></li>
         <li><a href="https://www.python.org/">Python</a> &raquo;</li>
         <li>
-          <a href="../index.html">3.5.1 Documentation</a> &raquo;
+          <a href="../index.html">3.5.2 Documentation</a> &raquo;
         </li>
 
           <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &raquo;</li>
           <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">25. Graphical User Interfaces with Tk</a> &raquo;</li>
+    <li class="right">
+
+
+    <div class="inline-search" style="display: none" role="search">
+        <form class="inline-search" action="../search.html" method="get">
+          <input placeholder="Quick search" type="text" name="q" />
+          <input type="submit" value="Go" />
+          <input type="hidden" name="check_keywords" value="yes" />
+          <input type="hidden" name="area" value="default" />
+        </form>
+    </div>
+    <script type="text/javascript">$('.inline-search').show(0);</script>
+         |
+    </li>
+
       </ul>
     </div>
 
@@ -240,6 +255,8 @@ line.</dd>
 <dd>Scroll the shell window to the last Shell restart.</dd>
 <dt>Restart Shell</dt>
 <dd>Restart the shell to clean the environment.</dd>
+<dt>Interrupt Execution</dt>
+<dd>Stop a running program.</dd>
 </dl>
 </div>
 <div class="section" id="debug-menu-shell-window-only">
@@ -492,12 +509,12 @@ executed in the Tk namespace, so this file is not useful for importing
 functions to be used from IDLE&#8217;s Python shell.</p>
 <div class="section" id="command-line-usage">
 <h3>25.5.3.1. Command line usage<a class="headerlink" href="#command-line-usage" title="Permalink to this headline">¶</a></h3>
-<div class="highlight-python3"><div class="highlight"><pre>idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...
+<div class="highlight-none"><div class="highlight"><pre><span></span>idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...
 
 -c command  run command in the shell window
 -d          enable debugger and open shell window
 -e          open editor window
--h          print help message with legal combinatios and exit
+-h          print help message with legal combinations and exit
 -i          open shell window
 -r file     run file in shell window
 -s          run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
@@ -526,10 +543,12 @@ objects that get input from and send output to the Shell window.
 When this window has the focus, it controls the keyboard and screen.
 This is normally transparent, but functions that directly access the keyboard
 and screen will not work.  If <code class="docutils literal"><span class="pre">sys</span></code> is reset with <code class="docutils literal"><span class="pre">importlib.reload(sys)</span></code>,
-IDLE&#8217;s changes are lost and things li ke <code class="docutils literal"><span class="pre">input</span></code>, <code class="docutils literal"><span class="pre">raw_input</span></code>, and
+IDLE&#8217;s changes are lost and things like <code class="docutils literal"><span class="pre">input</span></code>, <code class="docutils literal"><span class="pre">raw_input</span></code>, and
 <code class="docutils literal"><span class="pre">print</span></code> will not work correctly.</p>
 <p>With IDLE&#8217;s Shell, one enters, edits, and recalls complete statements.
-Some consoles only work with a single physical line at a time.</p>
+Some consoles only work with a single physical line at a time.  IDLE uses
+<code class="docutils literal"><span class="pre">exec</span></code> to run each statement.  As a result, <code class="docutils literal"><span class="pre">'__builtins__'</span></code> is always
+defined for each statement.</p>
 </div>
 <div class="section" id="running-without-a-subprocess">
 <h3>25.5.3.3. Running without a subprocess<a class="headerlink" href="#running-without-a-subprocess" title="Permalink to this headline">¶</a></h3>
@@ -647,26 +666,14 @@ are currently:</p>
   <h4>Next topic</h4>
   <p class="topless"><a href="othergui.html"
                         title="next chapter">25.6. Other Graphical User Interface Packages</a></p>
-<h3>This Page</h3>
-<ul class="this-page-menu">
-  <li><a href="../bugs.html">Report a Bug</a></li>
-  <li><a href="../_sources/library/idle.txt"
-         rel="nofollow">Show Source</a></li>
-</ul>
-
-<div id="searchbox" style="display: none" role="search">
-  <h3>Quick search</h3>
-    <form class="search" action="../search.html" method="get">
-      <input type="text" name="q" />
-      <input type="submit" value="Go" />
-      <input type="hidden" name="check_keywords" value="yes" />
-      <input type="hidden" name="area" value="default" />
-    </form>
-    <p class="searchtip" style="font-size: 90%">
-    Enter search terms or a module, class or function name.
-    </p>
-</div>
-<script type="text/javascript">$('#searchbox').show(0);</script>
+  <div role="note" aria-label="source link">
+    <h3>This Page</h3>
+    <ul class="this-page-menu">
+      <li><a href="../bugs.html">Report a Bug</a></li>
+      <li><a href="../_sources/library/idle.txt"
+            rel="nofollow">Show Source</a></li>
+    </ul>
+  </div>
         </div>
       </div>
       <div class="clearer"></div>
@@ -690,11 +697,26 @@ are currently:</p>
                  style="vertical-align: middle; margin-top: -1px"/></li>
         <li><a href="https://www.python.org/">Python</a> &raquo;</li>
         <li>
-          <a href="../index.html">3.5.1 Documentation</a> &raquo;
+          <a href="../index.html">3.5.2 Documentation</a> &raquo;
         </li>
 
           <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &raquo;</li>
           <li class="nav-item nav-item-2"><a href="tk.html" >25. Graphical User Interfaces with Tk</a> &raquo;</li>
+    <li class="right">
+
+
+    <div class="inline-search" style="display: none" role="search">
+        <form class="inline-search" action="../search.html" method="get">
+          <input placeholder="Quick search" type="text" name="q" />
+          <input type="submit" value="Go" />
+          <input type="hidden" name="check_keywords" value="yes" />
+          <input type="hidden" name="area" value="default" />
+        </form>
+    </div>
+    <script type="text/javascript">$('.inline-search').show(0);</script>
+         |
+    </li>
+
       </ul>
     </div>
     <div class="footer">
@@ -703,10 +725,10 @@ are currently:</p>
     The Python Software Foundation is a non-profit corporation.
     <a href="https://www.python.org/psf/donations/">Please donate.</a>
     <br />
-    Last updated on Jun 11, 2016.
+    Last updated on Sep 12, 2016.
     <a href="../bugs.html">Found a bug</a>?
     <br />
-    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.3.
+    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.6.
     </div>
 
   </body>
index d0c59c5..a7008e9 100644 (file)
@@ -26,6 +26,7 @@ show_idlehelp - Create HelpWindow.  Called in EditorWindow.help_dialog.
 """
 from html.parser import HTMLParser
 from os.path import abspath, dirname, isdir, isfile, join
+from platform import python_version
 from tkinter import Tk, Toplevel, Frame, Text, Scrollbar, Menu, Menubutton
 from tkinter import font as tkfont
 from idlelib.configHandler import idleConf
@@ -265,7 +266,7 @@ def show_idlehelp(parent):
     if not isfile(filename):
         # try copy_strip, present message
         return
-    HelpWindow(parent, filename, 'IDLE Help')
+    HelpWindow(parent, filename, 'IDLE Help (%s)' % python_version())
 
 if __name__ == '__main__':
     from idlelib.idle_test.htest import run
index a249557..141534d 100644 (file)
@@ -1,11 +1,13 @@
 import os.path
 import sys
 
-# If we are working on a development version of IDLE, we need to prepend the
-# parent of this idlelib dir to sys.path.  Otherwise, importing idlelib gets
-# the version installed with the Python used to call this module:
+# 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,
+# removal should require deprecation.
 idlelib_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-sys.path.insert(0, idlelib_dir)
+if idlelib_dir not in sys.path:
+    sys.path.insert(0, idlelib_dir)
 
-import idlelib.PyShell
-idlelib.PyShell.main()
+from idlelib.PyShell import main  # This is subject to change
+main()
index e4493d1..5fc899d 100644 (file)
@@ -4,7 +4,6 @@ from tkinter import Tk, Text
 
 import idlelib.AutoComplete as ac
 import idlelib.AutoCompleteWindow as acw
-import idlelib.macosxSupport as mac
 from idlelib.idle_test.mock_idle import Func
 from idlelib.idle_test.mock_tk import Event
 
@@ -27,7 +26,6 @@ class AutoCompleteTest(unittest.TestCase):
     def setUpClass(cls):
         requires('gui')
         cls.root = Tk()
-        mac.setupApp(cls.root, None)
         cls.text = Text(cls.root)
         cls.editor = DummyEditwin(cls.root, cls.text)
 
index b063601..5c09790 100644 (file)
@@ -15,6 +15,7 @@ class ConfigDialogTest(unittest.TestCase):
     @classmethod
     def setUpClass(cls):
         cls.root = Tk()
+        cls.root.withdraw()
         macosx._initializeTkVariantTests(cls.root)
 
     @classmethod
index 50317a9..a258e29 100644 (file)
@@ -16,6 +16,7 @@ class PasteTest(unittest.TestCase):
     @classmethod
     def setUpClass(cls):
         cls.root = root = tk.Tk()
+        root.withdraw()
         PyShell.fix_x11_paste(root)
         cls.text = tk.Text(root)
         cls.entry = tk.Entry(root)
index e5561d8..b6eb2f3 100644 (file)
@@ -159,7 +159,7 @@ class FindTest(unittest.TestCase):
 class ReformatFunctionTest(unittest.TestCase):
     """Test the reformat_paragraph function without the editor window."""
 
-    def test_reformat_paragrah(self):
+    def test_reformat_paragraph(self):
         Equal = self.assertEqual
         reform = fp.reformat_paragraph
         hw = "O hello world"
diff --git a/Lib/idlelib/idle_test/test_help_about.py b/Lib/idlelib/idle_test/test_help_about.py
new file mode 100644 (file)
index 0000000..d0a0127
--- /dev/null
@@ -0,0 +1,52 @@
+'''Test idlelib.help_about.
+
+Coverage:
+'''
+from idlelib import aboutDialog as help_about
+from idlelib import textView as textview
+from idlelib.idle_test.mock_idle import Func
+from idlelib.idle_test.mock_tk import Mbox
+import unittest
+
+About = help_about.AboutDialog
+class Dummy_about_dialog():
+    # Dummy class for testing file display functions.
+    idle_credits = About.ShowIDLECredits
+    idle_readme = About.ShowIDLEAbout
+    idle_news = About.ShowIDLENEWS
+    # Called by the above
+    display_file_text = About.display_file_text
+
+
+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_view = textview.view_text
+        cls.mbox = Mbox()
+        cls.view = Func()
+        textview.tkMessageBox = cls.mbox
+        textview.view_text = cls.view
+        cls.About = Dummy_about_dialog()
+
+    @classmethod
+    def tearDownClass(cls):
+        textview.tkMessageBox = cls.orig_mbox
+        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.view.called = False
+            handler()
+            self.assertEqual(self.mbox.showerror.message, '')
+            self.assertEqual(self.view.called, True)
+
+
+if __name__ == '__main__':
+    unittest.main(verbosity=2)
index edfc783..9ce3f2c 100644 (file)
@@ -37,6 +37,7 @@ class HyperParserTest(unittest.TestCase):
     def setUpClass(cls):
         requires('gui')
         cls.root = Tk()
+        cls.root.withdraw()
         cls.text = Text(cls.root)
         cls.editwin = DummyEditwin(cls.text)
 
index d7c3d70..6e7c6c3 100644 (file)
@@ -68,6 +68,7 @@ class FetchTest(unittest.TestCase):
     def setUpClass(cls):
         requires('gui')
         cls.root = tk.Tk()
+        cls.root.withdraw()
 
     def setUp(self):
         self.text = text = TextWrapper(self.root)
index 02d1472..5d2e600 100644 (file)
@@ -20,16 +20,16 @@ from idlelib.idle_test.mock_tk import Mbox
 def setUpModule():
     global root
     root = Tk()
+    root.withdraw()
 
 def tearDownModule():
-    global root, TV
-    del TV
+    global root
     root.update_idletasks()
-    root.destroy()  # pyflakes falsely sees root as undefined
+    root.destroy()  # Pyflakes falsely sees root as undefined.
     del root
 
 
-class TV(tv.TextViewer):  # used by TextViewTest
+class TV(tv.TextViewer):  # Used in TextViewTest.
     transient = Func()
     grab_set = Func()
     wait_window = Func()
@@ -60,8 +60,8 @@ class TextViewTest(unittest.TestCase):
         view.destroy = Func()
         view.Ok()
         self.assertTrue(view.destroy.called)
-        del view.destroy  # unmask real function
-        view.destroy
+        del view.destroy  # Unmask real function.
+        view.destroy()
 
 
 class textviewTest(unittest.TestCase):
@@ -77,9 +77,10 @@ class textviewTest(unittest.TestCase):
         del cls.orig_mbox
 
     def test_view_text(self):
-        # If modal True, tkinter will error with 'can't invoke "event" command'
+        # If modal True, get tk error 'can't invoke "event" command'.
         view = tv.view_text(root, 'Title', 'test text', modal=False)
         self.assertIsInstance(view, tv.TextViewer)
+        view.Ok()
 
     def test_view_file(self):
         test_dir = os.path.dirname(__file__)
index c68dfcc..baa975d 100644 (file)
@@ -15,6 +15,7 @@ class InitCloseTest(unittest.TestCase):
     def setUpClass(cls):
         requires('gui')
         cls.root = Tk()
+        cls.root.withdraw()
         cls.text = Text(cls.root)
 
     @classmethod
@@ -44,6 +45,7 @@ class WidgetRedirectorTest(unittest.TestCase):
     def setUpClass(cls):
         requires('gui')
         cls.root = Tk()
+        cls.root.withdraw()
         cls.text = Text(cls.root)
 
     @classmethod
index 595e7bc..28ce420 100644 (file)
@@ -19,6 +19,12 @@ from idlelib import IOBinding
 
 import __main__
 
+for mod in ('simpledialog', 'messagebox', 'font',
+            'dialog', 'filedialog', 'commondialog',
+            'colorchooser'):
+    delattr(tkinter, mod)
+    del sys.modules['tkinter.' + mod]
+
 LOCALHOST = '127.0.0.1'
 
 import warnings
index 01b2d8f..12ac319 100644 (file)
@@ -76,6 +76,10 @@ def view_file(parent, title, filename, encoding=None, modal=True):
         tkMessageBox.showerror(title='File Load Error',
                                message='Unable to load file %r .' % filename,
                                parent=parent)
+    except UnicodeDecodeError as err:
+        tkMessageBox.showerror(title='Unicode Decode Error',
+                               message=str(err),
+                               parent=parent)
     else:
         return view_text(parent, title, contents, modal)
 
index 4e8a4bb..2f7e933 100644 (file)
@@ -411,7 +411,7 @@ class IMAP4:
         self.literal = _Authenticator(authobject).process
         typ, dat = self._simple_command('AUTHENTICATE', mech)
         if typ != 'OK':
-            raise self.error(dat[-1])
+            raise self.error(dat[-1].decode('utf-8', 'replace'))
         self.state = 'AUTH'
         return typ, dat
 
index f6fff44..e264391 100644 (file)
@@ -266,8 +266,8 @@ def find_module(name, path=None):
         raise TypeError("'name' must be a str, not {}".format(type(name)))
     elif not isinstance(path, (type(None), list)):
         # Backwards-compatibility
-        raise RuntimeError("'list' must be None or a list, "
-                           "not {}".format(type(name)))
+        raise RuntimeError("'path' must be None or a list, "
+                           "not {}".format(type(path)))
 
     if path is None:
         if is_builtin(name):
index 9788828..e54d691 100644 (file)
@@ -21,15 +21,22 @@ work. One should use importlib as the public-facing version of this module.
 # anything specified at the class level.
 
 # Bootstrap-related code ######################################################
-
-_CASE_INSENSITIVE_PLATFORMS = 'win', 'cygwin', 'darwin'
+_CASE_INSENSITIVE_PLATFORMS_STR_KEY = 'win',
+_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY = 'cygwin', 'darwin'
+_CASE_INSENSITIVE_PLATFORMS =  (_CASE_INSENSITIVE_PLATFORMS_BYTES_KEY
+                                + _CASE_INSENSITIVE_PLATFORMS_STR_KEY)
 
 
 def _make_relax_case():
     if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS):
+        if sys.platform.startswith(_CASE_INSENSITIVE_PLATFORMS_STR_KEY):
+            key = 'PYTHONCASEOK'
+        else:
+            key = b'PYTHONCASEOK'
+
         def _relax_case():
             """True if filenames must be checked case-insensitively."""
-            return b'PYTHONCASEOK' in _os.environ
+            return key in _os.environ
     else:
         def _relax_case():
             """True if filenames must be checked case-insensitively."""
@@ -223,6 +230,7 @@ _code_type = type(_write_atomic.__code__)
 #     Python 3.5b1  3330 (PEP 448: Additional Unpacking Generalizations)
 #     Python 3.5b2  3340 (fix dictionary display evaluation order #11205)
 #     Python 3.5b2  3350 (add GET_YIELD_FROM_ITER opcode #24400)
+#     Python 3.5.2  3351 (fix BUILD_MAP_UNPACK_WITH_CALL opcode #27286)
 #
 # MAGIC must change whenever the bytecode emitted by the compiler may no
 # longer be understood by older implementations of the eval loop (usually
@@ -231,7 +239,7 @@ _code_type = type(_write_atomic.__code__)
 # Whenever MAGIC_NUMBER is changed, the ranges in the magic_values array
 # in PC/launcher.c must also be updated.
 
-MAGIC_NUMBER = (3350).to_bytes(2, 'little') + b'\r\n'
+MAGIC_NUMBER = (3351).to_bytes(2, 'little') + b'\r\n'
 _RAW_MAGIC_NUMBER = int.from_bytes(MAGIC_NUMBER, 'little')  # For import.c
 
 _PYCACHE = '__pycache__'
index 4525b3f..e1fa07a 100644 (file)
@@ -241,7 +241,7 @@ class _LazyModule(types.ModuleType):
             if id(self) != id(sys.modules[original_name]):
                 msg = ('module object for {!r} substituted in sys.modules '
                        'during a lazy load')
-            raise ValueError(msg.format(original_name))
+                raise ValueError(msg.format(original_name))
         # Update after loading since that's what would happen in an eager
         # loading situation.
         self.__dict__.update(attrs_updated)
index e830eb6..6b9e0b0 100644 (file)
@@ -171,9 +171,8 @@ def isfunction(object):
 def isgeneratorfunction(object):
     """Return true if the object is a user-defined generator function.
 
-    Generator function objects provides same attributes as functions.
-
-    See help(isfunction) for attributes listing."""
+    Generator function objects provide the same attributes as functions.
+    See help(isfunction) for a list of attributes."""
     return bool((isfunction(object) or ismethod(object)) and
                 object.__code__.co_flags & CO_GENERATOR)
 
@@ -208,10 +207,10 @@ def iscoroutine(object):
     return isinstance(object, types.CoroutineType)
 
 def isawaitable(object):
-    """Return true is object can be passed to an ``await`` expression."""
+    """Return true if object can be passed to an ``await`` expression."""
     return (isinstance(object, types.CoroutineType) or
             isinstance(object, types.GeneratorType) and
-                object.gi_code.co_flags & CO_ITERABLE_COROUTINE or
+                bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
             isinstance(object, collections.abc.Awaitable))
 
 def istraceback(object):
@@ -1153,6 +1152,8 @@ def getargvalues(frame):
     return ArgInfo(args, varargs, varkw, frame.f_locals)
 
 def formatannotation(annotation, base_module=None):
+    if getattr(annotation, '__module__', None) == 'typing':
+        return repr(annotation).replace('typing.', '')
     if isinstance(annotation, type):
         if annotation.__module__ in ('builtins', base_module):
             return annotation.__qualname__
@@ -1415,7 +1416,7 @@ def getframeinfo(frame, context=1):
         except OSError:
             lines = index = None
         else:
-            start = max(start, 1)
+            start = max(start, 0)
             start = max(0, min(start, len(lines) - context))
             lines = lines[start:start+context]
             index = lineno - 1 - start
index 2612657..1118b0e 100644 (file)
@@ -152,7 +152,7 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
     ``default(obj)`` is a function that should return a serializable version
     of obj or raise TypeError. The default simply raises TypeError.
 
-    If *sort_keys* is ``True`` (default: ``False``), then the output of
+    If *sort_keys* is true (default: ``False``), then the output of
     dictionaries will be sorted by key.
 
     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
@@ -214,7 +214,7 @@ def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
     ``default(obj)`` is a function that should return a serializable version
     of obj or raise TypeError. The default simply raises TypeError.
 
-    If *sort_keys* is ``True`` (default: ``False``), then the output of
+    If *sort_keys* is true (default: ``False``), then the output of
     dictionaries will be sorted by key.
 
     To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
@@ -297,7 +297,7 @@ def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None,
     for JSON integers (e.g. float).
 
     ``parse_constant``, if specified, will be called with one of the
-    following strings: -Infinity, Infinity, NaN, null, true, false.
+    following strings: -Infinity, Infinity, NaN.
     This can be used to raise an exception if invalid JSON numbers
     are encountered.
 
index c954669..60503dd 100644 (file)
@@ -138,15 +138,26 @@ subscript: test | [test] ':' [test] [sliceop]
 sliceop: ':' [test]
 exprlist: (expr|star_expr) (',' (expr|star_expr))* [',']
 testlist: test (',' test)* [',']
-dictsetmaker: ( (test ':' test (comp_for | (',' test ':' test)* [','])) |
-                (test (comp_for | (',' test)* [','])) )
+dictsetmaker: ( ((test ':' test | '**' expr)
+                 (comp_for | (',' (test ':' test | '**' expr))* [','])) |
+                ((test | star_expr)
+                (comp_for | (',' (test | star_expr))* [','])) )
 
 classdef: 'class' NAME ['(' [arglist] ')'] ':' suite
 
-arglist: (argument ',')* (argument [',']
-                         |'*' test (',' argument)* [',' '**' test]
-                         |'**' test)
-argument: test [comp_for] | test '=' test  # Really [keyword '='] test
+arglist: argument (',' argument)* [',']
+
+# "test '=' test" is really "keyword '=' test", but we have no such token.
+# These need to be in a single rule to avoid grammar that is ambiguous
+# to our LL(1) parser. Even though 'test' includes '*expr' in star_expr,
+# we explicitly match '*' here, too, to give it proper precedence.
+# Illegal combinations and orderings are blocked in ast.c:
+# multiple (test comp_for) arguments are blocked; keyword unpackings
+# that precede iterable unpackings are blocked; etc.
+argument: ( test [comp_for] |
+            test '=' test |
+           '**' expr |
+           star_expr )
 
 comp_iter: comp_for | comp_if
 comp_for: 'for' exprlist 'in' testlist_safe [comp_iter]
index 1ce62fe..df581a4 100644 (file)
@@ -4,7 +4,6 @@
 """Base class for fixers (optional, but recommended)."""
 
 # Python imports
-import logging
 import itertools
 
 # Local imports
index 81a46dc..826ec8c 100644 (file)
@@ -34,6 +34,17 @@ class FixApply(fixer_base.BaseFix):
         func = results["func"]
         args = results["args"]
         kwds = results.get("kwds")
+        # I feel like we should be able to express this logic in the
+        # PATTERN above but I don't know how to do it so...
+        if args:
+            if args.type == self.syms.star_expr:
+                return  # Make no change.
+            if (args.type == self.syms.argument and
+                args.children[0].value == '**'):
+                return  # Make no change.
+        if kwds and (kwds.type == self.syms.argument and
+                     kwds.children[0].value == '**'):
+            return  # Make no change.
         prefix = node.prefix
         func = func.clone()
         if (func.type not in (token.NAME, syms.atom) and
diff --git a/Lib/lib2to3/fixes/fix_callable.py b/Lib/lib2to3/fixes/fix_callable.py
deleted file mode 100644 (file)
index 4c92b9c..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-# Copyright 2007 Google, Inc. All Rights Reserved.
-# Licensed to PSF under a Contributor Agreement.
-
-"""Fixer for callable().
-
-This converts callable(obj) into isinstance(obj, collections.Callable), adding a
-collections import if needed."""
-
-# Local imports
-from lib2to3 import fixer_base
-from lib2to3.fixer_util import Call, Name, String, Attr, touch_import
-
-class FixCallable(fixer_base.BaseFix):
-    BM_compatible = True
-
-    order = "pre"
-
-    # Ignore callable(*args) or use of keywords.
-    # Either could be a hint that the builtin callable() is not being used.
-    PATTERN = """
-    power< 'callable'
-           trailer< lpar='('
-                    ( not(arglist | argument<any '=' any>) func=any
-                      | func=arglist<(not argument<any '=' any>) any ','> )
-                    rpar=')' >
-           after=any*
-    >
-    """
-
-    def transform(self, node, results):
-        func = results['func']
-
-        touch_import(None, 'collections', node=node)
-
-        args = [func.clone(), String(', ')]
-        args.extend(Attr(Name('collections'), Name('Callable')))
-        return Call(Name('isinstance'), args, prefix=node.prefix)
index fb2973c..a852330 100644 (file)
@@ -25,6 +25,16 @@ class FixIntern(fixer_base.BaseFix):
     """
 
     def transform(self, node, results):
+        if results:
+            # I feel like we should be able to express this logic in the
+            # PATTERN above but I don't know how to do it so...
+            obj = results['obj']
+            if obj:
+                if obj.type == self.syms.star_expr:
+                    return  # Make no change.
+                if (obj.type == self.syms.argument and
+                    obj.children[0].value == '**'):
+                    return  # Make no change.
         names = ('sys', 'intern')
         new = ImportAndCall(node, results, names)
         touch_import(None, 'sys', node)
index 1855357..5bec7d5 100644 (file)
@@ -22,6 +22,16 @@ class FixReload(fixer_base.BaseFix):
     """
 
     def transform(self, node, results):
+        if results:
+            # I feel like we should be able to express this logic in the
+            # PATTERN above but I don't know how to do it so...
+            obj = results['obj']
+            if obj:
+                if obj.type == self.syms.star_expr:
+                    return  # Make no change.
+                if (obj.type == self.syms.argument and
+                    obj.children[0].value == '**'):
+                    return  # Make no change.
         names = ('imp', 'reload')
         new = ImportAndCall(node, results, names)
         touch_import(None, 'imp', node)
index 3ccc69d..a27b9cb 100644 (file)
@@ -106,16 +106,19 @@ class Driver(object):
         return self.parse_tokens(tokens, debug)
 
 
+def _generate_pickle_name(gt):
+    head, tail = os.path.splitext(gt)
+    if tail == ".txt":
+        tail = ""
+    return head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
+
+
 def load_grammar(gt="Grammar.txt", gp=None,
                  save=True, force=False, logger=None):
     """Load the grammar (maybe from a pickle)."""
     if logger is None:
         logger = logging.getLogger()
-    if gp is None:
-        head, tail = os.path.splitext(gt)
-        if tail == ".txt":
-            tail = ""
-        gp = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
+    gp = _generate_pickle_name(gt) if gp is None else gp
     if force or not _newer(gp, gt):
         logger.info("Generating grammar tables from %s", gt)
         g = pgen.generate_grammar(gt)
@@ -124,7 +127,7 @@ def load_grammar(gt="Grammar.txt", gp=None,
             try:
                 g.dump(gp)
             except OSError as e:
-                logger.info("Writing failed:"+str(e))
+                logger.info("Writing failed: %s", e)
     else:
         g = grammar.Grammar()
         g.load(gp)
index b4481d1..321e25e 100644 (file)
@@ -13,6 +13,7 @@ fallback token code OP, but the parser needs the actual token code.
 """
 
 # Python imports
+import collections
 import pickle
 
 # Local imports
@@ -85,9 +86,21 @@ class Grammar(object):
         self.start = 256
 
     def dump(self, filename):
-        """Dump the grammar tables to a pickle file."""
+        """Dump the grammar tables to a pickle file.
+
+        dump() recursively changes all dict to OrderedDict, so the pickled file
+        is not exactly the same as what was passed in to dump(). load() uses the
+        pickled file to create the tables, but  only changes OrderedDict to dict
+        at the top level; it does not recursively change OrderedDict to dict.
+        So, the loaded tables are different from the original tables that were
+        passed to load() in that some of the OrderedDict (from the pickled file)
+        are not changed back to dict. For parsing, this has no effect on
+        performance because OrderedDict uses dict's __getitem__ with nothing in
+        between.
+        """
         with open(filename, "wb") as f:
-            pickle.dump(self.__dict__, f, 2)
+            d = _make_deterministic(self.__dict__)
+            pickle.dump(d, f, 2)
 
     def load(self, filename):
         """Load the grammar tables from a pickle file."""
@@ -124,6 +137,17 @@ class Grammar(object):
         print("start", self.start)
 
 
+def _make_deterministic(top):
+    if isinstance(top, dict):
+        return collections.OrderedDict(
+            sorted(((k, _make_deterministic(v)) for k, v in top.items())))
+    if isinstance(top, list):
+        return [_make_deterministic(e) for e in top]
+    if isinstance(top, tuple):
+        return tuple(_make_deterministic(e) for e in top)
+    return top
+
+
 # Map from operator to number (since tokenize doesn't do this)
 
 opmap_raw = """
index 2c51eef..b0cbd16 100644 (file)
@@ -39,7 +39,7 @@ class ParserGenerator(object):
             states = []
             for state in dfa:
                 arcs = []
-                for label, next in state.arcs.items():
+                for label, next in sorted(state.arcs.items()):
                     arcs.append((self.make_label(c, label), dfa.index(next)))
                 if state.isfinal:
                     arcs.append((0, dfa.index(state)))
@@ -52,7 +52,7 @@ class ParserGenerator(object):
     def make_first(self, c, name):
         rawfirst = self.first[name]
         first = {}
-        for label in rawfirst:
+        for label in sorted(rawfirst):
             ilabel = self.make_label(c, label)
             ##assert ilabel not in first # XXX failed on <> ... !=
             first[ilabel] = 1
@@ -192,7 +192,7 @@ class ParserGenerator(object):
                 for label, next in nfastate.arcs:
                     if label is not None:
                         addclosure(next, arcs.setdefault(label, {}))
-            for label, nfaset in arcs.items():
+            for label, nfaset in sorted(arcs.items()):
                 for st in states:
                     if st.nfaset == nfaset:
                         break
@@ -222,7 +222,7 @@ class ParserGenerator(object):
         print("Dump of DFA for", name)
         for i, state in enumerate(dfa):
             print("  State", i, state.isfinal and "(final)" or "")
-            for label, next in state.arcs.items():
+            for label, next in sorted(state.arcs.items()):
                 print("    %s -> %d" % (label, dfa.index(next)))
 
     def simplify_dfa(self, dfa):
index 6f2d214..0897177 100644 (file)
@@ -11,13 +11,13 @@ from textwrap import dedent
 
 # Local imports
 from lib2to3 import pytree, refactor
-from lib2to3.pgen2 import driver
+from lib2to3.pgen2 import driver as pgen2_driver
 
 test_dir = os.path.dirname(__file__)
 proj_dir = os.path.normpath(os.path.join(test_dir, ".."))
 grammar_path = os.path.join(test_dir, "..", "Grammar.txt")
-grammar = driver.load_grammar(grammar_path)
-driver = driver.Driver(grammar, convert=pytree.convert)
+grammar = pgen2_driver.load_grammar(grammar_path)
+driver = pgen2_driver.Driver(grammar, convert=pytree.convert)
 
 def parse_string(string):
     return driver.parse_string(reformat(string), debug=True)
index 06b0033..640dcef 100644 (file)
@@ -260,6 +260,10 @@ class Test_apply(FixerTestCase):
         s = """apply(f, *args)"""
         self.unchanged(s)
 
+    def test_unchanged_6b(self):
+        s = """apply(f, **kwds)"""
+        self.unchanged(s)
+
     def test_unchanged_7(self):
         s = """apply(func=f, args=args, kwds=kwds)"""
         self.unchanged(s)
@@ -2920,98 +2924,6 @@ class Test_unicode(FixerTestCase):
         a = f + r"""r'\\\u20ac\U0001d121\\u20ac'"""
         self.check(b, a)
 
-class Test_callable(FixerTestCase):
-    fixer = "callable"
-
-    def test_prefix_preservation(self):
-        b = """callable(    x)"""
-        a = """import collections\nisinstance(    x, collections.Callable)"""
-        self.check(b, a)
-
-        b = """if     callable(x): pass"""
-        a = """import collections
-if     isinstance(x, collections.Callable): pass"""
-        self.check(b, a)
-
-    def test_callable_call(self):
-        b = """callable(x)"""
-        a = """import collections\nisinstance(x, collections.Callable)"""
-        self.check(b, a)
-
-    def test_global_import(self):
-        b = """
-def spam(foo):
-    callable(foo)"""[1:]
-        a = """
-import collections
-def spam(foo):
-    isinstance(foo, collections.Callable)"""[1:]
-        self.check(b, a)
-
-        b = """
-import collections
-def spam(foo):
-    callable(foo)"""[1:]
-        # same output if it was already imported
-        self.check(b, a)
-
-        b = """
-from collections import *
-def spam(foo):
-    callable(foo)"""[1:]
-        a = """
-from collections import *
-import collections
-def spam(foo):
-    isinstance(foo, collections.Callable)"""[1:]
-        self.check(b, a)
-
-        b = """
-do_stuff()
-do_some_other_stuff()
-assert callable(do_stuff)"""[1:]
-        a = """
-import collections
-do_stuff()
-do_some_other_stuff()
-assert isinstance(do_stuff, collections.Callable)"""[1:]
-        self.check(b, a)
-
-        b = """
-if isinstance(do_stuff, Callable):
-    assert callable(do_stuff)
-    do_stuff(do_stuff)
-    if not callable(do_stuff):
-        exit(1)
-    else:
-        assert callable(do_stuff)
-else:
-    assert not callable(do_stuff)"""[1:]
-        a = """
-import collections
-if isinstance(do_stuff, Callable):
-    assert isinstance(do_stuff, collections.Callable)
-    do_stuff(do_stuff)
-    if not isinstance(do_stuff, collections.Callable):
-        exit(1)
-    else:
-        assert isinstance(do_stuff, collections.Callable)
-else:
-    assert not isinstance(do_stuff, collections.Callable)"""[1:]
-        self.check(b, a)
-
-    def test_callable_should_not_change(self):
-        a = """callable(*x)"""
-        self.unchanged(a)
-
-        a = """callable(x, y)"""
-        self.unchanged(a)
-
-        a = """callable(x, kw=y)"""
-        self.unchanged(a)
-
-        a = """callable()"""
-        self.unchanged(a)
 
 class Test_filter(FixerTestCase):
     fixer = "filter"
index b533c01..e4a0194 100644 (file)
@@ -6,8 +6,6 @@ parts of the grammar we've changed, we also make sure we can parse the
 test_grammar.py files from both Python 2 and Python 3.
 """
 
-from __future__ import with_statement
-
 # Testing imports
 from . import support
 from .support import driver, test_dir
@@ -15,12 +13,15 @@ from test.support import verbose
 
 # Python imports
 import os
+import shutil
+import subprocess
 import sys
+import tempfile
 import unittest
 import warnings
-import subprocess
 
 # Local imports
+from lib2to3.pgen2 import driver as pgen2_driver
 from lib2to3.pgen2 import tokenize
 from ..pgen2.parse import ParseError
 from lib2to3.pygram import python_symbols as syms
@@ -35,6 +36,71 @@ class TestDriver(support.TestCase):
         self.assertEqual(t.children[1].children[0].type, syms.print_stmt)
 
 
+class TestPgen2Caching(support.TestCase):
+    def test_load_grammar_from_txt_file(self):
+        pgen2_driver.load_grammar(support.grammar_path, save=False, force=True)
+
+    def test_load_grammar_from_pickle(self):
+        # Make a copy of the grammar file in a temp directory we are
+        # guaranteed to be able to write to.
+        tmpdir = tempfile.mkdtemp()
+        try:
+            grammar_copy = os.path.join(
+                    tmpdir, os.path.basename(support.grammar_path))
+            shutil.copy(support.grammar_path, grammar_copy)
+            pickle_name = pgen2_driver._generate_pickle_name(grammar_copy)
+
+            pgen2_driver.load_grammar(grammar_copy, save=True, force=True)
+            self.assertTrue(os.path.exists(pickle_name))
+
+            os.unlink(grammar_copy)  # Only the pickle remains...
+            pgen2_driver.load_grammar(grammar_copy, save=False, force=False)
+        finally:
+            shutil.rmtree(tmpdir)
+
+    @unittest.skipIf(sys.executable is None, 'sys.executable required')
+    def test_load_grammar_from_subprocess(self):
+        tmpdir = tempfile.mkdtemp()
+        tmpsubdir = os.path.join(tmpdir, 'subdir')
+        try:
+            os.mkdir(tmpsubdir)
+            grammar_base = os.path.basename(support.grammar_path)
+            grammar_copy = os.path.join(tmpdir, grammar_base)
+            grammar_sub_copy = os.path.join(tmpsubdir, grammar_base)
+            shutil.copy(support.grammar_path, grammar_copy)
+            shutil.copy(support.grammar_path, grammar_sub_copy)
+            pickle_name = pgen2_driver._generate_pickle_name(grammar_copy)
+            pickle_sub_name = pgen2_driver._generate_pickle_name(
+                     grammar_sub_copy)
+            self.assertNotEqual(pickle_name, pickle_sub_name)
+
+            # Generate a pickle file from this process.
+            pgen2_driver.load_grammar(grammar_copy, save=True, force=True)
+            self.assertTrue(os.path.exists(pickle_name))
+
+            # Generate a new pickle file in a subprocess with a most likely
+            # different hash randomization seed.
+            sub_env = dict(os.environ)
+            sub_env['PYTHONHASHSEED'] = 'random'
+            subprocess.check_call(
+                    [sys.executable, '-c', """
+from lib2to3.pgen2 import driver as pgen2_driver
+pgen2_driver.load_grammar(%r, save=True, force=True)
+                    """ % (grammar_sub_copy,)],
+                    env=sub_env)
+            self.assertTrue(os.path.exists(pickle_sub_name))
+
+            with open(pickle_name, 'rb') as pickle_f_1, \
+                    open(pickle_sub_name, 'rb') as pickle_f_2:
+                self.assertEqual(
+                    pickle_f_1.read(), pickle_f_2.read(),
+                    msg='Grammar caches generated using different hash seeds'
+                    ' were not identical.')
+        finally:
+            shutil.rmtree(tmpdir)
+
+
+
 class GrammarTest(support.TestCase):
     def validate(self, code):
         support.parse_string(code)
@@ -142,6 +208,41 @@ class TestRaiseChanges(GrammarTest):
         self.invalid_syntax("raise E from")
 
 
+# Modelled after Lib/test/test_grammar.py:TokenTests.test_funcdef issue2292
+# and Lib/test/text_parser.py test_list_displays, test_set_displays,
+# test_dict_displays, test_argument_unpacking, ... changes.
+class TestUnpackingGeneralizations(GrammarTest):
+    def test_mid_positional_star(self):
+        self.validate("""func(1, *(2, 3), 4)""")
+
+    def test_double_star_dict_literal(self):
+        self.validate("""func(**{'eggs':'scrambled', 'spam':'fried'})""")
+
+    def test_double_star_dict_literal_after_keywords(self):
+        self.validate("""func(spam='fried', **{'eggs':'scrambled'})""")
+
+    def test_list_display(self):
+        self.validate("""[*{2}, 3, *[4]]""")
+
+    def test_set_display(self):
+        self.validate("""{*{2}, 3, *[4]}""")
+
+    def test_dict_display_1(self):
+        self.validate("""{**{}}""")
+
+    def test_dict_display_2(self):
+        self.validate("""{**{}, 3:4, **{5:6, 7:8}}""")
+
+    def test_argument_unpacking_1(self):
+        self.validate("""f(a, *b, *c, d)""")
+
+    def test_argument_unpacking_2(self):
+        self.validate("""f(**a, **b)""")
+
+    def test_argument_unpacking_3(self):
+        self.validate("""f(2, *a, *b, **b, **c, **d)""")
+
+
 # Adapted from Python 3's Lib/test/test_grammar.py:GrammarTests.testFuncdef
 class TestFunctionAnnotations(GrammarTest):
     def test_1(self):
index f30c1e8..8563001 100644 (file)
@@ -9,6 +9,7 @@ import os
 import codecs
 import operator
 import io
+import re
 import tempfile
 import shutil
 import unittest
@@ -226,8 +227,8 @@ from __future__ import print_function"""
                                     actually_write=False)
         # Testing that it logged this message when write=False was passed is
         # sufficient to see that it did not bail early after "No changes".
-        message_regex = r"Not writing changes to .*%s%s" % (
-                os.sep, os.path.basename(test_file))
+        message_regex = r"Not writing changes to .*%s" % \
+                re.escape(os.sep + os.path.basename(test_file))
         for message in debug_messages:
             if "Not writing changes" in message:
                 self.assertRegex(message, message_regex)
index a7bd890..22744e1 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright 2001-2015 by Vinay Sajip. All Rights Reserved.
+# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved.
 #
 # Permission to use, copy, modify, and distribute this software and its
 # documentation for any purpose and without fee is hereby granted,
@@ -18,7 +18,7 @@
 Logging package for Python. Based on PEP 282 and comments thereto in
 comp.lang.python.
 
-Copyright (C) 2001-2015 Vinay Sajip. All Rights Reserved.
+Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved.
 
 To use, simply 'import logging' and log away!
 """
@@ -129,8 +129,9 @@ def getLevelName(level):
 
     Otherwise, the string "Level %s" % level is returned.
     """
-    # See Issue #22386 for the reason for this convoluted expression
-    return _levelToName.get(level, _nameToLevel.get(level, ("Level %s" % level)))
+    # See Issues #22386 and #27937 for why it's this way
+    return (_levelToName.get(level) or _nameToLevel.get(level) or
+            "Level %s" % level)
 
 def addLevelName(level, levelName):
     """
index c9f8217..c39a56f 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright 2001-2015 by Vinay Sajip. All Rights Reserved.
+# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved.
 #
 # Permission to use, copy, modify, and distribute this software and its
 # documentation for any purpose and without fee is hereby granted,
@@ -18,7 +18,7 @@
 Additional handlers for the logging package for Python. The core package is
 based on PEP 282 and comments thereto in comp.lang.python.
 
-Copyright (C) 2001-2015 Vinay Sajip. All Rights Reserved.
+Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved.
 
 To use, simply 'import logging.handlers' and log away!
 """
@@ -1366,7 +1366,6 @@ if threading:
             """
             self.queue = queue
             self.handlers = handlers
-            self._stop = threading.Event()
             self._thread = None
             self.respect_handler_level = respect_handler_level
 
@@ -1387,7 +1386,7 @@ if threading:
             LogRecords to process.
             """
             self._thread = t = threading.Thread(target=self._monitor)
-            t.setDaemon(True)
+            t.daemon = True
             t.start()
 
         def prepare(self , record):
@@ -1426,20 +1425,9 @@ if threading:
             """
             q = self.queue
             has_task_done = hasattr(q, 'task_done')
-            while not self._stop.isSet():
-                try:
-                    record = self.dequeue(True)
-                    if record is self._sentinel:
-                        break
-                    self.handle(record)
-                    if has_task_done:
-                        q.task_done()
-                except queue.Empty:
-                    pass
-            # There might still be records in the queue.
             while True:
                 try:
-                    record = self.dequeue(False)
+                    record = self.dequeue(True)
                     if record is self._sentinel:
                         break
                     self.handle(record)
@@ -1466,7 +1454,6 @@ if threading:
             Note that if you don't call this before your application exits, there
             may be some records still left on the queue, which won't be processed.
             """
-            self._stop.set()
             self.enqueue_sentinel()
             self._thread.join()
             self._thread = None
index 97e3035..bd0fc09 100644 (file)
@@ -1,9 +1,19 @@
 """Mailcap file handling.  See RFC 1524."""
 
 import os
+import warnings
 
 __all__ = ["getcaps","findmatch"]
 
+
+def lineno_sort_key(entry):
+    # Sort in ascending order, with unspecified entries at the end
+    if 'lineno' in entry:
+        return 0, entry['lineno']
+    else:
+        return 1, 0
+
+
 # Part 1: top-level interface.
 
 def getcaps():
@@ -17,13 +27,14 @@ def getcaps():
 
     """
     caps = {}
+    lineno = 0
     for mailcap in listmailcapfiles():
         try:
             fp = open(mailcap, 'r')
         except OSError:
             continue
         with fp:
-            morecaps = readmailcapfile(fp)
+            morecaps, lineno = _readmailcapfile(fp, lineno)
         for key, value in morecaps.items():
             if not key in caps:
                 caps[key] = value
@@ -49,8 +60,15 @@ def listmailcapfiles():
 
 
 # Part 2: the parser.
-
 def readmailcapfile(fp):
+    """Read a mailcap file and return a dictionary keyed by MIME type."""
+    warnings.warn('readmailcapfile is deprecated, use getcaps instead',
+                  DeprecationWarning, 2)
+    caps, _ = _readmailcapfile(fp, None)
+    return caps
+
+
+def _readmailcapfile(fp, lineno):
     """Read a mailcap file and return a dictionary keyed by MIME type.
 
     Each MIME type is mapped to an entry consisting of a list of
@@ -76,6 +94,9 @@ def readmailcapfile(fp):
         key, fields = parseline(line)
         if not (key and fields):
             continue
+        if lineno is not None:
+            fields['lineno'] = lineno
+            lineno += 1
         # Normalize the key
         types = key.split('/')
         for j in range(len(types)):
@@ -86,7 +107,7 @@ def readmailcapfile(fp):
             caps[key].append(fields)
         else:
             caps[key] = [fields]
-    return caps
+    return caps, lineno
 
 def parseline(line):
     """Parse one entry in a mailcap file and return a dictionary.
@@ -165,6 +186,7 @@ def lookup(caps, MIMEtype, key=None):
         entries = entries + caps[MIMEtype]
     if key is not None:
         entries = [e for e in entries if key in e]
+    entries = sorted(entries, key=lineno_sort_key)
     return entries
 
 def subst(field, MIMEtype, filename, plist=[]):
index 63849f9..115d4bf 100644 (file)
@@ -195,7 +195,7 @@ class BaseContext(object):
     def get_start_method(self, allow_none=False):
         return self._name
 
-    def set_start_method(self, method=None):
+    def set_start_method(self, method, force=False):
         raise ValueError('cannot set start method of concrete context')
 
     def _check_available(self):
index c559b55..b175470 100644 (file)
@@ -275,7 +275,7 @@ class Server(object):
                 try:
                     send(msg)
                 except Exception as e:
-                    send(('#UNSERIALIZABLE', repr(msg)))
+                    send(('#UNSERIALIZABLE', format_exc()))
             except Exception as e:
                 util.info('exception in thread serving %r',
                         threading.current_thread().name)
index 4d76951..392c159 100644 (file)
@@ -218,7 +218,7 @@ def prepare(data):
         process.ORIGINAL_DIR = data['orig_dir']
 
     if 'start_method' in data:
-        set_start_method(data['start_method'])
+        set_start_method(data['start_method'], force=True)
 
     if 'init_main_from_name' in data:
         _fixup_main_from_name(data['init_main_from_name'])
index b4c651d..011285e 100644 (file)
--- a/Lib/os.py
+++ b/Lib/os.py
@@ -537,13 +537,13 @@ if {open, stat} <= supports_dir_fd and {listdir, stat} <= supports_fd:
                     dirs.append(name)
                 else:
                     nondirs.append(name)
-            except FileNotFoundError:
+            except OSError:
                 try:
                     # Add dangling symlinks, ignore disappeared files
                     if st.S_ISLNK(stat(name, dir_fd=topfd, follow_symlinks=False)
                                 .st_mode):
                         nondirs.append(name)
-                except FileNotFoundError:
+                except OSError:
                     continue
 
         if topdown:
index b11ac0a..4797265 100755 (executable)
@@ -134,6 +134,8 @@ line_prefix = '\n-> '   # Probably a better default
 
 class Pdb(bdb.Bdb, cmd.Cmd):
 
+    _previous_sigint_handler = None
+
     def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
                  nosigint=False):
         bdb.Bdb.__init__(self, skip=skip)
@@ -187,8 +189,6 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         self.message("\nProgram interrupted. (Use 'cont' to resume).")
         self.set_step()
         self.set_trace(frame)
-        # restore previous signal handler
-        signal.signal(signal.SIGINT, self._previous_sigint_handler)
 
     def reset(self):
         bdb.Bdb.reset(self)
@@ -337,6 +337,10 @@ class Pdb(bdb.Bdb, cmd.Cmd):
                                  (expr, newvalue, oldvalue))
 
     def interaction(self, frame, traceback):
+        # Restore the previous signal handler at the Pdb prompt.
+        if Pdb._previous_sigint_handler:
+            signal.signal(signal.SIGINT, Pdb._previous_sigint_handler)
+            Pdb._previous_sigint_handler = None
         if self.setup(frame, traceback):
             # no interaction desired at this time (happens if .pdbrc contains
             # a command like "continue")
@@ -1037,7 +1041,7 @@ class Pdb(bdb.Bdb, cmd.Cmd):
         """
         if not self.nosigint:
             try:
-                self._previous_sigint_handler = \
+                Pdb._previous_sigint_handler = \
                     signal.signal(signal.SIGINT, self.sigint_handler)
             except ValueError:
                 # ValueError happens when do_continue() is invoked from
index 7760425..040ecb2 100644 (file)
@@ -529,7 +529,11 @@ class _Pickler:
             self.save(pid, save_persistent_id=False)
             self.write(BINPERSID)
         else:
-            self.write(PERSID + str(pid).encode("ascii") + b'\n')
+            try:
+                self.write(PERSID + str(pid).encode("ascii") + b'\n')
+            except UnicodeEncodeError:
+                raise PicklingError(
+                    "persistent IDs in protocol 0 must be ASCII strings")
 
     def save_reduce(self, func, args, state=None, listitems=None,
                     dictitems=None, obj=None):
@@ -1075,7 +1079,11 @@ class _Unpickler:
     dispatch[FRAME[0]] = load_frame
 
     def load_persid(self):
-        pid = self.readline()[:-1].decode("ascii")
+        try:
+            pid = self.readline()[:-1].decode("ascii")
+        except UnicodeDecodeError:
+            raise UnpicklingError(
+                "persistent IDs in protocol 0 must be ASCII strings")
         self.append(self.persistent_load(pid))
     dispatch[PERSID[0]] = load_persid
 
index 97726a9..81d418d 100644 (file)
@@ -45,7 +45,7 @@ def read_code(stream):
 
 
 def walk_packages(path=None, prefix='', onerror=None):
-    """Yields (module_loader, name, ispkg) for all modules recursively
+    """Yields (module_finder, name, ispkg) 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
@@ -102,7 +102,7 @@ def walk_packages(path=None, prefix='', onerror=None):
 
 
 def iter_modules(path=None, prefix=''):
-    """Yields (module_loader, name, ispkg) for all submodules on path,
+    """Yields (module_finder, name, ispkg) 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
@@ -184,10 +184,10 @@ def _import_imp():
         imp = importlib.import_module('imp')
 
 class ImpImporter:
-    """PEP 302 Importer that wraps Python's "classic" import algorithm
+    """PEP 302 Finder that wraps Python's "classic" import algorithm
 
-    ImpImporter(dirname) produces a PEP 302 importer that searches that
-    directory.  ImpImporter(None) produces a PEP 302 importer that searches
+    ImpImporter(dirname) produces a PEP 302 finder that searches that
+    directory.  ImpImporter(None) produces a PEP 302 finder that searches
     the current sys.path, plus any modules that are frozen or built-in.
 
     Note that ImpImporter does not currently support being used by placement
@@ -395,9 +395,9 @@ except ImportError:
 
 
 def get_importer(path_item):
-    """Retrieve a PEP 302 importer for the given path item
+    """Retrieve a finder for the given path item
 
-    The returned importer is cached in sys.path_importer_cache
+    The returned finder is cached in sys.path_importer_cache
     if it was newly created by a path hook.
 
     The cache (or part of it) can be cleared manually if a
@@ -419,16 +419,16 @@ def get_importer(path_item):
 
 
 def iter_importers(fullname=""):
-    """Yield PEP 302 importers for the given module name
+    """Yield finders for the given module name
 
-    If fullname contains a '.', the importers will be for the package
+    If fullname contains a '.', the finders will be for the package
     containing fullname, otherwise they will be all registered top level
-    importers (i.e. those on both sys.meta_path and sys.path_hooks).
+    finders (i.e. those on both sys.meta_path and sys.path_hooks).
 
     If the named module is in a package, that package is imported as a side
     effect of invoking this function.
 
-    If no module name is specified, all top level importers are produced.
+    If no module name is specified, all top level finders are produced.
     """
     if fullname.startswith('.'):
         msg = "Relative module name {!r} not supported".format(fullname)
@@ -448,7 +448,7 @@ def iter_importers(fullname=""):
 
 
 def get_loader(module_or_name):
-    """Get a PEP 302 "loader" object for module_or_name
+    """Get a "loader" object for module_or_name
 
     Returns None if the module cannot be found or imported.
     If the named module is not already imported, its containing package
@@ -472,7 +472,7 @@ def get_loader(module_or_name):
 
 
 def find_loader(fullname):
-    """Find a PEP 302 "loader" object for fullname
+    """Find a "loader" object for fullname
 
     This is a backwards compatibility wrapper around
     importlib.util.find_spec that converts most failures to ImportError
index d58494c..3e726a7 100755 (executable)
@@ -61,7 +61,7 @@
 #            though
 #    0.5.2 - fixed uname() to return '' instead of 'unknown' in all
 #            return values (the system uname command tends to return
-#            'unknown' instead of just leaving the field emtpy)
+#            'unknown' instead of just leaving the field empty)
 #    0.5.1 - included code for slackware dist; added exception handlers
 #            to cover up situations where platforms don't have os.popen
 #            (e.g. Mac) or fail on socket.gethostname(); fixed libc
@@ -498,65 +498,6 @@ _WIN32_SERVER_RELEASES = {
     (6, None): "post2012ServerR2",
 }
 
-def _get_real_winver(maj, min, build):
-    if maj < 6 or (maj == 6 and min < 2):
-        return maj, min, build
-
-    from ctypes import (c_buffer, POINTER, byref, create_unicode_buffer,
-                        Structure, WinDLL)
-    from ctypes.wintypes import DWORD, HANDLE
-
-    class VS_FIXEDFILEINFO(Structure):
-        _fields_ = [
-            ("dwSignature", DWORD),
-            ("dwStrucVersion", DWORD),
-            ("dwFileVersionMS", DWORD),
-            ("dwFileVersionLS", DWORD),
-            ("dwProductVersionMS", DWORD),
-            ("dwProductVersionLS", DWORD),
-            ("dwFileFlagsMask", DWORD),
-            ("dwFileFlags", DWORD),
-            ("dwFileOS", DWORD),
-            ("dwFileType", DWORD),
-            ("dwFileSubtype", DWORD),
-            ("dwFileDateMS", DWORD),
-            ("dwFileDateLS", DWORD),
-        ]
-
-    kernel32 = WinDLL('kernel32')
-    version = WinDLL('version')
-
-    # We will immediately double the length up to MAX_PATH, but the
-    # path may be longer, so we retry until the returned string is
-    # shorter than our buffer.
-    name_len = actual_len = 130
-    while actual_len == name_len:
-        name_len *= 2
-        name = create_unicode_buffer(name_len)
-        actual_len = kernel32.GetModuleFileNameW(HANDLE(kernel32._handle),
-                                                 name, len(name))
-        if not actual_len:
-            return maj, min, build
-
-    size = version.GetFileVersionInfoSizeW(name, None)
-    if not size:
-        return maj, min, build
-
-    ver_block = c_buffer(size)
-    if (not version.GetFileVersionInfoW(name, None, size, ver_block) or
-        not ver_block):
-        return maj, min, build
-
-    pvi = POINTER(VS_FIXEDFILEINFO)()
-    if not version.VerQueryValueW(ver_block, "", byref(pvi), byref(DWORD())):
-        return maj, min, build
-
-    maj = pvi.contents.dwProductVersionMS >> 16
-    min = pvi.contents.dwProductVersionMS & 0xFFFF
-    build = pvi.contents.dwProductVersionLS >> 16
-
-    return maj, min, build
-
 def win32_ver(release='', version='', csd='', ptype=''):
     try:
         from sys import getwindowsversion
@@ -568,7 +509,7 @@ def win32_ver(release='', version='', csd='', ptype=''):
         from _winreg import OpenKeyEx, QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE
 
     winver = getwindowsversion()
-    maj, min, build = _get_real_winver(*winver[:3])
+    maj, min, build = winver._platform_version or winver[:3]
     version = '{0}.{1}.{2}'.format(maj, min, build)
 
     release = (_WIN32_CLIENT_RELEASES.get((maj, min)) or
@@ -586,7 +527,7 @@ def win32_ver(release='', version='', csd='', ptype=''):
                 csd = 'SP' + csd[13:]
 
     # VER_NT_SERVER = 3
-    if getattr(winver, 'product', None) == 3:
+    if getattr(winver, 'product_type', None) == 3:
         release = (_WIN32_SERVER_RELEASES.get((maj, min)) or
                    _WIN32_SERVER_RELEASES.get((maj, None)) or
                    release)
index b66639c..2502b39 100644 (file)
@@ -918,7 +918,7 @@ class _BinaryPlistWriter (object):
                 self._write_size(0x50, len(value))
             except UnicodeEncodeError:
                 t = value.encode('utf-16be')
-                self._write_size(0x60, len(value))
+                self._write_size(0x60, len(t) // 2)
 
             self._fp.write(t)
 
index 7bb4d59..d9f3f99 100644 (file)
@@ -193,6 +193,7 @@ def ismount(path):
         parent = join(path, b'..')
     else:
         parent = join(path, '..')
+    parent = realpath(parent)
     try:
         s2 = os.lstat(parent)
     except OSError:
index e1ec355..d861413 100644 (file)
@@ -574,7 +574,10 @@ if __name__ == '__main__':
 
         def do_add(self, line):
             if self.stats:
-                self.stats.add(line)
+                try:
+                    self.stats.add(line)
+                except IOError as e:
+                    print("Failed to load statistics for %s: %s" % (line, e), file=self.stream)
             else:
                 print("No statistics object is loaded.", file=self.stream)
             return 0
index 3ca08c9..0d0d0ab 100755 (executable)
@@ -28,7 +28,7 @@ to a file named "<name>.html".
 
 Module docs for core modules are assumed to be in
 
-    http://docs.python.org/X.Y/library/
+    https://docs.python.org/X.Y/library/
 
 This can be overridden by setting the PYTHONDOCS environment variable
 to a different URL or to a local directory containing the Library
@@ -395,6 +395,7 @@ class Doc:
 
         docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS)
 
+        basedir = os.path.normcase(basedir)
         if (isinstance(object, type(os)) and
             (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
                                  'marshal', 'posix', 'signal', 'sys',
@@ -402,7 +403,7 @@ class Doc:
              (file.startswith(basedir) and
               not file.startswith(os.path.join(basedir, 'site-packages')))) and
             object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
-            if docloc.startswith("http://"):
+            if docloc.startswith(("http://", "https://")):
                 docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__.lower())
             else:
                 docloc = os.path.join(docloc, object.__name__.lower() + ".html")
index d6f1366..141a999 100644 (file)
@@ -1,5 +1,5 @@
 # -*- coding: utf-8 -*-
-# Autogenerated by Sphinx on Sat Jun 25 14:08:44 2016
+# Autogenerated by Sphinx on Sun Jan  1 22:05:59 2017
 topics = {'assert': u'\nThe "assert" statement\n**********************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n   assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, "assert expression", is equivalent to\n\n   if __debug__:\n       if not expression: raise AssertionError\n\nThe extended form, "assert expression1, expression2", is equivalent to\n\n   if __debug__:\n       if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that "__debug__" and "AssertionError" refer\nto the built-in variables with those names.  In the current\nimplementation, the built-in variable "__debug__" is "True" under\nnormal circumstances, "False" when optimization is requested (command\nline option -O).  The current code generator emits no code for an\nassert statement when optimization is requested at compile time.  Note\nthat it is unnecessary to include the source code for the expression\nthat failed in the error message; it will be displayed as part of the\nstack trace.\n\nAssignments to "__debug__" are illegal.  The value for the built-in\nvariable is determined when the interpreter starts.\n',
  'assignment': u'\nAssignment statements\n*********************\n\nAssignment statements are used to (re)bind names to values and to\nmodify attributes or items of mutable objects:\n\n   assignment_stmt ::= (target_list "=")+ (starred_expression | yield_expression)\n   target_list     ::= target ("," target)* [","]\n   target          ::= identifier\n              | "(" target_list ")"\n              | "[" [target_list] "]"\n              | attributeref\n              | subscription\n              | slicing\n              | "*" target\n\n(See section *Primaries* for the syntax definitions for\n*attributeref*, *subscription*, and *slicing*.)\n\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\n\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable.  The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section *The standard type\nhierarchy*).\n\nAssignment of an object to a target list, optionally enclosed in\nparentheses or square brackets, is recursively defined as follows.\n\n* If the target list is empty: The object must also be an empty\n  iterable.\n\n* If the target list is a single target in parentheses: The object\n  is assigned to that target.\n\n* If the target list is a comma-separated list of targets, or a\n  single target in square brackets: The object must be an iterable\n  with the same number of items as there are targets in the target\n  list, and the items are assigned, from left to right, to the\n  corresponding targets.\n\n  * If the target list contains one target prefixed with an\n    asterisk, called a "starred" target: The object must be an\n    iterable with at least as many items as there are targets in the\n    target list, minus one.  The first items of the iterable are\n    assigned, from left to right, to the targets before the starred\n    target.  The final items of the iterable are assigned to the\n    targets after the starred target.  A list of the remaining items\n    in the iterable is then assigned to the starred target (the list\n    can be empty).\n\n  * Else: The object must be an iterable with the same number of\n    items as there are targets in the target list, and the items are\n    assigned, from left to right, to the corresponding targets.\n\nAssignment of an object to a single target is recursively defined as\nfollows.\n\n* If the target is an identifier (name):\n\n  * If the name does not occur in a "global" or "nonlocal" statement\n    in the current code block: the name is bound to the object in the\n    current local namespace.\n\n  * Otherwise: the name is bound to the object in the global\n    namespace or the outer namespace determined by "nonlocal",\n    respectively.\n\n  The name is rebound if it was already bound.  This may cause the\n  reference count for the object previously bound to the name to reach\n  zero, causing the object to be deallocated and its destructor (if it\n  has one) to be called.\n\n* If the target is an attribute reference: The primary expression in\n  the reference is evaluated.  It should yield an object with\n  assignable attributes; if this is not the case, "TypeError" is\n  raised.  That object is then asked to assign the assigned object to\n  the given attribute; if it cannot perform the assignment, it raises\n  an exception (usually but not necessarily "AttributeError").\n\n  Note: If the object is a class instance and the attribute reference\n  occurs on both sides of the assignment operator, the RHS expression,\n  "a.x" can access either an instance attribute or (if no instance\n  attribute exists) a class attribute.  The LHS target "a.x" is always\n  set as an instance attribute, creating it if necessary.  Thus, the\n  two occurrences of "a.x" do not necessarily refer to the same\n  attribute: if the RHS expression refers to a class attribute, the\n  LHS creates a new instance attribute as the target of the\n  assignment:\n\n     class Cls:\n         x = 3             # class variable\n     inst = Cls()\n     inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3\n\n  This description does not necessarily apply to descriptor\n  attributes, such as properties created with "property()".\n\n* If the target is a subscription: The primary expression in the\n  reference is evaluated.  It should yield either a mutable sequence\n  object (such as a list) or a mapping object (such as a dictionary).\n  Next, the subscript expression is evaluated.\n\n  If the primary is a mutable sequence object (such as a list), the\n  subscript must yield an integer.  If it is negative, the sequence\'s\n  length is added to it.  The resulting value must be a nonnegative\n  integer less than the sequence\'s length, and the sequence is asked\n  to assign the assigned object to its item with that index.  If the\n  index is out of range, "IndexError" is raised (assignment to a\n  subscripted sequence cannot add new items to a list).\n\n  If the primary is a mapping object (such as a dictionary), the\n  subscript must have a type compatible with the mapping\'s key type,\n  and the mapping is then asked to create a key/datum pair which maps\n  the subscript to the assigned object.  This can either replace an\n  existing key/value pair with the same key value, or insert a new\n  key/value pair (if no key with the same value existed).\n\n  For user-defined objects, the "__setitem__()" method is called with\n  appropriate arguments.\n\n* If the target is a slicing: The primary expression in the\n  reference is evaluated.  It should yield a mutable sequence object\n  (such as a list).  The assigned object should be a sequence object\n  of the same type.  Next, the lower and upper bound expressions are\n  evaluated, insofar they are present; defaults are zero and the\n  sequence\'s length.  The bounds should evaluate to integers. If\n  either bound is negative, the sequence\'s length is added to it.  The\n  resulting bounds are clipped to lie between zero and the sequence\'s\n  length, inclusive.  Finally, the sequence object is asked to replace\n  the slice with the items of the assigned sequence.  The length of\n  the slice may be different from the length of the assigned sequence,\n  thus changing the length of the target sequence, if the target\n  sequence allows it.\n\n**CPython implementation detail:** In the current implementation, the\nsyntax for targets is taken to be the same as for expressions, and\ninvalid syntax is rejected during the code generation phase, causing\nless detailed error messages.\n\nAlthough the definition of assignment implies that overlaps between\nthe left-hand side and the right-hand side are \'simultaneous\' (for\nexample "a, b = b, a" swaps two variables), overlaps *within* the\ncollection of assigned-to variables occur left-to-right, sometimes\nresulting in confusion.  For instance, the following program prints\n"[0, 2]":\n\n   x = [0, 1]\n   i = 0\n   i, x[i] = 1, 2         # i is updated, then x[i] is updated\n   print(x)\n\nSee also: **PEP 3132** - Extended Iterable Unpacking\n\n     The specification for the "*target" feature.\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n   augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n   augtarget                 ::= identifier | attributeref | subscription | slicing\n   augop                     ::= "+=" | "-=" | "*=" | "@=" | "/=" | "//=" | "%=" | "**="\n             | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions of the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like "x += 1" can be rewritten as\n"x = x + 1" to achieve a similar, but not exactly equal effect. In the\naugmented version, "x" is only evaluated once. Also, when possible,\nthe actual operation is performed *in-place*, meaning that rather than\ncreating a new object and assigning that to the target, the old object\nis modified instead.\n\nUnlike normal assignments, augmented assignments evaluate the left-\nhand side *before* evaluating the right-hand side.  For example, "a[i]\n+= f(x)" first looks-up "a[i]", then it evaluates "f(x)" and performs\nthe addition, and lastly, it writes the result back to "a[i]".\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n',
  'atom-identifiers': u'\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name.  See section\n*Identifiers and keywords* for lexical definition and section *Naming\nand binding* for documentation of naming and binding.\n\nWhen the name is bound to an object, evaluation of the atom yields\nthat object. When a name is not bound, an attempt to evaluate it\nraises a "NameError" exception.\n\n**Private name mangling:** When an identifier that textually occurs in\na class definition begins with two or more underscore characters and\ndoes not end in two or more underscores, it is considered a *private\nname* of that class. Private names are transformed to a longer form\nbefore code is generated for them.  The transformation inserts the\nclass name, with leading underscores removed and a single underscore\ninserted, in front of the name.  For example, the identifier "__spam"\noccurring in a class named "Ham" will be transformed to "_Ham__spam".\nThis transformation is independent of the syntactical context in which\nthe identifier is used.  If the transformed name is extremely long\n(longer than 255 characters), implementation defined truncation may\nhappen. If the class name consists only of underscores, no\ntransformation is done.\n',
@@ -16,15 +16,15 @@ topics = {'assert': u'\nThe "assert" statement\n**********************\n\nAssert
  'booleans': u'\nBoolean operations\n******************\n\n   or_test  ::= and_test | or_test "or" and_test\n   and_test ::= not_test | and_test "and" not_test\n   not_test ::= comparison | "not" not_test\n\nIn the context of Boolean operations, and also when expressions are\nused by control flow statements, the following values are interpreted\nas false: "False", "None", numeric zero of all types, and empty\nstrings and containers (including strings, tuples, lists,\ndictionaries, sets and frozensets).  All other values are interpreted\nas true.  User-defined objects can customize their truth value by\nproviding a "__bool__()" method.\n\nThe operator "not" yields "True" if its argument is false, "False"\notherwise.\n\nThe expression "x and y" first evaluates *x*; if *x* is false, its\nvalue is returned; otherwise, *y* is evaluated and the resulting value\nis returned.\n\nThe expression "x or y" first evaluates *x*; if *x* is true, its value\nis returned; otherwise, *y* is evaluated and the resulting value is\nreturned.\n\n(Note that neither "and" nor "or" restrict the value and type they\nreturn to "False" and "True", but rather return the last evaluated\nargument.  This is sometimes useful, e.g., if "s" is a string that\nshould be replaced by a default value if it is empty, the expression\n"s or \'foo\'" yields the desired value.  Because "not" has to create a\nnew value, it returns a boolean value regardless of the type of its\nargument (for example, "not \'foo\'" produces "False" rather than "\'\'".)\n',
  'break': u'\nThe "break" statement\n*********************\n\n   break_stmt ::= "break"\n\n"break" may only occur syntactically nested in a "for" or "while"\nloop, but not nested in a function or class definition within that\nloop.\n\nIt terminates the nearest enclosing loop, skipping the optional "else"\nclause if the loop has one.\n\nIf a "for" loop is terminated by "break", the loop control target\nkeeps its current value.\n\nWhen "break" passes control out of a "try" statement with a "finally"\nclause, that "finally" clause is executed before really leaving the\nloop.\n',
  'callable-types': u'\nEmulating callable objects\n**************************\n\nobject.__call__(self[, args...])\n\n   Called when the instance is "called" as a function; if this method\n   is defined, "x(arg1, arg2, ...)" is a shorthand for\n   "x.__call__(arg1, arg2, ...)".\n',
- 'calls': u'\nCalls\n*****\n\nA call calls a callable object (e.g., a *function*) with a possibly\nempty series of *arguments*:\n\n   call                 ::= primary "(" [argument_list [","] | comprehension] ")"\n   argument_list        ::= positional_arguments ["," starred_and_keywords]\n                       ["," keywords_arguments]\n                     | starred_and_keywords ["," keywords_arguments]\n                     | keywords_arguments\n   positional_arguments ::= ["*"] expression ("," ["*"] expression)*\n   starred_and_keywords ::= ("*" expression | keyword_item)\n                            ("," "*" expression | "," keyword_item)*\n   keywords_arguments   ::= (keyword_item | "**" expression)\n                          ("," keyword_item | "**" expression)*\n   keyword_item         ::= identifier "=" expression\n\nAn optional trailing comma may be present after the positional and\nkeyword arguments but does not affect the semantics.\n\nThe primary must evaluate to a callable object (user-defined\nfunctions, built-in functions, methods of built-in objects, class\nobjects, methods of class instances, and all objects having a\n"__call__()" method are callable).  All argument expressions are\nevaluated before the call is attempted.  Please refer to section\n*Function definitions* for the syntax of formal *parameter* lists.\n\nIf keyword arguments are present, they are first converted to\npositional arguments, as follows.  First, a list of unfilled slots is\ncreated for the formal parameters.  If there are N positional\narguments, they are placed in the first N slots.  Next, for each\nkeyword argument, the identifier is used to determine the\ncorresponding slot (if the identifier is the same as the first formal\nparameter name, the first slot is used, and so on).  If the slot is\nalready filled, a "TypeError" exception is raised. Otherwise, the\nvalue of the argument is placed in the slot, filling it (even if the\nexpression is "None", it fills the slot).  When all arguments have\nbeen processed, the slots that are still unfilled are filled with the\ncorresponding default value from the function definition.  (Default\nvalues are calculated, once, when the function is defined; thus, a\nmutable object such as a list or dictionary used as default value will\nbe shared by all calls that don\'t specify an argument value for the\ncorresponding slot; this should usually be avoided.)  If there are any\nunfilled slots for which no default value is specified, a "TypeError"\nexception is raised.  Otherwise, the list of filled slots is used as\nthe argument list for the call.\n\n**CPython implementation detail:** An implementation may provide\nbuilt-in functions whose positional parameters do not have names, even\nif they are \'named\' for the purpose of documentation, and which\ntherefore cannot be supplied by keyword.  In CPython, this is the case\nfor functions implemented in C that use "PyArg_ParseTuple()" to parse\ntheir arguments.\n\nIf there are more positional arguments than there are formal parameter\nslots, a "TypeError" exception is raised, unless a formal parameter\nusing the syntax "*identifier" is present; in this case, that formal\nparameter receives a tuple containing the excess positional arguments\n(or an empty tuple if there were no excess positional arguments).\n\nIf any keyword argument does not correspond to a formal parameter\nname, a "TypeError" exception is raised, unless a formal parameter\nusing the syntax "**identifier" is present; in this case, that formal\nparameter receives a dictionary containing the excess keyword\narguments (using the keywords as keys and the argument values as\ncorresponding values), or a (new) empty dictionary if there were no\nexcess keyword arguments.\n\nIf the syntax "*expression" appears in the function call, "expression"\nmust evaluate to an *iterable*.  Elements from these iterables are\ntreated as if they were additional positional arguments.  For the call\n"f(x1, x2, *y, x3, x4)", if *y* evaluates to a sequence *y1*, ...,\n*yM*, this is equivalent to a call with M+4 positional arguments *x1*,\n*x2*, *y1*, ..., *yM*, *x3*, *x4*.\n\nA consequence of this is that although the "*expression" syntax may\nappear *after* explicit keyword arguments, it is processed *before*\nthe keyword arguments (and any "**expression" arguments -- see below).\nSo:\n\n   >>> def f(a, b):\n   ...     print(a, b)\n   ...\n   >>> f(b=1, *(2,))\n   2 1\n   >>> f(a=1, *(2,))\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n   TypeError: f() got multiple values for keyword argument \'a\'\n   >>> f(1, *(2,))\n   1 2\n\nIt is unusual for both keyword arguments and the "*expression" syntax\nto be used in the same call, so in practice this confusion does not\narise.\n\nIf the syntax "**expression" appears in the function call,\n"expression" must evaluate to a *mapping*, the contents of which are\ntreated as additional keyword arguments.  If a keyword is already\npresent (as an explicit keyword argument, or from another unpacking),\na "TypeError" exception is raised.\n\nFormal parameters using the syntax "*identifier" or "**identifier"\ncannot be used as positional argument slots or as keyword argument\nnames.\n\nChanged in version 3.5: Function calls accept any number of "*" and\n"**" unpackings, positional arguments may follow iterable unpackings\n("*"), and keyword arguments may follow dictionary unpackings ("**").\nOriginally proposed by **PEP 448**.\n\nA call always returns some value, possibly "None", unless it raises an\nexception.  How this value is computed depends on the type of the\ncallable object.\n\nIf it is---\n\na user-defined function:\n   The code block for the function is executed, passing it the\n   argument list.  The first thing the code block will do is bind the\n   formal parameters to the arguments; this is described in section\n   *Function definitions*.  When the code block executes a "return"\n   statement, this specifies the return value of the function call.\n\na built-in function or method:\n   The result is up to the interpreter; see *Built-in Functions* for\n   the descriptions of built-in functions and methods.\n\na class object:\n   A new instance of that class is returned.\n\na class instance method:\n   The corresponding user-defined function is called, with an argument\n   list that is one longer than the argument list of the call: the\n   instance becomes the first argument.\n\na class instance:\n   The class must define a "__call__()" method; the effect is then the\n   same as if that method was called.\n',
- 'class': u'\nClass definitions\n*****************\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [argument_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing.  Classes without an inheritance\nlist inherit, by default, from the base class "object"; hence,\n\n   class Foo:\n       pass\n\nis equivalent to\n\n   class Foo(object):\n       pass\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.)  When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated: just like when decorating functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\nThe evaluation rules for the decorator expressions are the same as for\nfunction decorators.  The result must be a class object, which is then\nbound to the class name.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances.  Instance attributes\ncan be set in a method with "self.name = value".  Both class and\ninstance attributes are accessible through the notation ""self.name"",\nand an instance attribute hides a class attribute with the same name\nwhen accessed in this way.  Class attributes can be used as defaults\nfor instance attributes, but using mutable values there can lead to\nunexpected results.  *Descriptors* can be used to create instance\nvariables with different implementation details.\n\nSee also: **PEP 3115** - Metaclasses in Python 3 **PEP 3129** -\n  Class Decorators\n',
- 'comparisons': u'\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation.  Also unlike C, expressions like "a < b < c" have the\ninterpretation that is conventional in mathematics:\n\n   comparison    ::= or_expr ( comp_operator or_expr )*\n   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n                     | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: "True" or "False".\n\nComparisons can be chained arbitrarily, e.g., "x < y <= z" is\nequivalent to "x < y and y <= z", except that "y" is evaluated only\nonce (but in both cases "z" is not evaluated at all when "x < y" is\nfound to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then "a op1 b op2 c ... y\nopN z" is equivalent to "a op1 b and b op2 c and ... y opN z", except\nthat each expression is evaluated at most once.\n\nNote that "a op1 b op2 c" doesn\'t imply any kind of comparison between\n*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\nperhaps not pretty).\n\n\nValue comparisons\n=================\n\nThe operators "<", ">", "==", ">=", "<=", and "!=" compare the values\nof two objects.  The objects do not need to have the same type.\n\nChapter *Objects, values and types* states that objects have a value\n(in addition to type and identity).  The value of an object is a\nrather abstract notion in Python: For example, there is no canonical\naccess method for an object\'s value.  Also, there is no requirement\nthat the value of an object should be constructed in a particular way,\ne.g. comprised of all its data attributes. Comparison operators\nimplement a particular notion of what the value of an object is.  One\ncan think of them as defining the value of an object indirectly, by\nmeans of their comparison implementation.\n\nBecause all types are (direct or indirect) subtypes of "object", they\ninherit the default comparison behavior from "object".  Types can\ncustomize their comparison behavior by implementing *rich comparison\nmethods* like "__lt__()", described in *Basic customization*.\n\nThe default behavior for equality comparison ("==" and "!=") is based\non the identity of the objects.  Hence, equality comparison of\ninstances with the same identity results in equality, and equality\ncomparison of instances with different identities results in\ninequality.  A motivation for this default behavior is the desire that\nall objects should be reflexive (i.e. "x is y" implies "x == y").\n\nA default order comparison ("<", ">", "<=", and ">=") is not provided;\nan attempt raises "TypeError".  A motivation for this default behavior\nis the lack of a similar invariant as for equality.\n\nThe behavior of the default equality comparison, that instances with\ndifferent identities are always unequal, may be in contrast to what\ntypes will need that have a sensible definition of object value and\nvalue-based equality.  Such types will need to customize their\ncomparison behavior, and in fact, a number of built-in types have done\nthat.\n\nThe following list describes the comparison behavior of the most\nimportant built-in types.\n\n* Numbers of built-in numeric types (*Numeric Types --- int, float,\n  complex*) and of the standard library types "fractions.Fraction" and\n  "decimal.Decimal" can be compared within and across their types,\n  with the restriction that complex numbers do not support order\n  comparison.  Within the limits of the types involved, they compare\n  mathematically (algorithmically) correct without loss of precision.\n\n  The not-a-number values "float(\'NaN\')" and "Decimal(\'NaN\')" are\n  special.  They are identical to themselves ("x is x" is true) but\n  are not equal to themselves ("x == x" is false).  Additionally,\n  comparing any number to a not-a-number value will return "False".\n  For example, both "3 < float(\'NaN\')" and "float(\'NaN\') < 3" will\n  return "False".\n\n* Binary sequences (instances of "bytes" or "bytearray") can be\n  compared within and across their types.  They compare\n  lexicographically using the numeric values of their elements.\n\n* Strings (instances of "str") compare lexicographically using the\n  numerical Unicode code points (the result of the built-in function\n  "ord()") of their characters. [3]\n\n  Strings and binary sequences cannot be directly compared.\n\n* Sequences (instances of "tuple", "list", or "range") can be\n  compared only within each of their types, with the restriction that\n  ranges do not support order comparison.  Equality comparison across\n  these types results in unequality, and ordering comparison across\n  these types raises "TypeError".\n\n  Sequences compare lexicographically using comparison of\n  corresponding elements, whereby reflexivity of the elements is\n  enforced.\n\n  In enforcing reflexivity of elements, the comparison of collections\n  assumes that for a collection element "x", "x == x" is always true.\n  Based on that assumption, element identity is compared first, and\n  element comparison is performed only for distinct elements.  This\n  approach yields the same result as a strict element comparison\n  would, if the compared elements are reflexive.  For non-reflexive\n  elements, the result is different than for strict element\n  comparison, and may be surprising:  The non-reflexive not-a-number\n  values for example result in the following comparison behavior when\n  used in a list:\n\n     >>> nan = float(\'NaN\')\n     >>> nan is nan\n     True\n     >>> nan == nan\n     False                 <-- the defined non-reflexive behavior of NaN\n     >>> [nan] == [nan]\n     True                  <-- list enforces reflexivity and tests identity first\n\n  Lexicographical comparison between built-in collections works as\n  follows:\n\n  * For two collections to compare equal, they must be of the same\n    type, have the same length, and each pair of corresponding\n    elements must compare equal (for example, "[1,2] == (1,2)" is\n    false because the type is not the same).\n\n  * Collections that support order comparison are ordered the same\n    as their first unequal elements (for example, "[1,2,x] <= [1,2,y]"\n    has the same value as "x <= y").  If a corresponding element does\n    not exist, the shorter collection is ordered first (for example,\n    "[1,2] < [1,2,3]" is true).\n\n* Mappings (instances of "dict") compare equal if and only if they\n  have equal *(key, value)* pairs. Equality comparison of the keys and\n  elements enforces reflexivity.\n\n  Order comparisons ("<", ">", "<=", and ">=") raise "TypeError".\n\n* Sets (instances of "set" or "frozenset") can be compared within\n  and across their types.\n\n  They define order comparison operators to mean subset and superset\n  tests.  Those relations do not define total orderings (for example,\n  the two sets "{1,2}" and "{2,3}" are not equal, nor subsets of one\n  another, nor supersets of one another).  Accordingly, sets are not\n  appropriate arguments for functions which depend on total ordering\n  (for example, "min()", "max()", and "sorted()" produce undefined\n  results given a list of sets as inputs).\n\n  Comparison of sets enforces reflexivity of its elements.\n\n* Most other built-in types have no comparison methods implemented,\n  so they inherit the default comparison behavior.\n\nUser-defined classes that customize their comparison behavior should\nfollow some consistency rules, if possible:\n\n* Equality comparison should be reflexive. In other words, identical\n  objects should compare equal:\n\n     "x is y" implies "x == y"\n\n* Comparison should be symmetric. In other words, the following\n  expressions should have the same result:\n\n     "x == y" and "y == x"\n\n     "x != y" and "y != x"\n\n     "x < y" and "y > x"\n\n     "x <= y" and "y >= x"\n\n* Comparison should be transitive. The following (non-exhaustive)\n  examples illustrate that:\n\n     "x > y and y > z" implies "x > z"\n\n     "x < y and y <= z" implies "x < z"\n\n* Inverse comparison should result in the boolean negation. In other\n  words, the following expressions should have the same result:\n\n     "x == y" and "not x != y"\n\n     "x < y" and "not x >= y" (for total ordering)\n\n     "x > y" and "not x <= y" (for total ordering)\n\n  The last two expressions apply to totally ordered collections (e.g.\n  to sequences, but not to sets or mappings). See also the\n  "total_ordering()" decorator.\n\nPython does not enforce these consistency rules. In fact, the\nnot-a-number values are an example for not following these rules.\n\n\nMembership test operations\n==========================\n\nThe operators "in" and "not in" test for membership.  "x in s"\nevaluates to true if *x* is a member of *s*, and false otherwise.  "x\nnot in s" returns the negation of "x in s".  All built-in sequences\nand set types support this as well as dictionary, for which "in" tests\nwhether the dictionary has a given key. For container types such as\nlist, tuple, set, frozenset, dict, or collections.deque, the\nexpression "x in y" is equivalent to "any(x is e or x == e for e in\ny)".\n\nFor the string and bytes types, "x in y" is true if and only if *x* is\na substring of *y*.  An equivalent test is "y.find(x) != -1".  Empty\nstrings are always considered to be a substring of any other string,\nso """ in "abc"" will return "True".\n\nFor user-defined classes which define the "__contains__()" method, "x\nin y" is true if and only if "y.__contains__(x)" is true.\n\nFor user-defined classes which do not define "__contains__()" but do\ndefine "__iter__()", "x in y" is true if some value "z" with "x == z"\nis produced while iterating over "y".  If an exception is raised\nduring the iteration, it is as if "in" raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n"__getitem__()", "x in y" is true if and only if there is a non-\nnegative integer index *i* such that "x == y[i]", and all lower\ninteger indices do not raise "IndexError" exception.  (If any other\nexception is raised, it is as if "in" raised that exception).\n\nThe operator "not in" is defined to have the inverse true value of\n"in".\n\n\nIdentity comparisons\n====================\n\nThe operators "is" and "is not" test for object identity: "x is y" is\ntrue if and only if *x* and *y* are the same object.  "x is not y"\nyields the inverse truth value. [4]\n',
- 'compound': u'\nCompound statements\n*******************\n\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way.  In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\n\nThe "if", "while" and "for" statements implement traditional control\nflow constructs.  "try" specifies exception handlers and/or cleanup\ncode for a group of statements, while the "with" statement allows the\nexecution of initialization and finalization code around a block of\ncode.  Function and class definitions are also syntactically compound\nstatements.\n\nA compound statement consists of one or more \'clauses.\'  A clause\nconsists of a header and a \'suite.\'  The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon.  A suite is a group of statements controlled by a\nclause.  A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header\'s\ncolon, or it can be one or more indented statements on subsequent\nlines.  Only the latter form of a suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn\'t be\nclear to which "if" clause a following "else" clause would belong:\n\n   if test1: if test2: print(x)\n\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\n"print()" calls are executed:\n\n   if x < y < z: print(x); print(y); print(z)\n\nSummarizing:\n\n   compound_stmt ::= if_stmt\n                     | while_stmt\n                     | for_stmt\n                     | try_stmt\n                     | with_stmt\n                     | funcdef\n                     | classdef\n                     | async_with_stmt\n                     | async_for_stmt\n                     | async_funcdef\n   suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\n   statement     ::= stmt_list NEWLINE | compound_stmt\n   stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]\n\nNote that statements always end in a "NEWLINE" possibly followed by a\n"DEDENT".  Also note that optional continuation clauses always begin\nwith a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling "else"\' problem is solved in Python by\nrequiring nested "if" statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\nThe "if" statement\n==================\n\nThe "if" statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the "if" statement is executed or evaluated).\nIf all expressions are false, the suite of the "else" clause, if\npresent, is executed.\n\n\nThe "while" statement\n=====================\n\nThe "while" statement is used for repeated execution as long as an\nexpression is true:\n\n   while_stmt ::= "while" expression ":" suite\n                  ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the "else" clause, if present, is executed\nand the loop terminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite.  A "continue" statement\nexecuted in the first suite skips the rest of the suite and goes back\nto testing the expression.\n\n\nThe "for" statement\n===================\n\nThe "for" statement is used to iterate over the elements of a sequence\n(such as a string, tuple or list) or other iterable object:\n\n   for_stmt ::= "for" target_list "in" expression_list ":" suite\n                ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject.  An iterator is created for the result of the\n"expression_list".  The suite is then executed once for each item\nprovided by the iterator, in the order returned by the iterator.  Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted.  When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a "StopIteration" exception),\nthe suite in the "else" clause, if present, is executed, and the loop\nterminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite.  A "continue" statement\nexecuted in the first suite skips the rest of the suite and continues\nwith the next item, or with the "else" clause if there is no next\nitem.\n\nThe for-loop makes assignments to the variables(s) in the target list.\nThis overwrites all previous assignments to those variables including\nthose made in the suite of the for-loop:\n\n   for i in range(10):\n       print(i)\n       i = 5             # this will not affect the for-loop\n                         # because i will be overwritten with the next\n                         # index in the range\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, they will not have been assigned to at\nall by the loop.  Hint: the built-in function "range()" returns an\niterator of integers suitable to emulate the effect of Pascal\'s "for i\n:= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]".\n\nNote: There is a subtlety when the sequence is being modified by the\n  loop (this can only occur for mutable sequences, i.e. lists).  An\n  internal counter is used to keep track of which item is used next,\n  and this is incremented on each iteration.  When this counter has\n  reached the length of the sequence the loop terminates.  This means\n  that if the suite deletes the current (or a previous) item from the\n  sequence, the next item will be skipped (since it gets the index of\n  the current item which has already been treated).  Likewise, if the\n  suite inserts an item in the sequence before the current item, the\n  current item will be treated again the next time through the loop.\n  This can lead to nasty bugs that can be avoided by making a\n  temporary copy using a slice of the whole sequence, e.g.,\n\n     for x in a[:]:\n         if x < 0: a.remove(x)\n\n\nThe "try" statement\n===================\n\nThe "try" statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" identifier]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe "except" clause(s) specify one or more exception handlers. When no\nexception occurs in the "try" clause, no exception handler is\nexecuted. When an exception occurs in the "try" suite, a search for an\nexception handler is started.  This search inspects the except clauses\nin turn until one is found that matches the exception.  An expression-\nless except clause, if present, must be last; it matches any\nexception.  For an except clause with an expression, that expression\nis evaluated, and the clause matches the exception if the resulting\nobject is "compatible" with the exception.  An object is compatible\nwith an exception if it is the class or a base class of the exception\nobject or a tuple containing an item compatible with the exception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire "try" statement raised\nthe exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the "as" keyword in that except clause, if\npresent, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using "as target", it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause.  Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the "sys" module and can be accessed via\n"sys.exc_info()". "sys.exc_info()" returns a 3-tuple consisting of the\nexception class, the exception instance and a traceback object (see\nsection *The standard type hierarchy*) identifying the point in the\nprogram where the exception occurred.  "sys.exc_info()" values are\nrestored to their previous values (before the call) when returning\nfrom a function that handled an exception.\n\nThe optional "else" clause is executed if and when control flows off\nthe end of the "try" clause. [2] Exceptions in the "else" clause are\nnot handled by the preceding "except" clauses.\n\nIf "finally" is present, it specifies a \'cleanup\' handler.  The "try"\nclause is executed, including any "except" and "else" clauses.  If an\nexception occurs in any of the clauses and is not handled, the\nexception is temporarily saved. The "finally" clause is executed.  If\nthere is a saved exception it is re-raised at the end of the "finally"\nclause.  If the "finally" clause raises another exception, the saved\nexception is set as the context of the new exception. If the "finally"\nclause executes a "return" or "break" statement, the saved exception\nis discarded:\n\n   >>> def f():\n   ...     try:\n   ...         1/0\n   ...     finally:\n   ...         return 42\n   ...\n   >>> f()\n   42\n\nThe exception information is not available to the program during\nexecution of the "finally" clause.\n\nWhen a "return", "break" or "continue" statement is executed in the\n"try" suite of a "try"..."finally" statement, the "finally" clause is\nalso executed \'on the way out.\' A "continue" statement is illegal in\nthe "finally" clause. (The reason is a problem with the current\nimplementation --- this restriction may be lifted in the future).\n\nThe return value of a function is determined by the last "return"\nstatement executed.  Since the "finally" clause always executes, a\n"return" statement executed in the "finally" clause will always be the\nlast one executed:\n\n   >>> def foo():\n   ...     try:\n   ...         return \'try\'\n   ...     finally:\n   ...         return \'finally\'\n   ...\n   >>> foo()\n   \'finally\'\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the "raise" statement to\ngenerate exceptions may be found in section *The raise statement*.\n\n\nThe "with" statement\n====================\n\nThe "with" statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common "try"..."except"..."finally"\nusage patterns to be encapsulated for convenient reuse.\n\n   with_stmt ::= "with" with_item ("," with_item)* ":" suite\n   with_item ::= expression ["as" target]\n\nThe execution of the "with" statement with one "item" proceeds as\nfollows:\n\n1. The context expression (the expression given in the "with_item")\n   is evaluated to obtain a context manager.\n\n2. The context manager\'s "__exit__()" is loaded for later use.\n\n3. The context manager\'s "__enter__()" method is invoked.\n\n4. If a target was included in the "with" statement, the return\n   value from "__enter__()" is assigned to it.\n\n   Note: The "with" statement guarantees that if the "__enter__()"\n     method returns without an error, then "__exit__()" will always be\n     called. Thus, if an error occurs during the assignment to the\n     target list, it will be treated the same as an error occurring\n     within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s "__exit__()" method is invoked.  If an\n   exception caused the suite to be exited, its type, value, and\n   traceback are passed as arguments to "__exit__()". Otherwise, three\n   "None" arguments are supplied.\n\n   If the suite was exited due to an exception, and the return value\n   from the "__exit__()" method was false, the exception is reraised.\n   If the return value was true, the exception is suppressed, and\n   execution continues with the statement following the "with"\n   statement.\n\n   If the suite was exited for any reason other than an exception, the\n   return value from "__exit__()" is ignored, and execution proceeds\n   at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple "with" statements were nested:\n\n   with A() as a, B() as b:\n       suite\n\nis equivalent to\n\n   with A() as a:\n       with B() as b:\n           suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also: **PEP 343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      | "*" [parameter] ("," defparameter)* ["," "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nWhen one or more *parameters* have the form *parameter* "="\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding *argument* may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the ""*"" must also have a default value --- this\nis a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated from left to right when the\nfunction definition is executed.** This means that the expression is\nevaluated once, when the function is defined, and that the same "pre-\ncomputed" value is used for each call.  This is especially important\nto understand when a default parameter is a mutable object, such as a\nlist or a dictionary: if the function modifies the object (e.g. by\nappending an item to a list), the default value is in effect modified.\nThis is generally not what was intended.  A way around this is to use\n"None" as the default, and explicitly test for it in the body of the\nfunction, e.g.:\n\n   def whats_on_the_telly(penguin=None):\n       if penguin is None:\n           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n""*identifier"" is present, it is initialized to a tuple receiving any\nexcess positional parameters, defaulting to the empty tuple.  If the\nform ""**identifier"" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after ""*"" or ""*identifier"" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "": expression"" following\nthe parameter name.  Any parameter may have an annotation even those\nof the form "*identifier" or "**identifier".  Functions may have\n"return" annotation of the form ""-> expression"" after the parameter\nlist.  These annotations can be any valid Python expression and are\nevaluated when the function definition is executed.  Annotations may\nbe evaluated in a different order than they appear in the source code.\nThe presence of annotations does not change the semantics of a\nfunction.  The annotation values are available as values of a\ndictionary keyed by the parameters\' names in the "__annotations__"\nattribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda\nexpressions, described in section *Lambdas*.  Note that the lambda\nexpression is merely a shorthand for a simplified function definition;\na function defined in a ""def"" statement can be passed around or\nassigned to another name just like a function defined by a lambda\nexpression.  The ""def"" form is actually more powerful since it\nallows the execution of multiple statements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A ""def""\nstatement executed inside a function definition defines a local\nfunction that can be returned or passed around.  Free variables used\nin the nested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n\nSee also: **PEP 3107** - Function Annotations\n\n     The original specification for function annotations.\n\n\nClass definitions\n=================\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [argument_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing.  Classes without an inheritance\nlist inherit, by default, from the base class "object"; hence,\n\n   class Foo:\n       pass\n\nis equivalent to\n\n   class Foo(object):\n       pass\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.)  When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated: just like when decorating functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\nThe evaluation rules for the decorator expressions are the same as for\nfunction decorators.  The result must be a class object, which is then\nbound to the class name.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances.  Instance attributes\ncan be set in a method with "self.name = value".  Both class and\ninstance attributes are accessible through the notation ""self.name"",\nand an instance attribute hides a class attribute with the same name\nwhen accessed in this way.  Class attributes can be used as defaults\nfor instance attributes, but using mutable values there can lead to\nunexpected results.  *Descriptors* can be used to create instance\nvariables with different implementation details.\n\nSee also: **PEP 3115** - Metaclasses in Python 3 **PEP 3129** -\n  Class Decorators\n\n\nCoroutines\n==========\n\nNew in version 3.5.\n\n\nCoroutine function definition\n-----------------------------\n\n   async_funcdef ::= [decorators] "async" "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n\nExecution of Python coroutines can be suspended and resumed at many\npoints (see *coroutine*).  In the body of a coroutine, any "await" and\n"async" identifiers become reserved keywords; "await" expressions,\n"async for" and "async with" can only be used in coroutine bodies.\n\nFunctions defined with "async def" syntax are always coroutine\nfunctions, even if they do not contain "await" or "async" keywords.\n\nIt is a "SyntaxError" to use "yield" expressions in "async def"\ncoroutines.\n\nAn example of a coroutine function:\n\n   async def func(param1, param2):\n       do_stuff()\n       await some_coroutine()\n\n\nThe "async for" statement\n-------------------------\n\n   async_for_stmt ::= "async" for_stmt\n\nAn *asynchronous iterable* is able to call asynchronous code in its\n*iter* implementation, and *asynchronous iterator* can call\nasynchronous code in its *next* method.\n\nThe "async for" statement allows convenient iteration over\nasynchronous iterators.\n\nThe following code:\n\n   async for TARGET in ITER:\n       BLOCK\n   else:\n       BLOCK2\n\nIs semantically equivalent to:\n\n   iter = (ITER)\n   iter = type(iter).__aiter__(iter)\n   running = True\n   while running:\n       try:\n           TARGET = await type(iter).__anext__(iter)\n       except StopAsyncIteration:\n           running = False\n       else:\n           BLOCK\n   else:\n       BLOCK2\n\nSee also "__aiter__()" and "__anext__()" for details.\n\nIt is a "SyntaxError" to use "async for" statement outside of an\n"async def" function.\n\n\nThe "async with" statement\n--------------------------\n\n   async_with_stmt ::= "async" with_stmt\n\nAn *asynchronous context manager* is a *context manager* that is able\nto suspend execution in its *enter* and *exit* methods.\n\nThe following code:\n\n   async with EXPR as VAR:\n       BLOCK\n\nIs semantically equivalent to:\n\n   mgr = (EXPR)\n   aexit = type(mgr).__aexit__\n   aenter = type(mgr).__aenter__(mgr)\n   exc = True\n\n   VAR = await aenter\n   try:\n       BLOCK\n   except:\n       if not await aexit(mgr, *sys.exc_info()):\n           raise\n   else:\n       await aexit(mgr, None, None, None)\n\nSee also "__aenter__()" and "__aexit__()" for details.\n\nIt is a "SyntaxError" to use "async with" statement outside of an\n"async def" function.\n\nSee also: **PEP 492** - Coroutines with async and await syntax\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless\n    there is a "finally" clause which happens to raise another\n    exception. That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of\n    an exception or the execution of a "return", "continue", or\n    "break" statement.\n\n[3] A string literal appearing as the first statement in the\n    function body is transformed into the function\'s "__doc__"\n    attribute and therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n    body is transformed into the namespace\'s "__doc__" item and\n    therefore the class\'s *docstring*.\n',
+ 'calls': u'\nCalls\n*****\n\nA call calls a callable object (e.g., a *function*) with a possibly\nempty series of *arguments*:\n\n   call                 ::= primary "(" [argument_list [","] | comprehension] ")"\n   argument_list        ::= positional_arguments ["," starred_and_keywords]\n                       ["," keywords_arguments]\n                     | starred_and_keywords ["," keywords_arguments]\n                     | keywords_arguments\n   positional_arguments ::= ["*"] expression ("," ["*"] expression)*\n   starred_and_keywords ::= ("*" expression | keyword_item)\n                            ("," "*" expression | "," keyword_item)*\n   keywords_arguments   ::= (keyword_item | "**" expression)\n                          ("," keyword_item | "," "**" expression)*\n   keyword_item         ::= identifier "=" expression\n\nAn optional trailing comma may be present after the positional and\nkeyword arguments but does not affect the semantics.\n\nThe primary must evaluate to a callable object (user-defined\nfunctions, built-in functions, methods of built-in objects, class\nobjects, methods of class instances, and all objects having a\n"__call__()" method are callable).  All argument expressions are\nevaluated before the call is attempted.  Please refer to section\n*Function definitions* for the syntax of formal *parameter* lists.\n\nIf keyword arguments are present, they are first converted to\npositional arguments, as follows.  First, a list of unfilled slots is\ncreated for the formal parameters.  If there are N positional\narguments, they are placed in the first N slots.  Next, for each\nkeyword argument, the identifier is used to determine the\ncorresponding slot (if the identifier is the same as the first formal\nparameter name, the first slot is used, and so on).  If the slot is\nalready filled, a "TypeError" exception is raised. Otherwise, the\nvalue of the argument is placed in the slot, filling it (even if the\nexpression is "None", it fills the slot).  When all arguments have\nbeen processed, the slots that are still unfilled are filled with the\ncorresponding default value from the function definition.  (Default\nvalues are calculated, once, when the function is defined; thus, a\nmutable object such as a list or dictionary used as default value will\nbe shared by all calls that don\'t specify an argument value for the\ncorresponding slot; this should usually be avoided.)  If there are any\nunfilled slots for which no default value is specified, a "TypeError"\nexception is raised.  Otherwise, the list of filled slots is used as\nthe argument list for the call.\n\n**CPython implementation detail:** An implementation may provide\nbuilt-in functions whose positional parameters do not have names, even\nif they are \'named\' for the purpose of documentation, and which\ntherefore cannot be supplied by keyword.  In CPython, this is the case\nfor functions implemented in C that use "PyArg_ParseTuple()" to parse\ntheir arguments.\n\nIf there are more positional arguments than there are formal parameter\nslots, a "TypeError" exception is raised, unless a formal parameter\nusing the syntax "*identifier" is present; in this case, that formal\nparameter receives a tuple containing the excess positional arguments\n(or an empty tuple if there were no excess positional arguments).\n\nIf any keyword argument does not correspond to a formal parameter\nname, a "TypeError" exception is raised, unless a formal parameter\nusing the syntax "**identifier" is present; in this case, that formal\nparameter receives a dictionary containing the excess keyword\narguments (using the keywords as keys and the argument values as\ncorresponding values), or a (new) empty dictionary if there were no\nexcess keyword arguments.\n\nIf the syntax "*expression" appears in the function call, "expression"\nmust evaluate to an *iterable*.  Elements from these iterables are\ntreated as if they were additional positional arguments.  For the call\n"f(x1, x2, *y, x3, x4)", if *y* evaluates to a sequence *y1*, ...,\n*yM*, this is equivalent to a call with M+4 positional arguments *x1*,\n*x2*, *y1*, ..., *yM*, *x3*, *x4*.\n\nA consequence of this is that although the "*expression" syntax may\nappear *after* explicit keyword arguments, it is processed *before*\nthe keyword arguments (and any "**expression" arguments -- see below).\nSo:\n\n   >>> def f(a, b):\n   ...     print(a, b)\n   ...\n   >>> f(b=1, *(2,))\n   2 1\n   >>> f(a=1, *(2,))\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n   TypeError: f() got multiple values for keyword argument \'a\'\n   >>> f(1, *(2,))\n   1 2\n\nIt is unusual for both keyword arguments and the "*expression" syntax\nto be used in the same call, so in practice this confusion does not\narise.\n\nIf the syntax "**expression" appears in the function call,\n"expression" must evaluate to a *mapping*, the contents of which are\ntreated as additional keyword arguments.  If a keyword is already\npresent (as an explicit keyword argument, or from another unpacking),\na "TypeError" exception is raised.\n\nFormal parameters using the syntax "*identifier" or "**identifier"\ncannot be used as positional argument slots or as keyword argument\nnames.\n\nChanged in version 3.5: Function calls accept any number of "*" and\n"**" unpackings, positional arguments may follow iterable unpackings\n("*"), and keyword arguments may follow dictionary unpackings ("**").\nOriginally proposed by **PEP 448**.\n\nA call always returns some value, possibly "None", unless it raises an\nexception.  How this value is computed depends on the type of the\ncallable object.\n\nIf it is---\n\na user-defined function:\n   The code block for the function is executed, passing it the\n   argument list.  The first thing the code block will do is bind the\n   formal parameters to the arguments; this is described in section\n   *Function definitions*.  When the code block executes a "return"\n   statement, this specifies the return value of the function call.\n\na built-in function or method:\n   The result is up to the interpreter; see *Built-in Functions* for\n   the descriptions of built-in functions and methods.\n\na class object:\n   A new instance of that class is returned.\n\na class instance method:\n   The corresponding user-defined function is called, with an argument\n   list that is one longer than the argument list of the call: the\n   instance becomes the first argument.\n\na class instance:\n   The class must define a "__call__()" method; the effect is then the\n   same as if that method was called.\n',
+ 'class': u'\nClass definitions\n*****************\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [argument_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing.  Classes without an inheritance\nlist inherit, by default, from the base class "object"; hence,\n\n   class Foo:\n       pass\n\nis equivalent to\n\n   class Foo(object):\n       pass\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.)  When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated: just like when decorating functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis roughly equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\nThe evaluation rules for the decorator expressions are the same as for\nfunction decorators.  The result is then bound to the class name.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances.  Instance attributes\ncan be set in a method with "self.name = value".  Both class and\ninstance attributes are accessible through the notation ""self.name"",\nand an instance attribute hides a class attribute with the same name\nwhen accessed in this way.  Class attributes can be used as defaults\nfor instance attributes, but using mutable values there can lead to\nunexpected results.  *Descriptors* can be used to create instance\nvariables with different implementation details.\n\nSee also: **PEP 3115** - Metaclasses in Python 3 **PEP 3129** -\n  Class Decorators\n',
+ 'comparisons': u'\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation.  Also unlike C, expressions like "a < b < c" have the\ninterpretation that is conventional in mathematics:\n\n   comparison    ::= or_expr ( comp_operator or_expr )*\n   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n                     | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: "True" or "False".\n\nComparisons can be chained arbitrarily, e.g., "x < y <= z" is\nequivalent to "x < y and y <= z", except that "y" is evaluated only\nonce (but in both cases "z" is not evaluated at all when "x < y" is\nfound to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then "a op1 b op2 c ... y\nopN z" is equivalent to "a op1 b and b op2 c and ... y opN z", except\nthat each expression is evaluated at most once.\n\nNote that "a op1 b op2 c" doesn\'t imply any kind of comparison between\n*a* and *c*, so that, e.g., "x < y > z" is perfectly legal (though\nperhaps not pretty).\n\n\nValue comparisons\n=================\n\nThe operators "<", ">", "==", ">=", "<=", and "!=" compare the values\nof two objects.  The objects do not need to have the same type.\n\nChapter *Objects, values and types* states that objects have a value\n(in addition to type and identity).  The value of an object is a\nrather abstract notion in Python: For example, there is no canonical\naccess method for an object\'s value.  Also, there is no requirement\nthat the value of an object should be constructed in a particular way,\ne.g. comprised of all its data attributes. Comparison operators\nimplement a particular notion of what the value of an object is.  One\ncan think of them as defining the value of an object indirectly, by\nmeans of their comparison implementation.\n\nBecause all types are (direct or indirect) subtypes of "object", they\ninherit the default comparison behavior from "object".  Types can\ncustomize their comparison behavior by implementing *rich comparison\nmethods* like "__lt__()", described in *Basic customization*.\n\nThe default behavior for equality comparison ("==" and "!=") is based\non the identity of the objects.  Hence, equality comparison of\ninstances with the same identity results in equality, and equality\ncomparison of instances with different identities results in\ninequality.  A motivation for this default behavior is the desire that\nall objects should be reflexive (i.e. "x is y" implies "x == y").\n\nA default order comparison ("<", ">", "<=", and ">=") is not provided;\nan attempt raises "TypeError".  A motivation for this default behavior\nis the lack of a similar invariant as for equality.\n\nThe behavior of the default equality comparison, that instances with\ndifferent identities are always unequal, may be in contrast to what\ntypes will need that have a sensible definition of object value and\nvalue-based equality.  Such types will need to customize their\ncomparison behavior, and in fact, a number of built-in types have done\nthat.\n\nThe following list describes the comparison behavior of the most\nimportant built-in types.\n\n* Numbers of built-in numeric types (*Numeric Types --- int, float,\n  complex*) and of the standard library types "fractions.Fraction" and\n  "decimal.Decimal" can be compared within and across their types,\n  with the restriction that complex numbers do not support order\n  comparison.  Within the limits of the types involved, they compare\n  mathematically (algorithmically) correct without loss of precision.\n\n  The not-a-number values "float(\'NaN\')" and "Decimal(\'NaN\')" are\n  special.  They are identical to themselves ("x is x" is true) but\n  are not equal to themselves ("x == x" is false).  Additionally,\n  comparing any number to a not-a-number value will return "False".\n  For example, both "3 < float(\'NaN\')" and "float(\'NaN\') < 3" will\n  return "False".\n\n* Binary sequences (instances of "bytes" or "bytearray") can be\n  compared within and across their types.  They compare\n  lexicographically using the numeric values of their elements.\n\n* Strings (instances of "str") compare lexicographically using the\n  numerical Unicode code points (the result of the built-in function\n  "ord()") of their characters. [3]\n\n  Strings and binary sequences cannot be directly compared.\n\n* Sequences (instances of "tuple", "list", or "range") can be\n  compared only within each of their types, with the restriction that\n  ranges do not support order comparison.  Equality comparison across\n  these types results in unequality, and ordering comparison across\n  these types raises "TypeError".\n\n  Sequences compare lexicographically using comparison of\n  corresponding elements, whereby reflexivity of the elements is\n  enforced.\n\n  In enforcing reflexivity of elements, the comparison of collections\n  assumes that for a collection element "x", "x == x" is always true.\n  Based on that assumption, element identity is compared first, and\n  element comparison is performed only for distinct elements.  This\n  approach yields the same result as a strict element comparison\n  would, if the compared elements are reflexive.  For non-reflexive\n  elements, the result is different than for strict element\n  comparison, and may be surprising:  The non-reflexive not-a-number\n  values for example result in the following comparison behavior when\n  used in a list:\n\n     >>> nan = float(\'NaN\')\n     >>> nan is nan\n     True\n     >>> nan == nan\n     False                 <-- the defined non-reflexive behavior of NaN\n     >>> [nan] == [nan]\n     True                  <-- list enforces reflexivity and tests identity first\n\n  Lexicographical comparison between built-in collections works as\n  follows:\n\n  * For two collections to compare equal, they must be of the same\n    type, have the same length, and each pair of corresponding\n    elements must compare equal (for example, "[1,2] == (1,2)" is\n    false because the type is not the same).\n\n  * Collections that support order comparison are ordered the same\n    as their first unequal elements (for example, "[1,2,x] <= [1,2,y]"\n    has the same value as "x <= y").  If a corresponding element does\n    not exist, the shorter collection is ordered first (for example,\n    "[1,2] < [1,2,3]" is true).\n\n* Mappings (instances of "dict") compare equal if and only if they\n  have equal *(key, value)* pairs. Equality comparison of the keys and\n  elements enforces reflexivity.\n\n  Order comparisons ("<", ">", "<=", and ">=") raise "TypeError".\n\n* Sets (instances of "set" or "frozenset") can be compared within\n  and across their types.\n\n  They define order comparison operators to mean subset and superset\n  tests.  Those relations do not define total orderings (for example,\n  the two sets "{1,2}" and "{2,3}" are not equal, nor subsets of one\n  another, nor supersets of one another).  Accordingly, sets are not\n  appropriate arguments for functions which depend on total ordering\n  (for example, "min()", "max()", and "sorted()" produce undefined\n  results given a list of sets as inputs).\n\n  Comparison of sets enforces reflexivity of its elements.\n\n* Most other built-in types have no comparison methods implemented,\n  so they inherit the default comparison behavior.\n\nUser-defined classes that customize their comparison behavior should\nfollow some consistency rules, if possible:\n\n* Equality comparison should be reflexive. In other words, identical\n  objects should compare equal:\n\n     "x is y" implies "x == y"\n\n* Comparison should be symmetric. In other words, the following\n  expressions should have the same result:\n\n     "x == y" and "y == x"\n\n     "x != y" and "y != x"\n\n     "x < y" and "y > x"\n\n     "x <= y" and "y >= x"\n\n* Comparison should be transitive. The following (non-exhaustive)\n  examples illustrate that:\n\n     "x > y and y > z" implies "x > z"\n\n     "x < y and y <= z" implies "x < z"\n\n* Inverse comparison should result in the boolean negation. In other\n  words, the following expressions should have the same result:\n\n     "x == y" and "not x != y"\n\n     "x < y" and "not x >= y" (for total ordering)\n\n     "x > y" and "not x <= y" (for total ordering)\n\n  The last two expressions apply to totally ordered collections (e.g.\n  to sequences, but not to sets or mappings). See also the\n  "total_ordering()" decorator.\n\nPython does not enforce these consistency rules. In fact, the\nnot-a-number values are an example for not following these rules.\n\n\nMembership test operations\n==========================\n\nThe operators "in" and "not in" test for membership.  "x in s"\nevaluates to true if *x* is a member of *s*, and false otherwise.  "x\nnot in s" returns the negation of "x in s".  All built-in sequences\nand set types support this as well as dictionary, for which "in" tests\nwhether the dictionary has a given key. For container types such as\nlist, tuple, set, frozenset, dict, or collections.deque, the\nexpression "x in y" is equivalent to "any(x is e or x == e for e in\ny)".\n\nFor the string and bytes types, "x in y" is true if and only if *x* is\na substring of *y*.  An equivalent test is "y.find(x) != -1".  Empty\nstrings are always considered to be a substring of any other string,\nso """ in "abc"" will return "True".\n\nFor user-defined classes which define the "__contains__()" method, "x\nin y" is true if and only if "y.__contains__(x)" is true.\n\nFor user-defined classes which do not define "__contains__()" but do\ndefine "__iter__()", "x in y" is true if some value "z" with "x == z"\nis produced while iterating over "y".  If an exception is raised\nduring the iteration, it is as if "in" raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n"__getitem__()", "x in y" is true if and only if there is a non-\nnegative integer index *i* such that "x == y[i]", and all lower\ninteger indices do not raise "IndexError" exception.  (If any other\nexception is raised, it is as if "in" raised that exception).\n\nThe operator "not in" is defined to have the inverse true value of\n"in".\n\n\nIdentity comparisons\n====================\n\nThe operators "is" and "is not" test for object identity: "x is y" is\ntrue if and only if *x* and *y* are the same object.  Object identity\nis determined using the "id()" function.  "x is not y" yields the\ninverse truth value. [4]\n',
+ 'compound': u'\nCompound statements\n*******************\n\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way.  In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\n\nThe "if", "while" and "for" statements implement traditional control\nflow constructs.  "try" specifies exception handlers and/or cleanup\ncode for a group of statements, while the "with" statement allows the\nexecution of initialization and finalization code around a block of\ncode.  Function and class definitions are also syntactically compound\nstatements.\n\nA compound statement consists of one or more \'clauses.\'  A clause\nconsists of a header and a \'suite.\'  The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon.  A suite is a group of statements controlled by a\nclause.  A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header\'s\ncolon, or it can be one or more indented statements on subsequent\nlines.  Only the latter form of a suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn\'t be\nclear to which "if" clause a following "else" clause would belong:\n\n   if test1: if test2: print(x)\n\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\n"print()" calls are executed:\n\n   if x < y < z: print(x); print(y); print(z)\n\nSummarizing:\n\n   compound_stmt ::= if_stmt\n                     | while_stmt\n                     | for_stmt\n                     | try_stmt\n                     | with_stmt\n                     | funcdef\n                     | classdef\n                     | async_with_stmt\n                     | async_for_stmt\n                     | async_funcdef\n   suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\n   statement     ::= stmt_list NEWLINE | compound_stmt\n   stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]\n\nNote that statements always end in a "NEWLINE" possibly followed by a\n"DEDENT".  Also note that optional continuation clauses always begin\nwith a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling "else"\' problem is solved in Python by\nrequiring nested "if" statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\nThe "if" statement\n==================\n\nThe "if" statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the "if" statement is executed or evaluated).\nIf all expressions are false, the suite of the "else" clause, if\npresent, is executed.\n\n\nThe "while" statement\n=====================\n\nThe "while" statement is used for repeated execution as long as an\nexpression is true:\n\n   while_stmt ::= "while" expression ":" suite\n                  ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the "else" clause, if present, is executed\nand the loop terminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite.  A "continue" statement\nexecuted in the first suite skips the rest of the suite and goes back\nto testing the expression.\n\n\nThe "for" statement\n===================\n\nThe "for" statement is used to iterate over the elements of a sequence\n(such as a string, tuple or list) or other iterable object:\n\n   for_stmt ::= "for" target_list "in" expression_list ":" suite\n                ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject.  An iterator is created for the result of the\n"expression_list".  The suite is then executed once for each item\nprovided by the iterator, in the order returned by the iterator.  Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted.  When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a "StopIteration" exception),\nthe suite in the "else" clause, if present, is executed, and the loop\nterminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite.  A "continue" statement\nexecuted in the first suite skips the rest of the suite and continues\nwith the next item, or with the "else" clause if there is no next\nitem.\n\nThe for-loop makes assignments to the variables(s) in the target list.\nThis overwrites all previous assignments to those variables including\nthose made in the suite of the for-loop:\n\n   for i in range(10):\n       print(i)\n       i = 5             # this will not affect the for-loop\n                         # because i will be overwritten with the next\n                         # index in the range\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, they will not have been assigned to at\nall by the loop.  Hint: the built-in function "range()" returns an\niterator of integers suitable to emulate the effect of Pascal\'s "for i\n:= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]".\n\nNote: There is a subtlety when the sequence is being modified by the\n  loop (this can only occur for mutable sequences, i.e. lists).  An\n  internal counter is used to keep track of which item is used next,\n  and this is incremented on each iteration.  When this counter has\n  reached the length of the sequence the loop terminates.  This means\n  that if the suite deletes the current (or a previous) item from the\n  sequence, the next item will be skipped (since it gets the index of\n  the current item which has already been treated).  Likewise, if the\n  suite inserts an item in the sequence before the current item, the\n  current item will be treated again the next time through the loop.\n  This can lead to nasty bugs that can be avoided by making a\n  temporary copy using a slice of the whole sequence, e.g.,\n\n     for x in a[:]:\n         if x < 0: a.remove(x)\n\n\nThe "try" statement\n===================\n\nThe "try" statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" identifier]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe "except" clause(s) specify one or more exception handlers. When no\nexception occurs in the "try" clause, no exception handler is\nexecuted. When an exception occurs in the "try" suite, a search for an\nexception handler is started.  This search inspects the except clauses\nin turn until one is found that matches the exception.  An expression-\nless except clause, if present, must be last; it matches any\nexception.  For an except clause with an expression, that expression\nis evaluated, and the clause matches the exception if the resulting\nobject is "compatible" with the exception.  An object is compatible\nwith an exception if it is the class or a base class of the exception\nobject or a tuple containing an item compatible with the exception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire "try" statement raised\nthe exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the "as" keyword in that except clause, if\npresent, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using "as target", it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause.  Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the "sys" module and can be accessed via\n"sys.exc_info()". "sys.exc_info()" returns a 3-tuple consisting of the\nexception class, the exception instance and a traceback object (see\nsection *The standard type hierarchy*) identifying the point in the\nprogram where the exception occurred.  "sys.exc_info()" values are\nrestored to their previous values (before the call) when returning\nfrom a function that handled an exception.\n\nThe optional "else" clause is executed if and when control flows off\nthe end of the "try" clause. [2] Exceptions in the "else" clause are\nnot handled by the preceding "except" clauses.\n\nIf "finally" is present, it specifies a \'cleanup\' handler.  The "try"\nclause is executed, including any "except" and "else" clauses.  If an\nexception occurs in any of the clauses and is not handled, the\nexception is temporarily saved. The "finally" clause is executed.  If\nthere is a saved exception it is re-raised at the end of the "finally"\nclause.  If the "finally" clause raises another exception, the saved\nexception is set as the context of the new exception. If the "finally"\nclause executes a "return" or "break" statement, the saved exception\nis discarded:\n\n   >>> def f():\n   ...     try:\n   ...         1/0\n   ...     finally:\n   ...         return 42\n   ...\n   >>> f()\n   42\n\nThe exception information is not available to the program during\nexecution of the "finally" clause.\n\nWhen a "return", "break" or "continue" statement is executed in the\n"try" suite of a "try"..."finally" statement, the "finally" clause is\nalso executed \'on the way out.\' A "continue" statement is illegal in\nthe "finally" clause. (The reason is a problem with the current\nimplementation --- this restriction may be lifted in the future).\n\nThe return value of a function is determined by the last "return"\nstatement executed.  Since the "finally" clause always executes, a\n"return" statement executed in the "finally" clause will always be the\nlast one executed:\n\n   >>> def foo():\n   ...     try:\n   ...         return \'try\'\n   ...     finally:\n   ...         return \'finally\'\n   ...\n   >>> foo()\n   \'finally\'\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the "raise" statement to\ngenerate exceptions may be found in section *The raise statement*.\n\n\nThe "with" statement\n====================\n\nThe "with" statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common "try"..."except"..."finally"\nusage patterns to be encapsulated for convenient reuse.\n\n   with_stmt ::= "with" with_item ("," with_item)* ":" suite\n   with_item ::= expression ["as" target]\n\nThe execution of the "with" statement with one "item" proceeds as\nfollows:\n\n1. The context expression (the expression given in the "with_item")\n   is evaluated to obtain a context manager.\n\n2. The context manager\'s "__exit__()" is loaded for later use.\n\n3. The context manager\'s "__enter__()" method is invoked.\n\n4. If a target was included in the "with" statement, the return\n   value from "__enter__()" is assigned to it.\n\n   Note: The "with" statement guarantees that if the "__enter__()"\n     method returns without an error, then "__exit__()" will always be\n     called. Thus, if an error occurs during the assignment to the\n     target list, it will be treated the same as an error occurring\n     within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s "__exit__()" method is invoked.  If an\n   exception caused the suite to be exited, its type, value, and\n   traceback are passed as arguments to "__exit__()". Otherwise, three\n   "None" arguments are supplied.\n\n   If the suite was exited due to an exception, and the return value\n   from the "__exit__()" method was false, the exception is reraised.\n   If the return value was true, the exception is suppressed, and\n   execution continues with the statement following the "with"\n   statement.\n\n   If the suite was exited for any reason other than an exception, the\n   return value from "__exit__()" is ignored, and execution proceeds\n   at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple "with" statements were nested:\n\n   with A() as a, B() as b:\n       suite\n\nis equivalent to\n\n   with A() as a:\n       with B() as b:\n           suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also: **PEP 343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      | "*" [parameter] ("," defparameter)* ["," "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis roughly equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nexcept that the original function is not temporarily bound to the name\n"func".\n\nWhen one or more *parameters* have the form *parameter* "="\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding *argument* may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the ""*"" must also have a default value --- this\nis a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated from left to right when the\nfunction definition is executed.** This means that the expression is\nevaluated once, when the function is defined, and that the same "pre-\ncomputed" value is used for each call.  This is especially important\nto understand when a default parameter is a mutable object, such as a\nlist or a dictionary: if the function modifies the object (e.g. by\nappending an item to a list), the default value is in effect modified.\nThis is generally not what was intended.  A way around this is to use\n"None" as the default, and explicitly test for it in the body of the\nfunction, e.g.:\n\n   def whats_on_the_telly(penguin=None):\n       if penguin is None:\n           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n""*identifier"" is present, it is initialized to a tuple receiving any\nexcess positional parameters, defaulting to the empty tuple.  If the\nform ""**identifier"" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after ""*"" or ""*identifier"" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "": expression"" following\nthe parameter name.  Any parameter may have an annotation even those\nof the form "*identifier" or "**identifier".  Functions may have\n"return" annotation of the form ""-> expression"" after the parameter\nlist.  These annotations can be any valid Python expression and are\nevaluated when the function definition is executed.  Annotations may\nbe evaluated in a different order than they appear in the source code.\nThe presence of annotations does not change the semantics of a\nfunction.  The annotation values are available as values of a\ndictionary keyed by the parameters\' names in the "__annotations__"\nattribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda\nexpressions, described in section *Lambdas*.  Note that the lambda\nexpression is merely a shorthand for a simplified function definition;\na function defined in a ""def"" statement can be passed around or\nassigned to another name just like a function defined by a lambda\nexpression.  The ""def"" form is actually more powerful since it\nallows the execution of multiple statements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A ""def""\nstatement executed inside a function definition defines a local\nfunction that can be returned or passed around.  Free variables used\nin the nested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n\nSee also: **PEP 3107** - Function Annotations\n\n     The original specification for function annotations.\n\n\nClass definitions\n=================\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [argument_list] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing.  Classes without an inheritance\nlist inherit, by default, from the base class "object"; hence,\n\n   class Foo:\n       pass\n\nis equivalent to\n\n   class Foo(object):\n       pass\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.)  When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated: just like when decorating functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis roughly equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\nThe evaluation rules for the decorator expressions are the same as for\nfunction decorators.  The result is then bound to the class name.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances.  Instance attributes\ncan be set in a method with "self.name = value".  Both class and\ninstance attributes are accessible through the notation ""self.name"",\nand an instance attribute hides a class attribute with the same name\nwhen accessed in this way.  Class attributes can be used as defaults\nfor instance attributes, but using mutable values there can lead to\nunexpected results.  *Descriptors* can be used to create instance\nvariables with different implementation details.\n\nSee also: **PEP 3115** - Metaclasses in Python 3 **PEP 3129** -\n  Class Decorators\n\n\nCoroutines\n==========\n\nNew in version 3.5.\n\n\nCoroutine function definition\n-----------------------------\n\n   async_funcdef ::= [decorators] "async" "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n\nExecution of Python coroutines can be suspended and resumed at many\npoints (see *coroutine*).  In the body of a coroutine, any "await" and\n"async" identifiers become reserved keywords; "await" expressions,\n"async for" and "async with" can only be used in coroutine bodies.\n\nFunctions defined with "async def" syntax are always coroutine\nfunctions, even if they do not contain "await" or "async" keywords.\n\nIt is a "SyntaxError" to use "yield" expressions in "async def"\ncoroutines.\n\nAn example of a coroutine function:\n\n   async def func(param1, param2):\n       do_stuff()\n       await some_coroutine()\n\n\nThe "async for" statement\n-------------------------\n\n   async_for_stmt ::= "async" for_stmt\n\nAn *asynchronous iterable* is able to call asynchronous code in its\n*iter* implementation, and *asynchronous iterator* can call\nasynchronous code in its *next* method.\n\nThe "async for" statement allows convenient iteration over\nasynchronous iterators.\n\nThe following code:\n\n   async for TARGET in ITER:\n       BLOCK\n   else:\n       BLOCK2\n\nIs semantically equivalent to:\n\n   iter = (ITER)\n   iter = type(iter).__aiter__(iter)\n   running = True\n   while running:\n       try:\n           TARGET = await type(iter).__anext__(iter)\n       except StopAsyncIteration:\n           running = False\n       else:\n           BLOCK\n   else:\n       BLOCK2\n\nSee also "__aiter__()" and "__anext__()" for details.\n\nIt is a "SyntaxError" to use "async for" statement outside of an\n"async def" function.\n\n\nThe "async with" statement\n--------------------------\n\n   async_with_stmt ::= "async" with_stmt\n\nAn *asynchronous context manager* is a *context manager* that is able\nto suspend execution in its *enter* and *exit* methods.\n\nThe following code:\n\n   async with EXPR as VAR:\n       BLOCK\n\nIs semantically equivalent to:\n\n   mgr = (EXPR)\n   aexit = type(mgr).__aexit__\n   aenter = type(mgr).__aenter__(mgr)\n   exc = True\n\n   VAR = await aenter\n   try:\n       BLOCK\n   except:\n       if not await aexit(mgr, *sys.exc_info()):\n           raise\n   else:\n       await aexit(mgr, None, None, None)\n\nSee also "__aenter__()" and "__aexit__()" for details.\n\nIt is a "SyntaxError" to use "async with" statement outside of an\n"async def" function.\n\nSee also: **PEP 492** - Coroutines with async and await syntax\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack unless\n    there is a "finally" clause which happens to raise another\n    exception. That new exception causes the old one to be lost.\n\n[2] Currently, control "flows off the end" except in the case of\n    an exception or the execution of a "return", "continue", or\n    "break" statement.\n\n[3] A string literal appearing as the first statement in the\n    function body is transformed into the function\'s "__doc__"\n    attribute and therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n    body is transformed into the namespace\'s "__doc__" item and\n    therefore the class\'s *docstring*.\n',
  'context-managers': u'\nWith Statement Context Managers\n*******************************\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a "with" statement. The context manager\nhandles the entry into, and the exit from, the desired runtime context\nfor the execution of the block of code.  Context managers are normally\ninvoked using the "with" statement (described in section *The with\nstatement*), but can also be used by directly invoking their methods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n   Enter the runtime context related to this object. The "with"\n   statement will bind this method\'s return value to the target(s)\n   specified in the "as" clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n   Exit the runtime context related to this object. The parameters\n   describe the exception that caused the context to be exited. If the\n   context was exited without an exception, all three arguments will\n   be "None".\n\n   If an exception is supplied, and the method wishes to suppress the\n   exception (i.e., prevent it from being propagated), it should\n   return a true value. Otherwise, the exception will be processed\n   normally upon exit from this method.\n\n   Note that "__exit__()" methods should not reraise the passed-in\n   exception; this is the caller\'s responsibility.\n\nSee also: **PEP 343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n',
  'continue': u'\nThe "continue" statement\n************************\n\n   continue_stmt ::= "continue"\n\n"continue" may only occur syntactically nested in a "for" or "while"\nloop, but not nested in a function or class definition or "finally"\nclause within that loop.  It continues with the next cycle of the\nnearest enclosing loop.\n\nWhen "continue" passes control out of a "try" statement with a\n"finally" clause, that "finally" clause is executed before really\nstarting the next loop cycle.\n',
  'conversions': u'\nArithmetic conversions\n**********************\n\nWhen a description of an arithmetic operator below uses the phrase\n"the numeric arguments are converted to a common type," this means\nthat the operator implementation for built-in types works as follows:\n\n* If either argument is a complex number, the other is converted to\n  complex;\n\n* otherwise, if either argument is a floating point number, the\n  other is converted to floating point;\n\n* otherwise, both must be integers and no conversion is necessary.\n\nSome additional rules apply for certain operators (e.g., a string as a\nleft argument to the \'%\' operator).  Extensions must define their own\nconversion behavior.\n',
- 'customization': u'\nBasic customization\n*******************\n\nobject.__new__(cls[, ...])\n\n   Called to create a new instance of class *cls*.  "__new__()" is a\n   static method (special-cased so you need not declare it as such)\n   that takes the class of which an instance was requested as its\n   first argument.  The remaining arguments are those passed to the\n   object constructor expression (the call to the class).  The return\n   value of "__new__()" should be the new object instance (usually an\n   instance of *cls*).\n\n   Typical implementations create a new instance of the class by\n   invoking the superclass\'s "__new__()" method using\n   "super(currentclass, cls).__new__(cls[, ...])" with appropriate\n   arguments and then modifying the newly-created instance as\n   necessary before returning it.\n\n   If "__new__()" returns an instance of *cls*, then the new\n   instance\'s "__init__()" method will be invoked like\n   "__init__(self[, ...])", where *self* is the new instance and the\n   remaining arguments are the same as were passed to "__new__()".\n\n   If "__new__()" does not return an instance of *cls*, then the new\n   instance\'s "__init__()" method will not be invoked.\n\n   "__new__()" is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called after the instance has been created (by "__new__()"), but\n   before it is returned to the caller.  The arguments are those\n   passed to the class constructor expression.  If a base class has an\n   "__init__()" method, the derived class\'s "__init__()" method, if\n   any, must explicitly call it to ensure proper initialization of the\n   base class part of the instance; for example:\n   "BaseClass.__init__(self, [args...])".\n\n   Because "__new__()" and "__init__()" work together in constructing\n   objects ("__new__()" to create it, and "__init__()" to customise\n   it), no non-"None" value may be returned by "__init__()"; doing so\n   will cause a "TypeError" to be raised at runtime.\n\nobject.__del__(self)\n\n   Called when the instance is about to be destroyed.  This is also\n   called a destructor.  If a base class has a "__del__()" method, the\n   derived class\'s "__del__()" method, if any, must explicitly call it\n   to ensure proper deletion of the base class part of the instance.\n   Note that it is possible (though not recommended!) for the\n   "__del__()" method to postpone destruction of the instance by\n   creating a new reference to it.  It may then be called at a later\n   time when this new reference is deleted.  It is not guaranteed that\n   "__del__()" methods are called for objects that still exist when\n   the interpreter exits.\n\n   Note: "del x" doesn\'t directly call "x.__del__()" --- the former\n     decrements the reference count for "x" by one, and the latter is\n     only called when "x"\'s reference count reaches zero.  Some common\n     situations that may prevent the reference count of an object from\n     going to zero include: circular references between objects (e.g.,\n     a doubly-linked list or a tree data structure with parent and\n     child pointers); a reference to the object on the stack frame of\n     a function that caught an exception (the traceback stored in\n     "sys.exc_info()[2]" keeps the stack frame alive); or a reference\n     to the object on the stack frame that raised an unhandled\n     exception in interactive mode (the traceback stored in\n     "sys.last_traceback" keeps the stack frame alive).  The first\n     situation can only be remedied by explicitly breaking the cycles;\n     the second can be resolved by freeing the reference to the\n     traceback object when it is no longer useful, and the third can\n     be resolved by storing "None" in "sys.last_traceback". Circular\n     references which are garbage are detected and cleaned up when the\n     cyclic garbage collector is enabled (it\'s on by default). Refer\n     to the documentation for the "gc" module for more information\n     about this topic.\n\n   Warning: Due to the precarious circumstances under which\n     "__del__()" methods are invoked, exceptions that occur during\n     their execution are ignored, and a warning is printed to\n     "sys.stderr" instead. Also, when "__del__()" is invoked in\n     response to a module being deleted (e.g., when execution of the\n     program is done), other globals referenced by the "__del__()"\n     method may already have been deleted or in the process of being\n     torn down (e.g. the import machinery shutting down).  For this\n     reason, "__del__()" methods should do the absolute minimum needed\n     to maintain external invariants.  Starting with version 1.5,\n     Python guarantees that globals whose name begins with a single\n     underscore are deleted from their module before other globals are\n     deleted; if no other references to such globals exist, this may\n     help in assuring that imported modules are still available at the\n     time when the "__del__()" method is called.\n\nobject.__repr__(self)\n\n   Called by the "repr()" built-in function to compute the "official"\n   string representation of an object.  If at all possible, this\n   should look like a valid Python expression that could be used to\n   recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   "<...some useful description...>" should be returned. The return\n   value must be a string object. If a class defines "__repr__()" but\n   not "__str__()", then "__repr__()" is also used when an "informal"\n   string representation of instances of that class is required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by "str(object)" and the built-in functions "format()" and\n   "print()" to compute the "informal" or nicely printable string\n   representation of an object.  The return value must be a *string*\n   object.\n\n   This method differs from "object.__repr__()" in that there is no\n   expectation that "__str__()" return a valid Python expression: a\n   more convenient or concise representation can be used.\n\n   The default implementation defined by the built-in type "object"\n   calls "object.__repr__()".\n\nobject.__bytes__(self)\n\n   Called by "bytes()" to compute a byte-string representation of an\n   object. This should return a "bytes" object.\n\nobject.__format__(self, format_spec)\n\n   Called by the "format()" built-in function (and by extension, the\n   "str.format()" method of class "str") to produce a "formatted"\n   string representation of an object. The "format_spec" argument is a\n   string that contains a description of the formatting options\n   desired. The interpretation of the "format_spec" argument is up to\n   the type implementing "__format__()", however most classes will\n   either delegate formatting to one of the built-in types, or use a\n   similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\n   Changed in version 3.4: The __format__ method of "object" itself\n   raises a "TypeError" if passed any non-empty string.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",\n   "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls\n   "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n   A rich comparison method may return the singleton "NotImplemented"\n   if it does not implement the operation for a given pair of\n   arguments. By convention, "False" and "True" are returned for a\n   successful comparison. However, these methods can return any value,\n   so if the comparison operator is used in a Boolean context (e.g.,\n   in the condition of an "if" statement), Python will call "bool()"\n   on the value to determine if the result is true or false.\n\n   By default, "__ne__()" delegates to "__eq__()" and inverts the\n   result unless it is "NotImplemented".  There are no other implied\n   relationships among the comparison operators, for example, the\n   truth of "(x<y or x==y)" does not imply "x<=y". To automatically\n   generate ordering operations from a single root operation, see\n   "functools.total_ordering()".\n\n   See the paragraph on "__hash__()" for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\n\n   There are no swapped-argument versions of these methods (to be used\n   when the left argument does not support the operation but the right\n   argument does); rather, "__lt__()" and "__gt__()" are each other\'s\n   reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n   and "__eq__()" and "__ne__()" are their own reflection. If the\n   operands are of different types, and right operand\'s type is a\n   direct or indirect subclass of the left operand\'s type, the\n   reflected method of the right operand has priority, otherwise the\n   left operand\'s method has priority.  Virtual subclassing is not\n   considered.\n\nobject.__hash__(self)\n\n   Called by built-in function "hash()" and for operations on members\n   of hashed collections including "set", "frozenset", and "dict".\n   "__hash__()" should return an integer.  The only required property\n   is that objects which compare equal have the same hash value; it is\n   advised to somehow mix together (e.g. using exclusive or) the hash\n   values for the components of the object that also play a part in\n   comparison of objects.\n\n   Note: "hash()" truncates the value returned from an object\'s\n     custom "__hash__()" method to the size of a "Py_ssize_t".  This\n     is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit\n     builds. If an object\'s   "__hash__()" must interoperate on builds\n     of different bit sizes, be sure to check the width on all\n     supported builds.  An easy way to do this is with "python -c\n     "import sys; print(sys.hash_info.width)"".\n\n   If a class does not define an "__eq__()" method it should not\n   define a "__hash__()" operation either; if it defines "__eq__()"\n   but not "__hash__()", its instances will not be usable as items in\n   hashable collections.  If a class defines mutable objects and\n   implements an "__eq__()" method, it should not implement\n   "__hash__()", since the implementation of hashable collections\n   requires that a key\'s hash value is immutable (if the object\'s hash\n   value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have "__eq__()" and "__hash__()" methods by\n   default; with them, all objects compare unequal (except with\n   themselves) and "x.__hash__()" returns an appropriate value such\n   that "x == y" implies both that "x is y" and "hash(x) == hash(y)".\n\n   A class that overrides "__eq__()" and does not define "__hash__()"\n   will have its "__hash__()" implicitly set to "None".  When the\n   "__hash__()" method of a class is "None", instances of the class\n   will raise an appropriate "TypeError" when a program attempts to\n   retrieve their hash value, and will also be correctly identified as\n   unhashable when checking "isinstance(obj, collections.Hashable)".\n\n   If a class that overrides "__eq__()" needs to retain the\n   implementation of "__hash__()" from a parent class, the interpreter\n   must be told this explicitly by setting "__hash__ =\n   <ParentClass>.__hash__".\n\n   If a class that does not override "__eq__()" wishes to suppress\n   hash support, it should include "__hash__ = None" in the class\n   definition. A class which defines its own "__hash__()" that\n   explicitly raises a "TypeError" would be incorrectly identified as\n   hashable by an "isinstance(obj, collections.Hashable)" call.\n\n   Note: By default, the "__hash__()" values of str, bytes and\n     datetime objects are "salted" with an unpredictable random value.\n     Although they remain constant within an individual Python\n     process, they are not predictable between repeated invocations of\n     Python.This is intended to provide protection against a denial-\n     of-service caused by carefully-chosen inputs that exploit the\n     worst case performance of a dict insertion, O(n^2) complexity.\n     See http://www.ocert.org/advisories/ocert-2011-003.html for\n     details.Changing hash values affects the iteration order of\n     dicts, sets and other mappings.  Python has never made guarantees\n     about this ordering (and it typically varies between 32-bit and\n     64-bit builds).See also "PYTHONHASHSEED".\n\n   Changed in version 3.3: Hash randomization is enabled by default.\n\nobject.__bool__(self)\n\n   Called to implement truth value testing and the built-in operation\n   "bool()"; should return "False" or "True".  When this method is not\n   defined, "__len__()" is called, if it is defined, and the object is\n   considered true if its result is nonzero.  If a class defines\n   neither "__len__()" nor "__bool__()", all its instances are\n   considered true.\n',
- 'debugger': u'\n"pdb" --- The Python Debugger\n*****************************\n\n**Source code:** Lib/pdb.py\n\n======================================================================\n\nThe module "pdb" defines an interactive source code debugger for\nPython programs.  It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame.  It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible -- it is actually defined as the class\n"Pdb". This is currently undocumented but easily understood by reading\nthe source.  The extension interface uses the modules "bdb" and "cmd".\n\nThe debugger\'s prompt is "(Pdb)". Typical usage to run a program under\ncontrol of the debugger is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> pdb.run(\'mymodule.test()\')\n   > <string>(0)?()\n   (Pdb) continue\n   > <string>(1)?()\n   (Pdb) continue\n   NameError: \'spam\'\n   > <string>(1)?()\n   (Pdb)\n\nChanged in version 3.3: Tab-completion via the "readline" module is\navailable for commands and command arguments, e.g. the current global\nand local names are offered as arguments of the "p" command.\n\n"pdb.py" can also be invoked as a script to debug other scripts.  For\nexample:\n\n   python3 -m pdb myscript.py\n\nWhen invoked as a script, pdb will automatically enter post-mortem\ndebugging if the program being debugged exits abnormally.  After post-\nmortem debugging (or after normal exit of the program), pdb will\nrestart the program.  Automatic restarting preserves pdb\'s state (such\nas breakpoints) and in most cases is more useful than quitting the\ndebugger upon program\'s exit.\n\nNew in version 3.2: "pdb.py" now accepts a "-c" option that executes\ncommands as if given in a ".pdbrc" file, see *Debugger Commands*.\n\nThe typical usage to break into the debugger from a running program is\nto insert\n\n   import pdb; pdb.set_trace()\n\nat the location you want to break into the debugger.  You can then\nstep through the code following this statement, and continue running\nwithout the debugger using the "continue" command.\n\nThe typical usage to inspect a crashed program is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> mymodule.test()\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n     File "./mymodule.py", line 4, in test\n       test2()\n     File "./mymodule.py", line 3, in test2\n       print(spam)\n   NameError: spam\n   >>> pdb.pm()\n   > ./mymodule.py(3)test2()\n   -> print(spam)\n   (Pdb)\n\nThe module defines the following functions; each enters the debugger\nin a slightly different way:\n\npdb.run(statement, globals=None, locals=None)\n\n   Execute the *statement* (given as a string or a code object) under\n   debugger control.  The debugger prompt appears before any code is\n   executed; you can set breakpoints and type "continue", or you can\n   step through the statement using "step" or "next" (all these\n   commands are explained below).  The optional *globals* and *locals*\n   arguments specify the environment in which the code is executed; by\n   default the dictionary of the module "__main__" is used.  (See the\n   explanation of the built-in "exec()" or "eval()" functions.)\n\npdb.runeval(expression, globals=None, locals=None)\n\n   Evaluate the *expression* (given as a string or a code object)\n   under debugger control.  When "runeval()" returns, it returns the\n   value of the expression.  Otherwise this function is similar to\n   "run()".\n\npdb.runcall(function, *args, **kwds)\n\n   Call the *function* (a function or method object, not a string)\n   with the given arguments.  When "runcall()" returns, it returns\n   whatever the function call returned.  The debugger prompt appears\n   as soon as the function is entered.\n\npdb.set_trace()\n\n   Enter the debugger at the calling stack frame.  This is useful to\n   hard-code a breakpoint at a given point in a program, even if the\n   code is not otherwise being debugged (e.g. when an assertion\n   fails).\n\npdb.post_mortem(traceback=None)\n\n   Enter post-mortem debugging of the given *traceback* object.  If no\n   *traceback* is given, it uses the one of the exception that is\n   currently being handled (an exception must be being handled if the\n   default is to be used).\n\npdb.pm()\n\n   Enter post-mortem debugging of the traceback found in\n   "sys.last_traceback".\n\nThe "run*" functions and "set_trace()" are aliases for instantiating\nthe "Pdb" class and calling the method of the same name.  If you want\nto access further features, you have to do this yourself:\n\nclass class pdb.Pdb(completekey=\'tab\', stdin=None, stdout=None, skip=None, nosigint=False)\n\n   "Pdb" is the debugger class.\n\n   The *completekey*, *stdin* and *stdout* arguments are passed to the\n   underlying "cmd.Cmd" class; see the description there.\n\n   The *skip* argument, if given, must be an iterable of glob-style\n   module name patterns.  The debugger will not step into frames that\n   originate in a module that matches one of these patterns. [1]\n\n   By default, Pdb sets a handler for the SIGINT signal (which is sent\n   when the user presses "Ctrl-C" on the console) when you give a\n   "continue" command. This allows you to break into the debugger\n   again by pressing "Ctrl-C".  If you want Pdb not to touch the\n   SIGINT handler, set *nosigint* tot true.\n\n   Example call to enable tracing with *skip*:\n\n      import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n   New in version 3.1: The *skip* argument.\n\n   New in version 3.2: The *nosigint* argument.  Previously, a SIGINT\n   handler was never set by Pdb.\n\n   run(statement, globals=None, locals=None)\n   runeval(expression, globals=None, locals=None)\n   runcall(function, *args, **kwds)\n   set_trace()\n\n      See the documentation for the functions explained above.\n\n\nDebugger Commands\n=================\n\nThe commands recognized by the debugger are listed below.  Most\ncommands can be abbreviated to one or two letters as indicated; e.g.\n"h(elp)" means that either "h" or "help" can be used to enter the help\ncommand (but not "he" or "hel", nor "H" or "Help" or "HELP").\nArguments to commands must be separated by whitespace (spaces or\ntabs).  Optional arguments are enclosed in square brackets ("[]") in\nthe command syntax; the square brackets must not be typed.\nAlternatives in the command syntax are separated by a vertical bar\n("|").\n\nEntering a blank line repeats the last command entered.  Exception: if\nthe last command was a "list" command, the next 11 lines are listed.\n\nCommands that the debugger doesn\'t recognize are assumed to be Python\nstatements and are executed in the context of the program being\ndebugged.  Python statements can also be prefixed with an exclamation\npoint ("!").  This is a powerful way to inspect the program being\ndebugged; it is even possible to change a variable or call a function.\nWhen an exception occurs in such a statement, the exception name is\nprinted but the debugger\'s state is not changed.\n\nThe debugger supports *aliases*.  Aliases can have parameters which\nallows one a certain level of adaptability to the context under\nexamination.\n\nMultiple commands may be entered on a single line, separated by ";;".\n(A single ";" is not used as it is the separator for multiple commands\nin a line that is passed to the Python parser.)  No intelligence is\napplied to separating the commands; the input is split at the first\n";;" pair, even if it is in the middle of a quoted string.\n\nIf a file ".pdbrc" exists in the user\'s home directory or in the\ncurrent directory, it is read in and executed as if it had been typed\nat the debugger prompt.  This is particularly useful for aliases.  If\nboth files exist, the one in the home directory is read first and\naliases defined there can be overridden by the local file.\n\nChanged in version 3.2: ".pdbrc" can now contain commands that\ncontinue debugging, such as "continue" or "next".  Previously, these\ncommands had no effect.\n\nh(elp) [command]\n\n   Without argument, print the list of available commands.  With a\n   *command* as argument, print help about that command.  "help pdb"\n   displays the full documentation (the docstring of the "pdb"\n   module).  Since the *command* argument must be an identifier, "help\n   exec" must be entered to get help on the "!" command.\n\nw(here)\n\n   Print a stack trace, with the most recent frame at the bottom.  An\n   arrow indicates the current frame, which determines the context of\n   most commands.\n\nd(own) [count]\n\n   Move the current frame *count* (default one) levels down in the\n   stack trace (to a newer frame).\n\nu(p) [count]\n\n   Move the current frame *count* (default one) levels up in the stack\n   trace (to an older frame).\n\nb(reak) [([filename:]lineno | function) [, condition]]\n\n   With a *lineno* argument, set a break there in the current file.\n   With a *function* argument, set a break at the first executable\n   statement within that function.  The line number may be prefixed\n   with a filename and a colon, to specify a breakpoint in another\n   file (probably one that hasn\'t been loaded yet).  The file is\n   searched on "sys.path".  Note that each breakpoint is assigned a\n   number to which all the other breakpoint commands refer.\n\n   If a second argument is present, it is an expression which must\n   evaluate to true before the breakpoint is honored.\n\n   Without argument, list all breaks, including for each breakpoint,\n   the number of times that breakpoint has been hit, the current\n   ignore count, and the associated condition if any.\n\ntbreak [([filename:]lineno | function) [, condition]]\n\n   Temporary breakpoint, which is removed automatically when it is\n   first hit. The arguments are the same as for "break".\n\ncl(ear) [filename:lineno | bpnumber [bpnumber ...]]\n\n   With a *filename:lineno* argument, clear all the breakpoints at\n   this line. With a space separated list of breakpoint numbers, clear\n   those breakpoints. Without argument, clear all breaks (but first\n   ask confirmation).\n\ndisable [bpnumber [bpnumber ...]]\n\n   Disable the breakpoints given as a space separated list of\n   breakpoint numbers.  Disabling a breakpoint means it cannot cause\n   the program to stop execution, but unlike clearing a breakpoint, it\n   remains in the list of breakpoints and can be (re-)enabled.\n\nenable [bpnumber [bpnumber ...]]\n\n   Enable the breakpoints specified.\n\nignore bpnumber [count]\n\n   Set the ignore count for the given breakpoint number.  If count is\n   omitted, the ignore count is set to 0.  A breakpoint becomes active\n   when the ignore count is zero.  When non-zero, the count is\n   decremented each time the breakpoint is reached and the breakpoint\n   is not disabled and any associated condition evaluates to true.\n\ncondition bpnumber [condition]\n\n   Set a new *condition* for the breakpoint, an expression which must\n   evaluate to true before the breakpoint is honored.  If *condition*\n   is absent, any existing condition is removed; i.e., the breakpoint\n   is made unconditional.\n\ncommands [bpnumber]\n\n   Specify a list of commands for breakpoint number *bpnumber*.  The\n   commands themselves appear on the following lines.  Type a line\n   containing just "end" to terminate the commands. An example:\n\n      (Pdb) commands 1\n      (com) p some_variable\n      (com) end\n      (Pdb)\n\n   To remove all commands from a breakpoint, type commands and follow\n   it immediately with "end"; that is, give no commands.\n\n   With no *bpnumber* argument, commands refers to the last breakpoint\n   set.\n\n   You can use breakpoint commands to start your program up again.\n   Simply use the continue command, or step, or any other command that\n   resumes execution.\n\n   Specifying any command resuming execution (currently continue,\n   step, next, return, jump, quit and their abbreviations) terminates\n   the command list (as if that command was immediately followed by\n   end). This is because any time you resume execution (even with a\n   simple next or step), you may encounter another breakpoint--which\n   could have its own command list, leading to ambiguities about which\n   list to execute.\n\n   If you use the \'silent\' command in the command list, the usual\n   message about stopping at a breakpoint is not printed.  This may be\n   desirable for breakpoints that are to print a specific message and\n   then continue.  If none of the other commands print anything, you\n   see no sign that the breakpoint was reached.\n\ns(tep)\n\n   Execute the current line, stop at the first possible occasion\n   (either in a function that is called or on the next line in the\n   current function).\n\nn(ext)\n\n   Continue execution until the next line in the current function is\n   reached or it returns.  (The difference between "next" and "step"\n   is that "step" stops inside a called function, while "next"\n   executes called functions at (nearly) full speed, only stopping at\n   the next line in the current function.)\n\nunt(il) [lineno]\n\n   Without argument, continue execution until the line with a number\n   greater than the current one is reached.\n\n   With a line number, continue execution until a line with a number\n   greater or equal to that is reached.  In both cases, also stop when\n   the current frame returns.\n\n   Changed in version 3.2: Allow giving an explicit line number.\n\nr(eturn)\n\n   Continue execution until the current function returns.\n\nc(ont(inue))\n\n   Continue execution, only stop when a breakpoint is encountered.\n\nj(ump) lineno\n\n   Set the next line that will be executed.  Only available in the\n   bottom-most frame.  This lets you jump back and execute code again,\n   or jump forward to skip code that you don\'t want to run.\n\n   It should be noted that not all jumps are allowed -- for instance\n   it is not possible to jump into the middle of a "for" loop or out\n   of a "finally" clause.\n\nl(ist) [first[, last]]\n\n   List source code for the current file.  Without arguments, list 11\n   lines around the current line or continue the previous listing.\n   With "." as argument, list 11 lines around the current line.  With\n   one argument, list 11 lines around at that line.  With two\n   arguments, list the given range; if the second argument is less\n   than the first, it is interpreted as a count.\n\n   The current line in the current frame is indicated by "->".  If an\n   exception is being debugged, the line where the exception was\n   originally raised or propagated is indicated by ">>", if it differs\n   from the current line.\n\n   New in version 3.2: The ">>" marker.\n\nll | longlist\n\n   List all source code for the current function or frame.\n   Interesting lines are marked as for "list".\n\n   New in version 3.2.\n\na(rgs)\n\n   Print the argument list of the current function.\n\np expression\n\n   Evaluate the *expression* in the current context and print its\n   value.\n\n   Note: "print()" can also be used, but is not a debugger command\n     --- this executes the Python "print()" function.\n\npp expression\n\n   Like the "p" command, except the value of the expression is pretty-\n   printed using the "pprint" module.\n\nwhatis expression\n\n   Print the type of the *expression*.\n\nsource expression\n\n   Try to get source code for the given object and display it.\n\n   New in version 3.2.\n\ndisplay [expression]\n\n   Display the value of the expression if it changed, each time\n   execution stops in the current frame.\n\n   Without expression, list all display expressions for the current\n   frame.\n\n   New in version 3.2.\n\nundisplay [expression]\n\n   Do not display the expression any more in the current frame.\n   Without expression, clear all display expressions for the current\n   frame.\n\n   New in version 3.2.\n\ninteract\n\n   Start an interative interpreter (using the "code" module) whose\n   global namespace contains all the (global and local) names found in\n   the current scope.\n\n   New in version 3.2.\n\nalias [name [command]]\n\n   Create an alias called *name* that executes *command*.  The command\n   must *not* be enclosed in quotes.  Replaceable parameters can be\n   indicated by "%1", "%2", and so on, while "%*" is replaced by all\n   the parameters. If no command is given, the current alias for\n   *name* is shown. If no arguments are given, all aliases are listed.\n\n   Aliases may be nested and can contain anything that can be legally\n   typed at the pdb prompt.  Note that internal pdb commands *can* be\n   overridden by aliases.  Such a command is then hidden until the\n   alias is removed.  Aliasing is recursively applied to the first\n   word of the command line; all other words in the line are left\n   alone.\n\n   As an example, here are two useful aliases (especially when placed\n   in the ".pdbrc" file):\n\n      # Print instance variables (usage "pi classInst")\n      alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])\n      # Print instance variables in self\n      alias ps pi self\n\nunalias name\n\n   Delete the specified alias.\n\n! statement\n\n   Execute the (one-line) *statement* in the context of the current\n   stack frame. The exclamation point can be omitted unless the first\n   word of the statement resembles a debugger command.  To set a\n   global variable, you can prefix the assignment command with a\n   "global" statement on the same line, e.g.:\n\n      (Pdb) global list_options; list_options = [\'-l\']\n      (Pdb)\n\nrun [args ...]\nrestart [args ...]\n\n   Restart the debugged Python program.  If an argument is supplied,\n   it is split with "shlex" and the result is used as the new\n   "sys.argv". History, breakpoints, actions and debugger options are\n   preserved. "restart" is an alias for "run".\n\nq(uit)\n\n   Quit from the debugger.  The program being executed is aborted.\n\n-[ Footnotes ]-\n\n[1] Whether a frame is considered to originate in a certain module\n    is determined by the "__name__" in the frame globals.\n',
+ 'customization': u'\nBasic customization\n*******************\n\nobject.__new__(cls[, ...])\n\n   Called to create a new instance of class *cls*.  "__new__()" is a\n   static method (special-cased so you need not declare it as such)\n   that takes the class of which an instance was requested as its\n   first argument.  The remaining arguments are those passed to the\n   object constructor expression (the call to the class).  The return\n   value of "__new__()" should be the new object instance (usually an\n   instance of *cls*).\n\n   Typical implementations create a new instance of the class by\n   invoking the superclass\'s "__new__()" method using\n   "super(currentclass, cls).__new__(cls[, ...])" with appropriate\n   arguments and then modifying the newly-created instance as\n   necessary before returning it.\n\n   If "__new__()" returns an instance of *cls*, then the new\n   instance\'s "__init__()" method will be invoked like\n   "__init__(self[, ...])", where *self* is the new instance and the\n   remaining arguments are the same as were passed to "__new__()".\n\n   If "__new__()" does not return an instance of *cls*, then the new\n   instance\'s "__init__()" method will not be invoked.\n\n   "__new__()" is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called after the instance has been created (by "__new__()"), but\n   before it is returned to the caller.  The arguments are those\n   passed to the class constructor expression.  If a base class has an\n   "__init__()" method, the derived class\'s "__init__()" method, if\n   any, must explicitly call it to ensure proper initialization of the\n   base class part of the instance; for example:\n   "BaseClass.__init__(self, [args...])".\n\n   Because "__new__()" and "__init__()" work together in constructing\n   objects ("__new__()" to create it, and "__init__()" to customize\n   it), no non-"None" value may be returned by "__init__()"; doing so\n   will cause a "TypeError" to be raised at runtime.\n\nobject.__del__(self)\n\n   Called when the instance is about to be destroyed.  This is also\n   called a destructor.  If a base class has a "__del__()" method, the\n   derived class\'s "__del__()" method, if any, must explicitly call it\n   to ensure proper deletion of the base class part of the instance.\n   Note that it is possible (though not recommended!) for the\n   "__del__()" method to postpone destruction of the instance by\n   creating a new reference to it.  It may then be called at a later\n   time when this new reference is deleted.  It is not guaranteed that\n   "__del__()" methods are called for objects that still exist when\n   the interpreter exits.\n\n   Note: "del x" doesn\'t directly call "x.__del__()" --- the former\n     decrements the reference count for "x" by one, and the latter is\n     only called when "x"\'s reference count reaches zero.  Some common\n     situations that may prevent the reference count of an object from\n     going to zero include: circular references between objects (e.g.,\n     a doubly-linked list or a tree data structure with parent and\n     child pointers); a reference to the object on the stack frame of\n     a function that caught an exception (the traceback stored in\n     "sys.exc_info()[2]" keeps the stack frame alive); or a reference\n     to the object on the stack frame that raised an unhandled\n     exception in interactive mode (the traceback stored in\n     "sys.last_traceback" keeps the stack frame alive).  The first\n     situation can only be remedied by explicitly breaking the cycles;\n     the second can be resolved by freeing the reference to the\n     traceback object when it is no longer useful, and the third can\n     be resolved by storing "None" in "sys.last_traceback". Circular\n     references which are garbage are detected and cleaned up when the\n     cyclic garbage collector is enabled (it\'s on by default). Refer\n     to the documentation for the "gc" module for more information\n     about this topic.\n\n   Warning: Due to the precarious circumstances under which\n     "__del__()" methods are invoked, exceptions that occur during\n     their execution are ignored, and a warning is printed to\n     "sys.stderr" instead. Also, when "__del__()" is invoked in\n     response to a module being deleted (e.g., when execution of the\n     program is done), other globals referenced by the "__del__()"\n     method may already have been deleted or in the process of being\n     torn down (e.g. the import machinery shutting down).  For this\n     reason, "__del__()" methods should do the absolute minimum needed\n     to maintain external invariants.  Starting with version 1.5,\n     Python guarantees that globals whose name begins with a single\n     underscore are deleted from their module before other globals are\n     deleted; if no other references to such globals exist, this may\n     help in assuring that imported modules are still available at the\n     time when the "__del__()" method is called.\n\nobject.__repr__(self)\n\n   Called by the "repr()" built-in function to compute the "official"\n   string representation of an object.  If at all possible, this\n   should look like a valid Python expression that could be used to\n   recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   "<...some useful description...>" should be returned. The return\n   value must be a string object. If a class defines "__repr__()" but\n   not "__str__()", then "__repr__()" is also used when an "informal"\n   string representation of instances of that class is required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by "str(object)" and the built-in functions "format()" and\n   "print()" to compute the "informal" or nicely printable string\n   representation of an object.  The return value must be a *string*\n   object.\n\n   This method differs from "object.__repr__()" in that there is no\n   expectation that "__str__()" return a valid Python expression: a\n   more convenient or concise representation can be used.\n\n   The default implementation defined by the built-in type "object"\n   calls "object.__repr__()".\n\nobject.__bytes__(self)\n\n   Called by "bytes()" to compute a byte-string representation of an\n   object. This should return a "bytes" object.\n\nobject.__format__(self, format_spec)\n\n   Called by the "format()" built-in function (and by extension, the\n   "str.format()" method of class "str") to produce a "formatted"\n   string representation of an object. The "format_spec" argument is a\n   string that contains a description of the formatting options\n   desired. The interpretation of the "format_spec" argument is up to\n   the type implementing "__format__()", however most classes will\n   either delegate formatting to one of the built-in types, or use a\n   similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\n   Changed in version 3.4: The __format__ method of "object" itself\n   raises a "TypeError" if passed any non-empty string.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",\n   "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls\n   "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n   A rich comparison method may return the singleton "NotImplemented"\n   if it does not implement the operation for a given pair of\n   arguments. By convention, "False" and "True" are returned for a\n   successful comparison. However, these methods can return any value,\n   so if the comparison operator is used in a Boolean context (e.g.,\n   in the condition of an "if" statement), Python will call "bool()"\n   on the value to determine if the result is true or false.\n\n   By default, "__ne__()" delegates to "__eq__()" and inverts the\n   result unless it is "NotImplemented".  There are no other implied\n   relationships among the comparison operators, for example, the\n   truth of "(x<y or x==y)" does not imply "x<=y". To automatically\n   generate ordering operations from a single root operation, see\n   "functools.total_ordering()".\n\n   See the paragraph on "__hash__()" for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\n\n   There are no swapped-argument versions of these methods (to be used\n   when the left argument does not support the operation but the right\n   argument does); rather, "__lt__()" and "__gt__()" are each other\'s\n   reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n   and "__eq__()" and "__ne__()" are their own reflection. If the\n   operands are of different types, and right operand\'s type is a\n   direct or indirect subclass of the left operand\'s type, the\n   reflected method of the right operand has priority, otherwise the\n   left operand\'s method has priority.  Virtual subclassing is not\n   considered.\n\nobject.__hash__(self)\n\n   Called by built-in function "hash()" and for operations on members\n   of hashed collections including "set", "frozenset", and "dict".\n   "__hash__()" should return an integer. The only required property\n   is that objects which compare equal have the same hash value; it is\n   advised to mix together the hash values of the components of the\n   object that also play a part in comparison of objects by packing\n   them into a tuple and hashing the tuple. Example:\n\n      def __hash__(self):\n          return hash((self.name, self.nick, self.color))\n\n   Note: "hash()" truncates the value returned from an object\'s\n     custom "__hash__()" method to the size of a "Py_ssize_t".  This\n     is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit\n     builds. If an object\'s   "__hash__()" must interoperate on builds\n     of different bit sizes, be sure to check the width on all\n     supported builds.  An easy way to do this is with "python -c\n     "import sys; print(sys.hash_info.width)"".\n\n   If a class does not define an "__eq__()" method it should not\n   define a "__hash__()" operation either; if it defines "__eq__()"\n   but not "__hash__()", its instances will not be usable as items in\n   hashable collections.  If a class defines mutable objects and\n   implements an "__eq__()" method, it should not implement\n   "__hash__()", since the implementation of hashable collections\n   requires that a key\'s hash value is immutable (if the object\'s hash\n   value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have "__eq__()" and "__hash__()" methods by\n   default; with them, all objects compare unequal (except with\n   themselves) and "x.__hash__()" returns an appropriate value such\n   that "x == y" implies both that "x is y" and "hash(x) == hash(y)".\n\n   A class that overrides "__eq__()" and does not define "__hash__()"\n   will have its "__hash__()" implicitly set to "None".  When the\n   "__hash__()" method of a class is "None", instances of the class\n   will raise an appropriate "TypeError" when a program attempts to\n   retrieve their hash value, and will also be correctly identified as\n   unhashable when checking "isinstance(obj, collections.Hashable)".\n\n   If a class that overrides "__eq__()" needs to retain the\n   implementation of "__hash__()" from a parent class, the interpreter\n   must be told this explicitly by setting "__hash__ =\n   <ParentClass>.__hash__".\n\n   If a class that does not override "__eq__()" wishes to suppress\n   hash support, it should include "__hash__ = None" in the class\n   definition. A class which defines its own "__hash__()" that\n   explicitly raises a "TypeError" would be incorrectly identified as\n   hashable by an "isinstance(obj, collections.Hashable)" call.\n\n   Note: By default, the "__hash__()" values of str, bytes and\n     datetime objects are "salted" with an unpredictable random value.\n     Although they remain constant within an individual Python\n     process, they are not predictable between repeated invocations of\n     Python.This is intended to provide protection against a denial-\n     of-service caused by carefully-chosen inputs that exploit the\n     worst case performance of a dict insertion, O(n^2) complexity.\n     See http://www.ocert.org/advisories/ocert-2011-003.html for\n     details.Changing hash values affects the iteration order of\n     dicts, sets and other mappings.  Python has never made guarantees\n     about this ordering (and it typically varies between 32-bit and\n     64-bit builds).See also "PYTHONHASHSEED".\n\n   Changed in version 3.3: Hash randomization is enabled by default.\n\nobject.__bool__(self)\n\n   Called to implement truth value testing and the built-in operation\n   "bool()"; should return "False" or "True".  When this method is not\n   defined, "__len__()" is called, if it is defined, and the object is\n   considered true if its result is nonzero.  If a class defines\n   neither "__len__()" nor "__bool__()", all its instances are\n   considered true.\n',
+ 'debugger': u'\n"pdb" --- The Python Debugger\n*****************************\n\n**Source code:** Lib/pdb.py\n\n======================================================================\n\nThe module "pdb" defines an interactive source code debugger for\nPython programs.  It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame.  It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible -- it is actually defined as the class\n"Pdb". This is currently undocumented but easily understood by reading\nthe source.  The extension interface uses the modules "bdb" and "cmd".\n\nThe debugger\'s prompt is "(Pdb)". Typical usage to run a program under\ncontrol of the debugger is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> pdb.run(\'mymodule.test()\')\n   > <string>(0)?()\n   (Pdb) continue\n   > <string>(1)?()\n   (Pdb) continue\n   NameError: \'spam\'\n   > <string>(1)?()\n   (Pdb)\n\nChanged in version 3.3: Tab-completion via the "readline" module is\navailable for commands and command arguments, e.g. the current global\nand local names are offered as arguments of the "p" command.\n\n"pdb.py" can also be invoked as a script to debug other scripts.  For\nexample:\n\n   python3 -m pdb myscript.py\n\nWhen invoked as a script, pdb will automatically enter post-mortem\ndebugging if the program being debugged exits abnormally.  After post-\nmortem debugging (or after normal exit of the program), pdb will\nrestart the program.  Automatic restarting preserves pdb\'s state (such\nas breakpoints) and in most cases is more useful than quitting the\ndebugger upon program\'s exit.\n\nNew in version 3.2: "pdb.py" now accepts a "-c" option that executes\ncommands as if given in a ".pdbrc" file, see *Debugger Commands*.\n\nThe typical usage to break into the debugger from a running program is\nto insert\n\n   import pdb; pdb.set_trace()\n\nat the location you want to break into the debugger.  You can then\nstep through the code following this statement, and continue running\nwithout the debugger using the "continue" command.\n\nThe typical usage to inspect a crashed program is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> mymodule.test()\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n     File "./mymodule.py", line 4, in test\n       test2()\n     File "./mymodule.py", line 3, in test2\n       print(spam)\n   NameError: spam\n   >>> pdb.pm()\n   > ./mymodule.py(3)test2()\n   -> print(spam)\n   (Pdb)\n\nThe module defines the following functions; each enters the debugger\nin a slightly different way:\n\npdb.run(statement, globals=None, locals=None)\n\n   Execute the *statement* (given as a string or a code object) under\n   debugger control.  The debugger prompt appears before any code is\n   executed; you can set breakpoints and type "continue", or you can\n   step through the statement using "step" or "next" (all these\n   commands are explained below).  The optional *globals* and *locals*\n   arguments specify the environment in which the code is executed; by\n   default the dictionary of the module "__main__" is used.  (See the\n   explanation of the built-in "exec()" or "eval()" functions.)\n\npdb.runeval(expression, globals=None, locals=None)\n\n   Evaluate the *expression* (given as a string or a code object)\n   under debugger control.  When "runeval()" returns, it returns the\n   value of the expression.  Otherwise this function is similar to\n   "run()".\n\npdb.runcall(function, *args, **kwds)\n\n   Call the *function* (a function or method object, not a string)\n   with the given arguments.  When "runcall()" returns, it returns\n   whatever the function call returned.  The debugger prompt appears\n   as soon as the function is entered.\n\npdb.set_trace()\n\n   Enter the debugger at the calling stack frame.  This is useful to\n   hard-code a breakpoint at a given point in a program, even if the\n   code is not otherwise being debugged (e.g. when an assertion\n   fails).\n\npdb.post_mortem(traceback=None)\n\n   Enter post-mortem debugging of the given *traceback* object.  If no\n   *traceback* is given, it uses the one of the exception that is\n   currently being handled (an exception must be being handled if the\n   default is to be used).\n\npdb.pm()\n\n   Enter post-mortem debugging of the traceback found in\n   "sys.last_traceback".\n\nThe "run*" functions and "set_trace()" are aliases for instantiating\nthe "Pdb" class and calling the method of the same name.  If you want\nto access further features, you have to do this yourself:\n\nclass class pdb.Pdb(completekey=\'tab\', stdin=None, stdout=None, skip=None, nosigint=False)\n\n   "Pdb" is the debugger class.\n\n   The *completekey*, *stdin* and *stdout* arguments are passed to the\n   underlying "cmd.Cmd" class; see the description there.\n\n   The *skip* argument, if given, must be an iterable of glob-style\n   module name patterns.  The debugger will not step into frames that\n   originate in a module that matches one of these patterns. [1]\n\n   By default, Pdb sets a handler for the SIGINT signal (which is sent\n   when the user presses "Ctrl-C" on the console) when you give a\n   "continue" command. This allows you to break into the debugger\n   again by pressing "Ctrl-C".  If you want Pdb not to touch the\n   SIGINT handler, set *nosigint* to true.\n\n   Example call to enable tracing with *skip*:\n\n      import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n   New in version 3.1: The *skip* argument.\n\n   New in version 3.2: The *nosigint* argument.  Previously, a SIGINT\n   handler was never set by Pdb.\n\n   run(statement, globals=None, locals=None)\n   runeval(expression, globals=None, locals=None)\n   runcall(function, *args, **kwds)\n   set_trace()\n\n      See the documentation for the functions explained above.\n\n\nDebugger Commands\n=================\n\nThe commands recognized by the debugger are listed below.  Most\ncommands can be abbreviated to one or two letters as indicated; e.g.\n"h(elp)" means that either "h" or "help" can be used to enter the help\ncommand (but not "he" or "hel", nor "H" or "Help" or "HELP").\nArguments to commands must be separated by whitespace (spaces or\ntabs).  Optional arguments are enclosed in square brackets ("[]") in\nthe command syntax; the square brackets must not be typed.\nAlternatives in the command syntax are separated by a vertical bar\n("|").\n\nEntering a blank line repeats the last command entered.  Exception: if\nthe last command was a "list" command, the next 11 lines are listed.\n\nCommands that the debugger doesn\'t recognize are assumed to be Python\nstatements and are executed in the context of the program being\ndebugged.  Python statements can also be prefixed with an exclamation\npoint ("!").  This is a powerful way to inspect the program being\ndebugged; it is even possible to change a variable or call a function.\nWhen an exception occurs in such a statement, the exception name is\nprinted but the debugger\'s state is not changed.\n\nThe debugger supports *aliases*.  Aliases can have parameters which\nallows one a certain level of adaptability to the context under\nexamination.\n\nMultiple commands may be entered on a single line, separated by ";;".\n(A single ";" is not used as it is the separator for multiple commands\nin a line that is passed to the Python parser.)  No intelligence is\napplied to separating the commands; the input is split at the first\n";;" pair, even if it is in the middle of a quoted string.\n\nIf a file ".pdbrc" exists in the user\'s home directory or in the\ncurrent directory, it is read in and executed as if it had been typed\nat the debugger prompt.  This is particularly useful for aliases.  If\nboth files exist, the one in the home directory is read first and\naliases defined there can be overridden by the local file.\n\nChanged in version 3.2: ".pdbrc" can now contain commands that\ncontinue debugging, such as "continue" or "next".  Previously, these\ncommands had no effect.\n\nh(elp) [command]\n\n   Without argument, print the list of available commands.  With a\n   *command* as argument, print help about that command.  "help pdb"\n   displays the full documentation (the docstring of the "pdb"\n   module).  Since the *command* argument must be an identifier, "help\n   exec" must be entered to get help on the "!" command.\n\nw(here)\n\n   Print a stack trace, with the most recent frame at the bottom.  An\n   arrow indicates the current frame, which determines the context of\n   most commands.\n\nd(own) [count]\n\n   Move the current frame *count* (default one) levels down in the\n   stack trace (to a newer frame).\n\nu(p) [count]\n\n   Move the current frame *count* (default one) levels up in the stack\n   trace (to an older frame).\n\nb(reak) [([filename:]lineno | function) [, condition]]\n\n   With a *lineno* argument, set a break there in the current file.\n   With a *function* argument, set a break at the first executable\n   statement within that function.  The line number may be prefixed\n   with a filename and a colon, to specify a breakpoint in another\n   file (probably one that hasn\'t been loaded yet).  The file is\n   searched on "sys.path".  Note that each breakpoint is assigned a\n   number to which all the other breakpoint commands refer.\n\n   If a second argument is present, it is an expression which must\n   evaluate to true before the breakpoint is honored.\n\n   Without argument, list all breaks, including for each breakpoint,\n   the number of times that breakpoint has been hit, the current\n   ignore count, and the associated condition if any.\n\ntbreak [([filename:]lineno | function) [, condition]]\n\n   Temporary breakpoint, which is removed automatically when it is\n   first hit. The arguments are the same as for "break".\n\ncl(ear) [filename:lineno | bpnumber [bpnumber ...]]\n\n   With a *filename:lineno* argument, clear all the breakpoints at\n   this line. With a space separated list of breakpoint numbers, clear\n   those breakpoints. Without argument, clear all breaks (but first\n   ask confirmation).\n\ndisable [bpnumber [bpnumber ...]]\n\n   Disable the breakpoints given as a space separated list of\n   breakpoint numbers.  Disabling a breakpoint means it cannot cause\n   the program to stop execution, but unlike clearing a breakpoint, it\n   remains in the list of breakpoints and can be (re-)enabled.\n\nenable [bpnumber [bpnumber ...]]\n\n   Enable the breakpoints specified.\n\nignore bpnumber [count]\n\n   Set the ignore count for the given breakpoint number.  If count is\n   omitted, the ignore count is set to 0.  A breakpoint becomes active\n   when the ignore count is zero.  When non-zero, the count is\n   decremented each time the breakpoint is reached and the breakpoint\n   is not disabled and any associated condition evaluates to true.\n\ncondition bpnumber [condition]\n\n   Set a new *condition* for the breakpoint, an expression which must\n   evaluate to true before the breakpoint is honored.  If *condition*\n   is absent, any existing condition is removed; i.e., the breakpoint\n   is made unconditional.\n\ncommands [bpnumber]\n\n   Specify a list of commands for breakpoint number *bpnumber*.  The\n   commands themselves appear on the following lines.  Type a line\n   containing just "end" to terminate the commands. An example:\n\n      (Pdb) commands 1\n      (com) p some_variable\n      (com) end\n      (Pdb)\n\n   To remove all commands from a breakpoint, type commands and follow\n   it immediately with "end"; that is, give no commands.\n\n   With no *bpnumber* argument, commands refers to the last breakpoint\n   set.\n\n   You can use breakpoint commands to start your program up again.\n   Simply use the continue command, or step, or any other command that\n   resumes execution.\n\n   Specifying any command resuming execution (currently continue,\n   step, next, return, jump, quit and their abbreviations) terminates\n   the command list (as if that command was immediately followed by\n   end). This is because any time you resume execution (even with a\n   simple next or step), you may encounter another breakpoint\u2014which\n   could have its own command list, leading to ambiguities about which\n   list to execute.\n\n   If you use the \'silent\' command in the command list, the usual\n   message about stopping at a breakpoint is not printed.  This may be\n   desirable for breakpoints that are to print a specific message and\n   then continue.  If none of the other commands print anything, you\n   see no sign that the breakpoint was reached.\n\ns(tep)\n\n   Execute the current line, stop at the first possible occasion\n   (either in a function that is called or on the next line in the\n   current function).\n\nn(ext)\n\n   Continue execution until the next line in the current function is\n   reached or it returns.  (The difference between "next" and "step"\n   is that "step" stops inside a called function, while "next"\n   executes called functions at (nearly) full speed, only stopping at\n   the next line in the current function.)\n\nunt(il) [lineno]\n\n   Without argument, continue execution until the line with a number\n   greater than the current one is reached.\n\n   With a line number, continue execution until a line with a number\n   greater or equal to that is reached.  In both cases, also stop when\n   the current frame returns.\n\n   Changed in version 3.2: Allow giving an explicit line number.\n\nr(eturn)\n\n   Continue execution until the current function returns.\n\nc(ont(inue))\n\n   Continue execution, only stop when a breakpoint is encountered.\n\nj(ump) lineno\n\n   Set the next line that will be executed.  Only available in the\n   bottom-most frame.  This lets you jump back and execute code again,\n   or jump forward to skip code that you don\'t want to run.\n\n   It should be noted that not all jumps are allowed -- for instance\n   it is not possible to jump into the middle of a "for" loop or out\n   of a "finally" clause.\n\nl(ist) [first[, last]]\n\n   List source code for the current file.  Without arguments, list 11\n   lines around the current line or continue the previous listing.\n   With "." as argument, list 11 lines around the current line.  With\n   one argument, list 11 lines around at that line.  With two\n   arguments, list the given range; if the second argument is less\n   than the first, it is interpreted as a count.\n\n   The current line in the current frame is indicated by "->".  If an\n   exception is being debugged, the line where the exception was\n   originally raised or propagated is indicated by ">>", if it differs\n   from the current line.\n\n   New in version 3.2: The ">>" marker.\n\nll | longlist\n\n   List all source code for the current function or frame.\n   Interesting lines are marked as for "list".\n\n   New in version 3.2.\n\na(rgs)\n\n   Print the argument list of the current function.\n\np expression\n\n   Evaluate the *expression* in the current context and print its\n   value.\n\n   Note: "print()" can also be used, but is not a debugger command\n     --- this executes the Python "print()" function.\n\npp expression\n\n   Like the "p" command, except the value of the expression is pretty-\n   printed using the "pprint" module.\n\nwhatis expression\n\n   Print the type of the *expression*.\n\nsource expression\n\n   Try to get source code for the given object and display it.\n\n   New in version 3.2.\n\ndisplay [expression]\n\n   Display the value of the expression if it changed, each time\n   execution stops in the current frame.\n\n   Without expression, list all display expressions for the current\n   frame.\n\n   New in version 3.2.\n\nundisplay [expression]\n\n   Do not display the expression any more in the current frame.\n   Without expression, clear all display expressions for the current\n   frame.\n\n   New in version 3.2.\n\ninteract\n\n   Start an interactive interpreter (using the "code" module) whose\n   global namespace contains all the (global and local) names found in\n   the current scope.\n\n   New in version 3.2.\n\nalias [name [command]]\n\n   Create an alias called *name* that executes *command*.  The command\n   must *not* be enclosed in quotes.  Replaceable parameters can be\n   indicated by "%1", "%2", and so on, while "%*" is replaced by all\n   the parameters. If no command is given, the current alias for\n   *name* is shown. If no arguments are given, all aliases are listed.\n\n   Aliases may be nested and can contain anything that can be legally\n   typed at the pdb prompt.  Note that internal pdb commands *can* be\n   overridden by aliases.  Such a command is then hidden until the\n   alias is removed.  Aliasing is recursively applied to the first\n   word of the command line; all other words in the line are left\n   alone.\n\n   As an example, here are two useful aliases (especially when placed\n   in the ".pdbrc" file):\n\n      # Print instance variables (usage "pi classInst")\n      alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])\n      # Print instance variables in self\n      alias ps pi self\n\nunalias name\n\n   Delete the specified alias.\n\n! statement\n\n   Execute the (one-line) *statement* in the context of the current\n   stack frame. The exclamation point can be omitted unless the first\n   word of the statement resembles a debugger command.  To set a\n   global variable, you can prefix the assignment command with a\n   "global" statement on the same line, e.g.:\n\n      (Pdb) global list_options; list_options = [\'-l\']\n      (Pdb)\n\nrun [args ...]\nrestart [args ...]\n\n   Restart the debugged Python program.  If an argument is supplied,\n   it is split with "shlex" and the result is used as the new\n   "sys.argv". History, breakpoints, actions and debugger options are\n   preserved. "restart" is an alias for "run".\n\nq(uit)\n\n   Quit from the debugger.  The program being executed is aborted.\n\n-[ Footnotes ]-\n\n[1] Whether a frame is considered to originate in a certain module\n    is determined by the "__name__" in the frame globals.\n',
  'del': u'\nThe "del" statement\n*******************\n\n   del_stmt ::= "del" target_list\n\nDeletion is recursively defined very similar to the way assignment is\ndefined. Rather than spelling it out in full details, here are some\nhints.\n\nDeletion of a target list recursively deletes each target, from left\nto right.\n\nDeletion of a name removes the binding of that name from the local or\nglobal namespace, depending on whether the name occurs in a "global"\nstatement in the same code block.  If the name is unbound, a\n"NameError" exception will be raised.\n\nDeletion of attribute references, subscriptions and slicings is passed\nto the primary object involved; deletion of a slicing is in general\nequivalent to assignment of an empty slice of the right type (but even\nthis is determined by the sliced object).\n\nChanged in version 3.2: Previously it was illegal to delete a name\nfrom the local namespace if it occurs as a free variable in a nested\nblock.\n',
  'dict': u'\nDictionary displays\n*******************\n\nA dictionary display is a possibly empty series of key/datum pairs\nenclosed in curly braces:\n\n   dict_display       ::= "{" [key_datum_list | dict_comprehension] "}"\n   key_datum_list     ::= key_datum ("," key_datum)* [","]\n   key_datum          ::= expression ":" expression | "**" or_expr\n   dict_comprehension ::= expression ":" expression comp_for\n\nA dictionary display yields a new dictionary object.\n\nIf a comma-separated sequence of key/datum pairs is given, they are\nevaluated from left to right to define the entries of the dictionary:\neach key object is used as a key into the dictionary to store the\ncorresponding datum.  This means that you can specify the same key\nmultiple times in the key/datum list, and the final dictionary\'s value\nfor that key will be the last one given.\n\nA double asterisk "**" denotes *dictionary unpacking*. Its operand\nmust be a *mapping*.  Each mapping item is added to the new\ndictionary.  Later values replace values already set by earlier\nkey/datum pairs and earlier dictionary unpackings.\n\nNew in version 3.5: Unpacking into dictionary displays, originally\nproposed by **PEP 448**.\n\nA dict comprehension, in contrast to list and set comprehensions,\nneeds two expressions separated with a colon followed by the usual\n"for" and "if" clauses. When the comprehension is run, the resulting\nkey and value elements are inserted in the new dictionary in the order\nthey are produced.\n\nRestrictions on the types of the key values are listed earlier in\nsection *The standard type hierarchy*.  (To summarize, the key type\nshould be *hashable*, which excludes all mutable objects.)  Clashes\nbetween duplicate keys are not detected; the last datum (textually\nrightmost in the display) stored for a given key value prevails.\n',
  'dynamic-features': u'\nInteraction with dynamic features\n*********************************\n\nName resolution of free variables occurs at runtime, not at compile\ntime. This means that the following code will print 42:\n\n   i = 10\n   def f():\n       print(i)\n   i = 42\n   f()\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nThe "eval()" and "exec()" functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe "exec()" and "eval()" functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n',
@@ -34,8 +34,8 @@ topics = {'assert': u'\nThe "assert" statement\n**********************\n\nAssert
  'exprlists': u'\nExpression lists\n****************\n\n   expression_list    ::= expression ( "," expression )* [","]\n   starred_list       ::= starred_item ( "," starred_item )* [","]\n   starred_expression ::= expression | ( starred_item "," )* [starred_item]\n   starred_item       ::= expression | "*" or_expr\n\nExcept when part of a list or set display, an expression list\ncontaining at least one comma yields a tuple.  The length of the tuple\nis the number of expressions in the list.  The expressions are\nevaluated from left to right.\n\nAn asterisk "*" denotes *iterable unpacking*.  Its operand must be an\n*iterable*.  The iterable is expanded into a sequence of items, which\nare included in the new tuple, list, or set, at the site of the\nunpacking.\n\nNew in version 3.5: Iterable unpacking in expression lists, originally\nproposed by **PEP 448**.\n\nThe trailing comma is required only to create a single tuple (a.k.a. a\n*singleton*); it is optional in all other cases.  A single expression\nwithout a trailing comma doesn\'t create a tuple, but rather yields the\nvalue of that expression. (To create an empty tuple, use an empty pair\nof parentheses: "()".)\n',
  'floating': u'\nFloating point literals\n***********************\n\nFloating point literals are described by the following lexical\ndefinitions:\n\n   floatnumber   ::= pointfloat | exponentfloat\n   pointfloat    ::= [intpart] fraction | intpart "."\n   exponentfloat ::= (intpart | pointfloat) exponent\n   intpart       ::= digit+\n   fraction      ::= "." digit+\n   exponent      ::= ("e" | "E") ["+" | "-"] digit+\n\nNote that the integer and exponent parts are always interpreted using\nradix 10. For example, "077e010" is legal, and denotes the same number\nas "77e10". The allowed range of floating point literals is\nimplementation-dependent. Some examples of floating point literals:\n\n   3.14    10.    .001    1e100    3.14e-10    0e0\n\nNote that numeric literals do not include a sign; a phrase like "-1"\nis actually an expression composed of the unary operator "-" and the\nliteral "1".\n',
  'for': u'\nThe "for" statement\n*******************\n\nThe "for" statement is used to iterate over the elements of a sequence\n(such as a string, tuple or list) or other iterable object:\n\n   for_stmt ::= "for" target_list "in" expression_list ":" suite\n                ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject.  An iterator is created for the result of the\n"expression_list".  The suite is then executed once for each item\nprovided by the iterator, in the order returned by the iterator.  Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted.  When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a "StopIteration" exception),\nthe suite in the "else" clause, if present, is executed, and the loop\nterminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite.  A "continue" statement\nexecuted in the first suite skips the rest of the suite and continues\nwith the next item, or with the "else" clause if there is no next\nitem.\n\nThe for-loop makes assignments to the variables(s) in the target list.\nThis overwrites all previous assignments to those variables including\nthose made in the suite of the for-loop:\n\n   for i in range(10):\n       print(i)\n       i = 5             # this will not affect the for-loop\n                         # because i will be overwritten with the next\n                         # index in the range\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, they will not have been assigned to at\nall by the loop.  Hint: the built-in function "range()" returns an\niterator of integers suitable to emulate the effect of Pascal\'s "for i\n:= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]".\n\nNote: There is a subtlety when the sequence is being modified by the\n  loop (this can only occur for mutable sequences, i.e. lists).  An\n  internal counter is used to keep track of which item is used next,\n  and this is incremented on each iteration.  When this counter has\n  reached the length of the sequence the loop terminates.  This means\n  that if the suite deletes the current (or a previous) item from the\n  sequence, the next item will be skipped (since it gets the index of\n  the current item which has already been treated).  Likewise, if the\n  suite inserts an item in the sequence before the current item, the\n  current item will be treated again the next time through the loop.\n  This can lead to nasty bugs that can be avoided by making a\n  temporary copy using a slice of the whole sequence, e.g.,\n\n     for x in a[:]:\n         if x < 0: a.remove(x)\n',
- 'formatstrings': u'\nFormat String Syntax\n********************\n\nThe "str.format()" method and the "Formatter" class share the same\nsyntax for format strings (although in the case of "Formatter",\nsubclasses can define their own format string syntax).\n\nFormat strings contain "replacement fields" surrounded by curly braces\n"{}". Anything that is not contained in braces is considered literal\ntext, which is copied unchanged to the output.  If you need to include\na brace character in the literal text, it can be escaped by doubling:\n"{{" and "}}".\n\nThe grammar for a replacement field is as follows:\n\n      replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"\n      field_name        ::= arg_name ("." attribute_name | "[" element_index "]")*\n      arg_name          ::= [identifier | integer]\n      attribute_name    ::= identifier\n      element_index     ::= integer | index_string\n      index_string      ::= <any source character except "]"> +\n      conversion        ::= "r" | "s" | "a"\n      format_spec       ::= <described in the next section>\n\nIn less formal terms, the replacement field can start with a\n*field_name* that specifies the object whose value is to be formatted\nand inserted into the output instead of the replacement field. The\n*field_name* is optionally followed by a  *conversion* field, which is\npreceded by an exclamation point "\'!\'", and a *format_spec*, which is\npreceded by a colon "\':\'".  These specify a non-default format for the\nreplacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either a\nnumber or a keyword.  If it\'s a number, it refers to a positional\nargument, and if it\'s a keyword, it refers to a named keyword\nargument.  If the numerical arg_names in a format string are 0, 1, 2,\n... in sequence, they can all be omitted (not just some) and the\nnumbers 0, 1, 2, ... will be automatically inserted in that order.\nBecause *arg_name* is not quote-delimited, it is not possible to\nspecify arbitrary dictionary keys (e.g., the strings "\'10\'" or\n"\':-]\'") within a format string. The *arg_name* can be followed by any\nnumber of index or attribute expressions. An expression of the form\n"\'.name\'" selects the named attribute using "getattr()", while an\nexpression of the form "\'[index]\'" does an index lookup using\n"__getitem__()".\n\nChanged in version 3.1: The positional argument specifiers can be\nomitted, so "\'{} {}\'" is equivalent to "\'{0} {1}\'".\n\nSome simple format string examples:\n\n   "First, thou shalt count to {0}"  # References first positional argument\n   "Bring me a {}"                   # Implicitly references the first positional argument\n   "From {} to {}"                   # Same as "From {0} to {1}"\n   "My quest is {name}"              # References keyword argument \'name\'\n   "Weight in tons {0.weight}"       # \'weight\' attribute of first positional arg\n   "Units destroyed: {players[0]}"   # First element of keyword argument \'players\'.\n\nThe *conversion* field causes a type coercion before formatting.\nNormally, the job of formatting a value is done by the "__format__()"\nmethod of the value itself.  However, in some cases it is desirable to\nforce a type to be formatted as a string, overriding its own\ndefinition of formatting.  By converting the value to a string before\ncalling "__format__()", the normal formatting logic is bypassed.\n\nThree conversion flags are currently supported: "\'!s\'" which calls\n"str()" on the value, "\'!r\'" which calls "repr()" and "\'!a\'" which\ncalls "ascii()".\n\nSome examples:\n\n   "Harold\'s a clever {0!s}"        # Calls str() on the argument first\n   "Bring out the holy {name!r}"    # Calls repr() on the argument first\n   "More {!a}"                      # Calls ascii() on the argument first\n\nThe *format_spec* field contains a specification of how the value\nshould be presented, including such details as field width, alignment,\npadding, decimal precision and so on.  Each value type can define its\nown "formatting mini-language" or interpretation of the *format_spec*.\n\nMost built-in types support a common formatting mini-language, which\nis described in the next section.\n\nA *format_spec* field can also include nested replacement fields\nwithin it. These nested replacement fields may contain a field name,\nconversion flag and format specification, but deeper nesting is not\nallowed.  The replacement fields within the format_spec are\nsubstituted before the *format_spec* string is interpreted. This\nallows the formatting of a value to be dynamically specified.\n\nSee the *Format examples* section for some examples.\n\n\nFormat Specification Mini-Language\n==================================\n\n"Format specifications" are used within replacement fields contained\nwithin a format string to define how individual values are presented\n(see *Format String Syntax*).  They can also be passed directly to the\nbuilt-in "format()" function.  Each formattable type may define how\nthe format specification is to be interpreted.\n\nMost built-in types implement the following options for format\nspecifications, although some of the formatting options are only\nsupported by the numeric types.\n\nA general convention is that an empty format string ("""") produces\nthe same result as if you had called "str()" on the value. A non-empty\nformat string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n   format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n   fill        ::= <any character>\n   align       ::= "<" | ">" | "=" | "^"\n   sign        ::= "+" | "-" | " "\n   width       ::= integer\n   precision   ::= integer\n   type        ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n\nIf a valid *align* value is specified, it can be preceded by a *fill*\ncharacter that can be any character and defaults to a space if\nomitted. It is not possible to use a literal curly brace (""{"" or\n""}"") as the *fill* character when using the "str.format()" method.\nHowever, it is possible to insert a curly brace with a nested\nreplacement field.  This limitation doesn\'t affect the "format()"\nfunction.\n\nThe meaning of the various alignment options is as follows:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | "\'<\'"     | Forces the field to be left-aligned within the available   |\n   |           | space (this is the default for most objects).              |\n   +-----------+------------------------------------------------------------+\n   | "\'>\'"     | Forces the field to be right-aligned within the available  |\n   |           | space (this is the default for numbers).                   |\n   +-----------+------------------------------------------------------------+\n   | "\'=\'"     | Forces the padding to be placed after the sign (if any)    |\n   |           | but before the digits.  This is used for printing fields   |\n   |           | in the form \'+000000120\'. This alignment option is only    |\n   |           | valid for numeric types.  It becomes the default when \'0\'  |\n   |           | immediately precedes the field width.                      |\n   +-----------+------------------------------------------------------------+\n   | "\'^\'"     | Forces the field to be centered within the available       |\n   |           | space.                                                     |\n   +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | "\'+\'"     | indicates that a sign should be used for both positive as  |\n   |           | well as negative numbers.                                  |\n   +-----------+------------------------------------------------------------+\n   | "\'-\'"     | indicates that a sign should be used only for negative     |\n   |           | numbers (this is the default behavior).                    |\n   +-----------+------------------------------------------------------------+\n   | space     | indicates that a leading space should be used on positive  |\n   |           | numbers, and a minus sign on negative numbers.             |\n   +-----------+------------------------------------------------------------+\n\nThe "\'#\'" option causes the "alternate form" to be used for the\nconversion.  The alternate form is defined differently for different\ntypes.  This option is only valid for integer, float, complex and\nDecimal types. For integers, when binary, octal, or hexadecimal output\nis used, this option adds the prefix respective "\'0b\'", "\'0o\'", or\n"\'0x\'" to the output value. For floats, complex and Decimal the\nalternate form causes the result of the conversion to always contain a\ndecimal-point character, even if no digits follow it. Normally, a\ndecimal-point character appears in the result of these conversions\nonly if a digit follows it. In addition, for "\'g\'" and "\'G\'"\nconversions, trailing zeros are not removed from the result.\n\nThe "\',\'" option signals the use of a comma for a thousands separator.\nFor a locale aware separator, use the "\'n\'" integer presentation type\ninstead.\n\nChanged in version 3.1: Added the "\',\'" option (see also **PEP 378**).\n\n*width* is a decimal integer defining the minimum field width.  If not\nspecified, then the field width will be determined by the content.\n\nWhen no explicit alignment is given, preceding the *width* field by a\nzero ("\'0\'") character enables sign-aware zero-padding for numeric\ntypes.  This is equivalent to a *fill* character of "\'0\'" with an\n*alignment* type of "\'=\'".\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with "\'f\'" and "\'F\'", or before and after the decimal point\nfor a floating point value formatted with "\'g\'" or "\'G\'".  For non-\nnumber types the field indicates the maximum field size - in other\nwords, how many characters will be used from the field content. The\n*precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | "\'s\'"     | String format. This is the default type for strings and    |\n   |           | may be omitted.                                            |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as "\'s\'".                                         |\n   +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | "\'b\'"     | Binary format. Outputs the number in base 2.               |\n   +-----------+------------------------------------------------------------+\n   | "\'c\'"     | Character. Converts the integer to the corresponding       |\n   |           | unicode character before printing.                         |\n   +-----------+------------------------------------------------------------+\n   | "\'d\'"     | Decimal Integer. Outputs the number in base 10.            |\n   +-----------+------------------------------------------------------------+\n   | "\'o\'"     | Octal format. Outputs the number in base 8.                |\n   +-----------+------------------------------------------------------------+\n   | "\'x\'"     | Hex format. Outputs the number in base 16, using lower-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | "\'X\'"     | Hex format. Outputs the number in base 16, using upper-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | "\'n\'"     | Number. This is the same as "\'d\'", except that it uses the |\n   |           | current locale setting to insert the appropriate number    |\n   |           | separator characters.                                      |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as "\'d\'".                                         |\n   +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except "\'n\'"\nand None). When doing so, "float()" is used to convert the integer to\na floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | "\'e\'"     | Exponent notation. Prints the number in scientific         |\n   |           | notation using the letter \'e\' to indicate the exponent.    |\n   |           | The default precision is "6".                              |\n   +-----------+------------------------------------------------------------+\n   | "\'E\'"     | Exponent notation. Same as "\'e\'" except it uses an upper   |\n   |           | case \'E\' as the separator character.                       |\n   +-----------+------------------------------------------------------------+\n   | "\'f\'"     | Fixed point. Displays the number as a fixed-point number.  |\n   |           | The default precision is "6".                              |\n   +-----------+------------------------------------------------------------+\n   | "\'F\'"     | Fixed point. Same as "\'f\'", but converts "nan" to "NAN"    |\n   |           | and "inf" to "INF".                                        |\n   +-----------+------------------------------------------------------------+\n   | "\'g\'"     | General format.  For a given precision "p >= 1", this      |\n   |           | rounds the number to "p" significant digits and then       |\n   |           | formats the result in either fixed-point format or in      |\n   |           | scientific notation, depending on its magnitude.  The      |\n   |           | precise rules are as follows: suppose that the result      |\n   |           | formatted with presentation type "\'e\'" and precision "p-1" |\n   |           | would have exponent "exp".  Then if "-4 <= exp < p", the   |\n   |           | number is formatted with presentation type "\'f\'" and       |\n   |           | precision "p-1-exp".  Otherwise, the number is formatted   |\n   |           | with presentation type "\'e\'" and precision "p-1". In both  |\n   |           | cases insignificant trailing zeros are removed from the    |\n   |           | significand, and the decimal point is also removed if      |\n   |           | there are no remaining digits following it.  Positive and  |\n   |           | negative infinity, positive and negative zero, and nans,   |\n   |           | are formatted as "inf", "-inf", "0", "-0" and "nan"        |\n   |           | respectively, regardless of the precision.  A precision of |\n   |           | "0" is treated as equivalent to a precision of "1". The    |\n   |           | default precision is "6".                                  |\n   +-----------+------------------------------------------------------------+\n   | "\'G\'"     | General format. Same as "\'g\'" except switches to "\'E\'" if  |\n   |           | the number gets too large. The representations of infinity |\n   |           | and NaN are uppercased, too.                               |\n   +-----------+------------------------------------------------------------+\n   | "\'n\'"     | Number. This is the same as "\'g\'", except that it uses the |\n   |           | current locale setting to insert the appropriate number    |\n   |           | separator characters.                                      |\n   +-----------+------------------------------------------------------------+\n   | "\'%\'"     | Percentage. Multiplies the number by 100 and displays in   |\n   |           | fixed ("\'f\'") format, followed by a percent sign.          |\n   +-----------+------------------------------------------------------------+\n   | None      | Similar to "\'g\'", except that fixed-point notation, when   |\n   |           | used, has at least one digit past the decimal point. The   |\n   |           | default precision is as high as needed to represent the    |\n   |           | particular value. The overall effect is to match the       |\n   |           | output of "str()" as altered by the other format           |\n   |           | modifiers.                                                 |\n   +-----------+------------------------------------------------------------+\n\n\nFormat examples\n===============\n\nThis section contains examples of the "str.format()" syntax and\ncomparison with the old "%"-formatting.\n\nIn most of the cases the syntax is similar to the old "%"-formatting,\nwith the addition of the "{}" and with ":" used instead of "%". For\nexample, "\'%03.2f\'" can be translated to "\'{:03.2f}\'".\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n   >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n   \'a, b, c\'\n   >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\')  # 3.1+ only\n   \'a, b, c\'\n   >>> \'{2}, {1}, {0}\'.format(\'a\', \'b\', \'c\')\n   \'c, b, a\'\n   >>> \'{2}, {1}, {0}\'.format(*\'abc\')      # unpacking argument sequence\n   \'c, b, a\'\n   >>> \'{0}{1}{0}\'.format(\'abra\', \'cad\')   # arguments\' indices can be repeated\n   \'abracadabra\'\n\nAccessing arguments by name:\n\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(latitude=\'37.24N\', longitude=\'-115.81W\')\n   \'Coordinates: 37.24N, -115.81W\'\n   >>> coord = {\'latitude\': \'37.24N\', \'longitude\': \'-115.81W\'}\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(**coord)\n   \'Coordinates: 37.24N, -115.81W\'\n\nAccessing arguments\' attributes:\n\n   >>> c = 3-5j\n   >>> (\'The complex number {0} is formed from the real part {0.real} \'\n   ...  \'and the imaginary part {0.imag}.\').format(c)\n   \'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.\'\n   >>> class Point:\n   ...     def __init__(self, x, y):\n   ...         self.x, self.y = x, y\n   ...     def __str__(self):\n   ...         return \'Point({self.x}, {self.y})\'.format(self=self)\n   ...\n   >>> str(Point(4, 2))\n   \'Point(4, 2)\'\n\nAccessing arguments\' items:\n\n   >>> coord = (3, 5)\n   >>> \'X: {0[0]};  Y: {0[1]}\'.format(coord)\n   \'X: 3;  Y: 5\'\n\nReplacing "%s" and "%r":\n\n   >>> "repr() shows quotes: {!r}; str() doesn\'t: {!s}".format(\'test1\', \'test2\')\n   "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n\nAligning the text and specifying a width:\n\n   >>> \'{:<30}\'.format(\'left aligned\')\n   \'left aligned                  \'\n   >>> \'{:>30}\'.format(\'right aligned\')\n   \'                 right aligned\'\n   >>> \'{:^30}\'.format(\'centered\')\n   \'           centered           \'\n   >>> \'{:*^30}\'.format(\'centered\')  # use \'*\' as a fill char\n   \'***********centered***********\'\n\nReplacing "%+f", "%-f", and "% f" and specifying a sign:\n\n   >>> \'{:+f}; {:+f}\'.format(3.14, -3.14)  # show it always\n   \'+3.140000; -3.140000\'\n   >>> \'{: f}; {: f}\'.format(3.14, -3.14)  # show a space for positive numbers\n   \' 3.140000; -3.140000\'\n   >>> \'{:-f}; {:-f}\'.format(3.14, -3.14)  # show only the minus -- same as \'{:f}; {:f}\'\n   \'3.140000; -3.140000\'\n\nReplacing "%x" and "%o" and converting the value to different bases:\n\n   >>> # format also supports binary numbers\n   >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)\n   \'int: 42;  hex: 2a;  oct: 52;  bin: 101010\'\n   >>> # with 0x, 0o, or 0b as prefix:\n   >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)\n   \'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n   >>> \'{:,}\'.format(1234567890)\n   \'1,234,567,890\'\n\nExpressing a percentage:\n\n   >>> points = 19\n   >>> total = 22\n   >>> \'Correct answers: {:.2%}\'.format(points/total)\n   \'Correct answers: 86.36%\'\n\nUsing type-specific formatting:\n\n   >>> import datetime\n   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n   >>> \'{:%Y-%m-%d %H:%M:%S}\'.format(d)\n   \'2010-07-04 12:15:58\'\n\nNesting arguments and more complex examples:\n\n   >>> for align, text in zip(\'<^>\', [\'left\', \'center\', \'right\']):\n   ...     \'{0:{fill}{align}16}\'.format(text, fill=align, align=align)\n   ...\n   \'left<<<<<<<<<<<<\'\n   \'^^^^^center^^^^^\'\n   \'>>>>>>>>>>>right\'\n   >>>\n   >>> octets = [192, 168, 0, 1]\n   >>> \'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n   \'C0A80001\'\n   >>> int(_, 16)\n   3232235521\n   >>>\n   >>> width = 5\n   >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE\n   ...     for base in \'dXob\':\n   ...         print(\'{0:{width}{base}}\'.format(num, base=base, width=width), end=\' \')\n   ...     print()\n   ...\n       5     5     5   101\n       6     6     6   110\n       7     7     7   111\n       8     8    10  1000\n       9     9    11  1001\n      10     A    12  1010\n      11     B    13  1011\n',
- 'function': u'\nFunction definitions\n********************\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      | "*" [parameter] ("," defparameter)* ["," "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nWhen one or more *parameters* have the form *parameter* "="\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding *argument* may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the ""*"" must also have a default value --- this\nis a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated from left to right when the\nfunction definition is executed.** This means that the expression is\nevaluated once, when the function is defined, and that the same "pre-\ncomputed" value is used for each call.  This is especially important\nto understand when a default parameter is a mutable object, such as a\nlist or a dictionary: if the function modifies the object (e.g. by\nappending an item to a list), the default value is in effect modified.\nThis is generally not what was intended.  A way around this is to use\n"None" as the default, and explicitly test for it in the body of the\nfunction, e.g.:\n\n   def whats_on_the_telly(penguin=None):\n       if penguin is None:\n           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n""*identifier"" is present, it is initialized to a tuple receiving any\nexcess positional parameters, defaulting to the empty tuple.  If the\nform ""**identifier"" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after ""*"" or ""*identifier"" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "": expression"" following\nthe parameter name.  Any parameter may have an annotation even those\nof the form "*identifier" or "**identifier".  Functions may have\n"return" annotation of the form ""-> expression"" after the parameter\nlist.  These annotations can be any valid Python expression and are\nevaluated when the function definition is executed.  Annotations may\nbe evaluated in a different order than they appear in the source code.\nThe presence of annotations does not change the semantics of a\nfunction.  The annotation values are available as values of a\ndictionary keyed by the parameters\' names in the "__annotations__"\nattribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda\nexpressions, described in section *Lambdas*.  Note that the lambda\nexpression is merely a shorthand for a simplified function definition;\na function defined in a ""def"" statement can be passed around or\nassigned to another name just like a function defined by a lambda\nexpression.  The ""def"" form is actually more powerful since it\nallows the execution of multiple statements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A ""def""\nstatement executed inside a function definition defines a local\nfunction that can be returned or passed around.  Free variables used\nin the nested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n\nSee also: **PEP 3107** - Function Annotations\n\n     The original specification for function annotations.\n',
+ 'formatstrings': u'\nFormat String Syntax\n********************\n\nThe "str.format()" method and the "Formatter" class share the same\nsyntax for format strings (although in the case of "Formatter",\nsubclasses can define their own format string syntax).\n\nFormat strings contain "replacement fields" surrounded by curly braces\n"{}". Anything that is not contained in braces is considered literal\ntext, which is copied unchanged to the output.  If you need to include\na brace character in the literal text, it can be escaped by doubling:\n"{{" and "}}".\n\nThe grammar for a replacement field is as follows:\n\n      replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"\n      field_name        ::= arg_name ("." attribute_name | "[" element_index "]")*\n      arg_name          ::= [identifier | integer]\n      attribute_name    ::= identifier\n      element_index     ::= integer | index_string\n      index_string      ::= <any source character except "]"> +\n      conversion        ::= "r" | "s" | "a"\n      format_spec       ::= <described in the next section>\n\nIn less formal terms, the replacement field can start with a\n*field_name* that specifies the object whose value is to be formatted\nand inserted into the output instead of the replacement field. The\n*field_name* is optionally followed by a  *conversion* field, which is\npreceded by an exclamation point "\'!\'", and a *format_spec*, which is\npreceded by a colon "\':\'".  These specify a non-default format for the\nreplacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either a\nnumber or a keyword.  If it\'s a number, it refers to a positional\nargument, and if it\'s a keyword, it refers to a named keyword\nargument.  If the numerical arg_names in a format string are 0, 1, 2,\n... in sequence, they can all be omitted (not just some) and the\nnumbers 0, 1, 2, ... will be automatically inserted in that order.\nBecause *arg_name* is not quote-delimited, it is not possible to\nspecify arbitrary dictionary keys (e.g., the strings "\'10\'" or\n"\':-]\'") within a format string. The *arg_name* can be followed by any\nnumber of index or attribute expressions. An expression of the form\n"\'.name\'" selects the named attribute using "getattr()", while an\nexpression of the form "\'[index]\'" does an index lookup using\n"__getitem__()".\n\nChanged in version 3.1: The positional argument specifiers can be\nomitted, so "\'{} {}\'" is equivalent to "\'{0} {1}\'".\n\nSome simple format string examples:\n\n   "First, thou shalt count to {0}"  # References first positional argument\n   "Bring me a {}"                   # Implicitly references the first positional argument\n   "From {} to {}"                   # Same as "From {0} to {1}"\n   "My quest is {name}"              # References keyword argument \'name\'\n   "Weight in tons {0.weight}"       # \'weight\' attribute of first positional arg\n   "Units destroyed: {players[0]}"   # First element of keyword argument \'players\'.\n\nThe *conversion* field causes a type coercion before formatting.\nNormally, the job of formatting a value is done by the "__format__()"\nmethod of the value itself.  However, in some cases it is desirable to\nforce a type to be formatted as a string, overriding its own\ndefinition of formatting.  By converting the value to a string before\ncalling "__format__()", the normal formatting logic is bypassed.\n\nThree conversion flags are currently supported: "\'!s\'" which calls\n"str()" on the value, "\'!r\'" which calls "repr()" and "\'!a\'" which\ncalls "ascii()".\n\nSome examples:\n\n   "Harold\'s a clever {0!s}"        # Calls str() on the argument first\n   "Bring out the holy {name!r}"    # Calls repr() on the argument first\n   "More {!a}"                      # Calls ascii() on the argument first\n\nThe *format_spec* field contains a specification of how the value\nshould be presented, including such details as field width, alignment,\npadding, decimal precision and so on.  Each value type can define its\nown "formatting mini-language" or interpretation of the *format_spec*.\n\nMost built-in types support a common formatting mini-language, which\nis described in the next section.\n\nA *format_spec* field can also include nested replacement fields\nwithin it. These nested replacement fields may contain a field name,\nconversion flag and format specification, but deeper nesting is not\nallowed.  The replacement fields within the format_spec are\nsubstituted before the *format_spec* string is interpreted. This\nallows the formatting of a value to be dynamically specified.\n\nSee the *Format examples* section for some examples.\n\n\nFormat Specification Mini-Language\n==================================\n\n"Format specifications" are used within replacement fields contained\nwithin a format string to define how individual values are presented\n(see *Format String Syntax*).  They can also be passed directly to the\nbuilt-in "format()" function.  Each formattable type may define how\nthe format specification is to be interpreted.\n\nMost built-in types implement the following options for format\nspecifications, although some of the formatting options are only\nsupported by the numeric types.\n\nA general convention is that an empty format string ("""") produces\nthe same result as if you had called "str()" on the value. A non-empty\nformat string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n   format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n   fill        ::= <any character>\n   align       ::= "<" | ">" | "=" | "^"\n   sign        ::= "+" | "-" | " "\n   width       ::= integer\n   precision   ::= integer\n   type        ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n\nIf a valid *align* value is specified, it can be preceded by a *fill*\ncharacter that can be any character and defaults to a space if\nomitted. It is not possible to use a literal curly brace (""{"" or\n""}"") as the *fill* character when using the "str.format()" method.\nHowever, it is possible to insert a curly brace with a nested\nreplacement field.  This limitation doesn\'t affect the "format()"\nfunction.\n\nThe meaning of the various alignment options is as follows:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | "\'<\'"     | Forces the field to be left-aligned within the available   |\n   |           | space (this is the default for most objects).              |\n   +-----------+------------------------------------------------------------+\n   | "\'>\'"     | Forces the field to be right-aligned within the available  |\n   |           | space (this is the default for numbers).                   |\n   +-----------+------------------------------------------------------------+\n   | "\'=\'"     | Forces the padding to be placed after the sign (if any)    |\n   |           | but before the digits.  This is used for printing fields   |\n   |           | in the form \'+000000120\'. This alignment option is only    |\n   |           | valid for numeric types.  It becomes the default when \'0\'  |\n   |           | immediately precedes the field width.                      |\n   +-----------+------------------------------------------------------------+\n   | "\'^\'"     | Forces the field to be centered within the available       |\n   |           | space.                                                     |\n   +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | "\'+\'"     | indicates that a sign should be used for both positive as  |\n   |           | well as negative numbers.                                  |\n   +-----------+------------------------------------------------------------+\n   | "\'-\'"     | indicates that a sign should be used only for negative     |\n   |           | numbers (this is the default behavior).                    |\n   +-----------+------------------------------------------------------------+\n   | space     | indicates that a leading space should be used on positive  |\n   |           | numbers, and a minus sign on negative numbers.             |\n   +-----------+------------------------------------------------------------+\n\nThe "\'#\'" option causes the "alternate form" to be used for the\nconversion.  The alternate form is defined differently for different\ntypes.  This option is only valid for integer, float, complex and\nDecimal types. For integers, when binary, octal, or hexadecimal output\nis used, this option adds the prefix respective "\'0b\'", "\'0o\'", or\n"\'0x\'" to the output value. For floats, complex and Decimal the\nalternate form causes the result of the conversion to always contain a\ndecimal-point character, even if no digits follow it. Normally, a\ndecimal-point character appears in the result of these conversions\nonly if a digit follows it. In addition, for "\'g\'" and "\'G\'"\nconversions, trailing zeros are not removed from the result.\n\nThe "\',\'" option signals the use of a comma for a thousands separator.\nFor a locale aware separator, use the "\'n\'" integer presentation type\ninstead.\n\nChanged in version 3.1: Added the "\',\'" option (see also **PEP 378**).\n\n*width* is a decimal integer defining the minimum field width.  If not\nspecified, then the field width will be determined by the content.\n\nWhen no explicit alignment is given, preceding the *width* field by a\nzero ("\'0\'") character enables sign-aware zero-padding for numeric\ntypes.  This is equivalent to a *fill* character of "\'0\'" with an\n*alignment* type of "\'=\'".\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with "\'f\'" and "\'F\'", or before and after the decimal point\nfor a floating point value formatted with "\'g\'" or "\'G\'".  For non-\nnumber types the field indicates the maximum field size - in other\nwords, how many characters will be used from the field content. The\n*precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | "\'s\'"     | String format. This is the default type for strings and    |\n   |           | may be omitted.                                            |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as "\'s\'".                                         |\n   +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | "\'b\'"     | Binary format. Outputs the number in base 2.               |\n   +-----------+------------------------------------------------------------+\n   | "\'c\'"     | Character. Converts the integer to the corresponding       |\n   |           | unicode character before printing.                         |\n   +-----------+------------------------------------------------------------+\n   | "\'d\'"     | Decimal Integer. Outputs the number in base 10.            |\n   +-----------+------------------------------------------------------------+\n   | "\'o\'"     | Octal format. Outputs the number in base 8.                |\n   +-----------+------------------------------------------------------------+\n   | "\'x\'"     | Hex format. Outputs the number in base 16, using lower-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | "\'X\'"     | Hex format. Outputs the number in base 16, using upper-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | "\'n\'"     | Number. This is the same as "\'d\'", except that it uses the |\n   |           | current locale setting to insert the appropriate number    |\n   |           | separator characters.                                      |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as "\'d\'".                                         |\n   +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except "\'n\'"\nand "None"). When doing so, "float()" is used to convert the integer\nto a floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | "\'e\'"     | Exponent notation. Prints the number in scientific         |\n   |           | notation using the letter \'e\' to indicate the exponent.    |\n   |           | The default precision is "6".                              |\n   +-----------+------------------------------------------------------------+\n   | "\'E\'"     | Exponent notation. Same as "\'e\'" except it uses an upper   |\n   |           | case \'E\' as the separator character.                       |\n   +-----------+------------------------------------------------------------+\n   | "\'f\'"     | Fixed point. Displays the number as a fixed-point number.  |\n   |           | The default precision is "6".                              |\n   +-----------+------------------------------------------------------------+\n   | "\'F\'"     | Fixed point. Same as "\'f\'", but converts "nan" to "NAN"    |\n   |           | and "inf" to "INF".                                        |\n   +-----------+------------------------------------------------------------+\n   | "\'g\'"     | General format.  For a given precision "p >= 1", this      |\n   |           | rounds the number to "p" significant digits and then       |\n   |           | formats the result in either fixed-point format or in      |\n   |           | scientific notation, depending on its magnitude.  The      |\n   |           | precise rules are as follows: suppose that the result      |\n   |           | formatted with presentation type "\'e\'" and precision "p-1" |\n   |           | would have exponent "exp".  Then if "-4 <= exp < p", the   |\n   |           | number is formatted with presentation type "\'f\'" and       |\n   |           | precision "p-1-exp".  Otherwise, the number is formatted   |\n   |           | with presentation type "\'e\'" and precision "p-1". In both  |\n   |           | cases insignificant trailing zeros are removed from the    |\n   |           | significand, and the decimal point is also removed if      |\n   |           | there are no remaining digits following it.  Positive and  |\n   |           | negative infinity, positive and negative zero, and nans,   |\n   |           | are formatted as "inf", "-inf", "0", "-0" and "nan"        |\n   |           | respectively, regardless of the precision.  A precision of |\n   |           | "0" is treated as equivalent to a precision of "1". The    |\n   |           | default precision is "6".                                  |\n   +-----------+------------------------------------------------------------+\n   | "\'G\'"     | General format. Same as "\'g\'" except switches to "\'E\'" if  |\n   |           | the number gets too large. The representations of infinity |\n   |           | and NaN are uppercased, too.                               |\n   +-----------+------------------------------------------------------------+\n   | "\'n\'"     | Number. This is the same as "\'g\'", except that it uses the |\n   |           | current locale setting to insert the appropriate number    |\n   |           | separator characters.                                      |\n   +-----------+------------------------------------------------------------+\n   | "\'%\'"     | Percentage. Multiplies the number by 100 and displays in   |\n   |           | fixed ("\'f\'") format, followed by a percent sign.          |\n   +-----------+------------------------------------------------------------+\n   | None      | Similar to "\'g\'", except that fixed-point notation, when   |\n   |           | used, has at least one digit past the decimal point. The   |\n   |           | default precision is as high as needed to represent the    |\n   |           | particular value. The overall effect is to match the       |\n   |           | output of "str()" as altered by the other format           |\n   |           | modifiers.                                                 |\n   +-----------+------------------------------------------------------------+\n\n\nFormat examples\n===============\n\nThis section contains examples of the "str.format()" syntax and\ncomparison with the old "%"-formatting.\n\nIn most of the cases the syntax is similar to the old "%"-formatting,\nwith the addition of the "{}" and with ":" used instead of "%". For\nexample, "\'%03.2f\'" can be translated to "\'{:03.2f}\'".\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n   >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n   \'a, b, c\'\n   >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\')  # 3.1+ only\n   \'a, b, c\'\n   >>> \'{2}, {1}, {0}\'.format(\'a\', \'b\', \'c\')\n   \'c, b, a\'\n   >>> \'{2}, {1}, {0}\'.format(*\'abc\')      # unpacking argument sequence\n   \'c, b, a\'\n   >>> \'{0}{1}{0}\'.format(\'abra\', \'cad\')   # arguments\' indices can be repeated\n   \'abracadabra\'\n\nAccessing arguments by name:\n\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(latitude=\'37.24N\', longitude=\'-115.81W\')\n   \'Coordinates: 37.24N, -115.81W\'\n   >>> coord = {\'latitude\': \'37.24N\', \'longitude\': \'-115.81W\'}\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(**coord)\n   \'Coordinates: 37.24N, -115.81W\'\n\nAccessing arguments\' attributes:\n\n   >>> c = 3-5j\n   >>> (\'The complex number {0} is formed from the real part {0.real} \'\n   ...  \'and the imaginary part {0.imag}.\').format(c)\n   \'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.\'\n   >>> class Point:\n   ...     def __init__(self, x, y):\n   ...         self.x, self.y = x, y\n   ...     def __str__(self):\n   ...         return \'Point({self.x}, {self.y})\'.format(self=self)\n   ...\n   >>> str(Point(4, 2))\n   \'Point(4, 2)\'\n\nAccessing arguments\' items:\n\n   >>> coord = (3, 5)\n   >>> \'X: {0[0]};  Y: {0[1]}\'.format(coord)\n   \'X: 3;  Y: 5\'\n\nReplacing "%s" and "%r":\n\n   >>> "repr() shows quotes: {!r}; str() doesn\'t: {!s}".format(\'test1\', \'test2\')\n   "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n\nAligning the text and specifying a width:\n\n   >>> \'{:<30}\'.format(\'left aligned\')\n   \'left aligned                  \'\n   >>> \'{:>30}\'.format(\'right aligned\')\n   \'                 right aligned\'\n   >>> \'{:^30}\'.format(\'centered\')\n   \'           centered           \'\n   >>> \'{:*^30}\'.format(\'centered\')  # use \'*\' as a fill char\n   \'***********centered***********\'\n\nReplacing "%+f", "%-f", and "% f" and specifying a sign:\n\n   >>> \'{:+f}; {:+f}\'.format(3.14, -3.14)  # show it always\n   \'+3.140000; -3.140000\'\n   >>> \'{: f}; {: f}\'.format(3.14, -3.14)  # show a space for positive numbers\n   \' 3.140000; -3.140000\'\n   >>> \'{:-f}; {:-f}\'.format(3.14, -3.14)  # show only the minus -- same as \'{:f}; {:f}\'\n   \'3.140000; -3.140000\'\n\nReplacing "%x" and "%o" and converting the value to different bases:\n\n   >>> # format also supports binary numbers\n   >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)\n   \'int: 42;  hex: 2a;  oct: 52;  bin: 101010\'\n   >>> # with 0x, 0o, or 0b as prefix:\n   >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)\n   \'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n   >>> \'{:,}\'.format(1234567890)\n   \'1,234,567,890\'\n\nExpressing a percentage:\n\n   >>> points = 19\n   >>> total = 22\n   >>> \'Correct answers: {:.2%}\'.format(points/total)\n   \'Correct answers: 86.36%\'\n\nUsing type-specific formatting:\n\n   >>> import datetime\n   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n   >>> \'{:%Y-%m-%d %H:%M:%S}\'.format(d)\n   \'2010-07-04 12:15:58\'\n\nNesting arguments and more complex examples:\n\n   >>> for align, text in zip(\'<^>\', [\'left\', \'center\', \'right\']):\n   ...     \'{0:{fill}{align}16}\'.format(text, fill=align, align=align)\n   ...\n   \'left<<<<<<<<<<<<\'\n   \'^^^^^center^^^^^\'\n   \'>>>>>>>>>>>right\'\n   >>>\n   >>> octets = [192, 168, 0, 1]\n   >>> \'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n   \'C0A80001\'\n   >>> int(_, 16)\n   3232235521\n   >>>\n   >>> width = 5\n   >>> for num in range(5,12): #doctest: +NORMALIZE_WHITESPACE\n   ...     for base in \'dXob\':\n   ...         print(\'{0:{width}{base}}\'.format(num, base=base, width=width), end=\' \')\n   ...     print()\n   ...\n       5     5     5   101\n       6     6     6   110\n       7     7     7   111\n       8     8    10  1000\n       9     9    11  1001\n      10     A    12  1010\n      11     B    13  1011\n',
+ 'function': u'\nFunction definitions\n********************\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      | "*" [parameter] ("," defparameter)* ["," "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis roughly equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nexcept that the original function is not temporarily bound to the name\n"func".\n\nWhen one or more *parameters* have the form *parameter* "="\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding *argument* may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the ""*"" must also have a default value --- this\nis a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated from left to right when the\nfunction definition is executed.** This means that the expression is\nevaluated once, when the function is defined, and that the same "pre-\ncomputed" value is used for each call.  This is especially important\nto understand when a default parameter is a mutable object, such as a\nlist or a dictionary: if the function modifies the object (e.g. by\nappending an item to a list), the default value is in effect modified.\nThis is generally not what was intended.  A way around this is to use\n"None" as the default, and explicitly test for it in the body of the\nfunction, e.g.:\n\n   def whats_on_the_telly(penguin=None):\n       if penguin is None:\n           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n""*identifier"" is present, it is initialized to a tuple receiving any\nexcess positional parameters, defaulting to the empty tuple.  If the\nform ""**identifier"" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after ""*"" or ""*identifier"" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "": expression"" following\nthe parameter name.  Any parameter may have an annotation even those\nof the form "*identifier" or "**identifier".  Functions may have\n"return" annotation of the form ""-> expression"" after the parameter\nlist.  These annotations can be any valid Python expression and are\nevaluated when the function definition is executed.  Annotations may\nbe evaluated in a different order than they appear in the source code.\nThe presence of annotations does not change the semantics of a\nfunction.  The annotation values are available as values of a\ndictionary keyed by the parameters\' names in the "__annotations__"\nattribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda\nexpressions, described in section *Lambdas*.  Note that the lambda\nexpression is merely a shorthand for a simplified function definition;\na function defined in a ""def"" statement can be passed around or\nassigned to another name just like a function defined by a lambda\nexpression.  The ""def"" form is actually more powerful since it\nallows the execution of multiple statements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A ""def""\nstatement executed inside a function definition defines a local\nfunction that can be returned or passed around.  Free variables used\nin the nested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n\nSee also: **PEP 3107** - Function Annotations\n\n     The original specification for function annotations.\n',
  'global': u'\nThe "global" statement\n**********************\n\n   global_stmt ::= "global" identifier ("," identifier)*\n\nThe "global" statement is a declaration which holds for the entire\ncurrent code block.  It means that the listed identifiers are to be\ninterpreted as globals.  It would be impossible to assign to a global\nvariable without "global", although free variables may refer to\nglobals without being declared global.\n\nNames listed in a "global" statement must not be used in the same code\nblock textually preceding that "global" statement.\n\nNames listed in a "global" statement must not be defined as formal\nparameters or in a "for" loop control target, "class" definition,\nfunction definition, or "import" statement.\n\n**CPython implementation detail:** The current implementation does not\nenforce the two restrictions, but programs should not abuse this\nfreedom, as future implementations may enforce them or silently change\nthe meaning of the program.\n\n**Programmer\'s note:** the "global" is a directive to the parser.  It\napplies only to code parsed at the same time as the "global"\nstatement. In particular, a "global" statement contained in a string\nor code object supplied to the built-in "exec()" function does not\naffect the code block *containing* the function call, and code\ncontained in such a string is unaffected by "global" statements in the\ncode containing the function call.  The same applies to the "eval()"\nand "compile()" functions.\n',
  'id-classes': u'\nReserved classes of identifiers\n*******************************\n\nCertain classes of identifiers (besides keywords) have special\nmeanings.  These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n"_*"\n   Not imported by "from module import *".  The special identifier "_"\n   is used in the interactive interpreter to store the result of the\n   last evaluation; it is stored in the "builtins" module.  When not\n   in interactive mode, "_" has no special meaning and is not defined.\n   See section *The import statement*.\n\n   Note: The name "_" is often used in conjunction with\n     internationalization; refer to the documentation for the\n     "gettext" module for more information on this convention.\n\n"__*__"\n   System-defined names. These names are defined by the interpreter\n   and its implementation (including the standard library).  Current\n   system names are discussed in the *Special method names* section\n   and elsewhere.  More will likely be defined in future versions of\n   Python.  *Any* use of "__*__" names, in any context, that does not\n   follow explicitly documented use, is subject to breakage without\n   warning.\n\n"__*"\n   Class-private names.  Names in this category, when used within the\n   context of a class definition, are re-written to use a mangled form\n   to help avoid name clashes between "private" attributes of base and\n   derived classes. See section *Identifiers (Names)*.\n',
  'identifiers': u'\nIdentifiers and keywords\n************************\n\nIdentifiers (also referred to as *names*) are described by the\nfollowing lexical definitions.\n\nThe syntax of identifiers in Python is based on the Unicode standard\nannex UAX-31, with elaboration and changes as defined below; see also\n**PEP 3131** for further details.\n\nWithin the ASCII range (U+0001..U+007F), the valid characters for\nidentifiers are the same as in Python 2.x: the uppercase and lowercase\nletters "A" through "Z", the underscore "_" and, except for the first\ncharacter, the digits "0" through "9".\n\nPython 3.0 introduces additional characters from outside the ASCII\nrange (see **PEP 3131**).  For these characters, the classification\nuses the version of the Unicode Character Database as included in the\n"unicodedata" module.\n\nIdentifiers are unlimited in length.  Case is significant.\n\n   identifier   ::= xid_start xid_continue*\n   id_start     ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>\n   id_continue  ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>\n   xid_start    ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">\n   xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">\n\nThe Unicode category codes mentioned above stand for:\n\n* *Lu* - uppercase letters\n\n* *Ll* - lowercase letters\n\n* *Lt* - titlecase letters\n\n* *Lm* - modifier letters\n\n* *Lo* - other letters\n\n* *Nl* - letter numbers\n\n* *Mn* - nonspacing marks\n\n* *Mc* - spacing combining marks\n\n* *Nd* - decimal numbers\n\n* *Pc* - connector punctuations\n\n* *Other_ID_Start* - explicit list of characters in PropList.txt to\n  support backwards compatibility\n\n* *Other_ID_Continue* - likewise\n\nAll identifiers are converted into the normal form NFKC while parsing;\ncomparison of identifiers is based on NFKC.\n\nA non-normative HTML file listing all valid identifier characters for\nUnicode 4.1 can be found at https://www.dcl.hpi.uni-\npotsdam.de/home/loewis/table-3131.html.\n\n\nKeywords\n========\n\nThe following identifiers are used as reserved words, or *keywords* of\nthe language, and cannot be used as ordinary identifiers.  They must\nbe spelled exactly as written here:\n\n   False      class      finally    is         return\n   None       continue   for        lambda     try\n   True       def        from       nonlocal   while\n   and        del        global     not        with\n   as         elif       if         or         yield\n   assert     else       import     pass\n   break      except     in         raise\n\n\nReserved classes of identifiers\n===============================\n\nCertain classes of identifiers (besides keywords) have special\nmeanings.  These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n"_*"\n   Not imported by "from module import *".  The special identifier "_"\n   is used in the interactive interpreter to store the result of the\n   last evaluation; it is stored in the "builtins" module.  When not\n   in interactive mode, "_" has no special meaning and is not defined.\n   See section *The import statement*.\n\n   Note: The name "_" is often used in conjunction with\n     internationalization; refer to the documentation for the\n     "gettext" module for more information on this convention.\n\n"__*__"\n   System-defined names. These names are defined by the interpreter\n   and its implementation (including the standard library).  Current\n   system names are discussed in the *Special method names* section\n   and elsewhere.  More will likely be defined in future versions of\n   Python.  *Any* use of "__*__" names, in any context, that does not\n   follow explicitly documented use, is subject to breakage without\n   warning.\n\n"__*"\n   Class-private names.  Names in this category, when used within the\n   context of a class definition, are re-written to use a mangled form\n   to help avoid name clashes between "private" attributes of base and\n   derived classes. See section *Identifiers (Names)*.\n',
@@ -44,7 +44,7 @@ topics = {'assert': u'\nThe "assert" statement\n**********************\n\nAssert
  'import': u'\nThe "import" statement\n**********************\n\n   import_stmt     ::= "import" module ["as" name] ( "," module ["as" name] )*\n                   | "from" relative_module "import" identifier ["as" name]\n                   ( "," identifier ["as" name] )*\n                   | "from" relative_module "import" "(" identifier ["as" name]\n                   ( "," identifier ["as" name] )* [","] ")"\n                   | "from" module "import" "*"\n   module          ::= (identifier ".")* identifier\n   relative_module ::= "."* module | "."+\n   name            ::= identifier\n\nThe basic import statement (no "from" clause) is executed in two\nsteps:\n\n1. find a module, loading and initializing it if necessary\n\n2. define a name or names in the local namespace for the scope\n   where the "import" statement occurs.\n\nWhen the statement contains multiple clauses (separated by commas) the\ntwo steps are carried out separately for each clause, just as though\nthe clauses had been separated out into individual import statements.\n\nThe details of the first step, finding and loading modules are\ndescribed in greater detail in the section on the *import system*,\nwhich also describes the various types of packages and modules that\ncan be imported, as well as all the hooks that can be used to\ncustomize the import system. Note that failures in this step may\nindicate either that the module could not be located, *or* that an\nerror occurred while initializing the module, which includes execution\nof the module\'s code.\n\nIf the requested module is retrieved successfully, it will be made\navailable in the local namespace in one of three ways:\n\n* If the module name is followed by "as", then the name following\n  "as" is bound directly to the imported module.\n\n* If no other name is specified, and the module being imported is a\n  top level module, the module\'s name is bound in the local namespace\n  as a reference to the imported module\n\n* If the module being imported is *not* a top level module, then the\n  name of the top level package that contains the module is bound in\n  the local namespace as a reference to the top level package. The\n  imported module must be accessed using its full qualified name\n  rather than directly\n\nThe "from" form uses a slightly more complex process:\n\n1. find the module specified in the "from" clause, loading and\n   initializing it if necessary;\n\n2. for each of the identifiers specified in the "import" clauses:\n\n   1. check if the imported module has an attribute by that name\n\n   2. if not, attempt to import a submodule with that name and then\n      check the imported module again for that attribute\n\n   3. if the attribute is not found, "ImportError" is raised.\n\n   4. otherwise, a reference to that value is stored in the local\n      namespace, using the name in the "as" clause if it is present,\n      otherwise using the attribute name\n\nExamples:\n\n   import foo                 # foo imported and bound locally\n   import foo.bar.baz         # foo.bar.baz imported, foo bound locally\n   import foo.bar.baz as fbb  # foo.bar.baz imported and bound as fbb\n   from foo.bar import baz    # foo.bar.baz imported and bound as baz\n   from foo import attr       # foo imported and foo.attr bound as attr\n\nIf the list of identifiers is replaced by a star ("\'*\'"), all public\nnames defined in the module are bound in the local namespace for the\nscope where the "import" statement occurs.\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named "__all__"; if defined, it must\nbe a sequence of strings which are names defined or imported by that\nmodule.  The names given in "__all__" are all considered public and\nare required to exist.  If "__all__" is not defined, the set of public\nnames includes all names found in the module\'s namespace which do not\nbegin with an underscore character ("\'_\'").  "__all__" should contain\nthe entire public API. It is intended to avoid accidentally exporting\nitems that are not part of the API (such as library modules which were\nimported and used within the module).\n\nThe wild card form of import --- "from module import *" --- is only\nallowed at the module level.  Attempting to use it in class or\nfunction definitions will raise a "SyntaxError".\n\nWhen specifying what module to import you do not have to specify the\nabsolute name of the module. When a module or package is contained\nwithin another package it is possible to make a relative import within\nthe same top package without having to mention the package name. By\nusing leading dots in the specified module or package after "from" you\ncan specify how high to traverse up the current package hierarchy\nwithout specifying exact names. One leading dot means the current\npackage where the module making the import exists. Two dots means up\none package level. Three dots is up two levels, etc. So if you execute\n"from . import mod" from a module in the "pkg" package then you will\nend up importing "pkg.mod". If you execute "from ..subpkg2 import mod"\nfrom within "pkg.subpkg1" you will import "pkg.subpkg2.mod". The\nspecification for relative imports is contained within **PEP 328**.\n\n"importlib.import_module()" is provided to support applications that\ndetermine dynamically the modules to be loaded.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python where the feature\nbecomes standard.\n\nThe future statement is intended to ease migration to future versions\nof Python that introduce incompatible changes to the language.  It\nallows use of the new features on a per-module basis before the\nrelease in which the feature becomes standard.\n\n   future_statement ::= "from" "__future__" "import" feature ["as" name]\n                        ("," feature ["as" name])*\n                        | "from" "__future__" "import" "(" feature ["as" name]\n                        ("," feature ["as" name])* [","] ")"\n   feature          ::= identifier\n   name             ::= identifier\n\nA future statement must appear near the top of the module.  The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 3.0 are "absolute_import",\n"division", "generators", "unicode_literals", "print_function",\n"nested_scopes" and "with_statement".  They are all redundant because\nthey are always enabled, and only kept for backwards compatibility.\n\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code.  It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently.  Such decisions cannot be pushed off until\nruntime.\n\nFor any given release, the compiler knows which feature names have\nbeen defined, and raises a compile-time error if a future statement\ncontains a feature not known to it.\n\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module "__future__", described later, and it will\nbe imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n   import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by calls to the built-in functions "exec()" and\n"compile()" that occur in a module "M" containing a future statement\nwill, by default, use the new syntax or semantics associated with the\nfuture statement.  This can be controlled by optional arguments to\n"compile()" --- see the documentation of that function for details.\n\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session.  If an\ninterpreter is started with the *-i* option, is passed a script name\nto execute, and the script includes a future statement, it will be in\neffect in the interactive session started after the script is\nexecuted.\n\nSee also: **PEP 236** - Back to the __future__\n\n     The original proposal for the __future__ mechanism.\n',
  'in': u'\nMembership test operations\n**************************\n\nThe operators "in" and "not in" test for membership.  "x in s"\nevaluates to true if *x* is a member of *s*, and false otherwise.  "x\nnot in s" returns the negation of "x in s".  All built-in sequences\nand set types support this as well as dictionary, for which "in" tests\nwhether the dictionary has a given key. For container types such as\nlist, tuple, set, frozenset, dict, or collections.deque, the\nexpression "x in y" is equivalent to "any(x is e or x == e for e in\ny)".\n\nFor the string and bytes types, "x in y" is true if and only if *x* is\na substring of *y*.  An equivalent test is "y.find(x) != -1".  Empty\nstrings are always considered to be a substring of any other string,\nso """ in "abc"" will return "True".\n\nFor user-defined classes which define the "__contains__()" method, "x\nin y" is true if and only if "y.__contains__(x)" is true.\n\nFor user-defined classes which do not define "__contains__()" but do\ndefine "__iter__()", "x in y" is true if some value "z" with "x == z"\nis produced while iterating over "y".  If an exception is raised\nduring the iteration, it is as if "in" raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n"__getitem__()", "x in y" is true if and only if there is a non-\nnegative integer index *i* such that "x == y[i]", and all lower\ninteger indices do not raise "IndexError" exception.  (If any other\nexception is raised, it is as if "in" raised that exception).\n\nThe operator "not in" is defined to have the inverse true value of\n"in".\n',
  'integers': u'\nInteger literals\n****************\n\nInteger literals are described by the following lexical definitions:\n\n   integer        ::= decimalinteger | octinteger | hexinteger | bininteger\n   decimalinteger ::= nonzerodigit digit* | "0"+\n   nonzerodigit   ::= "1"..."9"\n   digit          ::= "0"..."9"\n   octinteger     ::= "0" ("o" | "O") octdigit+\n   hexinteger     ::= "0" ("x" | "X") hexdigit+\n   bininteger     ::= "0" ("b" | "B") bindigit+\n   octdigit       ::= "0"..."7"\n   hexdigit       ::= digit | "a"..."f" | "A"..."F"\n   bindigit       ::= "0" | "1"\n\nThere is no limit for the length of integer literals apart from what\ncan be stored in available memory.\n\nNote that leading zeros in a non-zero decimal number are not allowed.\nThis is for disambiguation with C-style octal literals, which Python\nused before version 3.0.\n\nSome examples of integer literals:\n\n   7     2147483647                        0o177    0b100110111\n   3     79228162514264337593543950336     0o377    0xdeadbeef\n',
- 'lambda': u'\nLambdas\n*******\n\n   lambda_expr        ::= "lambda" [parameter_list]: expression\n   lambda_expr_nocond ::= "lambda" [parameter_list]: expression_nocond\n\nLambda expressions (sometimes called lambda forms) are used to create\nanonymous functions. The expression "lambda arguments: expression"\nyields a function object.  The unnamed object behaves like a function\nobject defined with\n\n   def <lambda>(arguments):\n       return expression\n\nSee section *Function definitions* for the syntax of parameter lists.\nNote that functions created with lambda expressions cannot contain\nstatements or annotations.\n',
+ 'lambda': u'\nLambdas\n*******\n\n   lambda_expr        ::= "lambda" [parameter_list]: expression\n   lambda_expr_nocond ::= "lambda" [parameter_list]: expression_nocond\n\nLambda expressions (sometimes called lambda forms) are used to create\nanonymous functions. The expression "lambda arguments: expression"\nyields a function object.  The unnamed object behaves like a function\nobject defined with:\n\n   def <lambda>(arguments):\n       return expression\n\nSee section *Function definitions* for the syntax of parameter lists.\nNote that functions created with lambda expressions cannot contain\nstatements or annotations.\n',
  'lists': u'\nList displays\n*************\n\nA list display is a possibly empty series of expressions enclosed in\nsquare brackets:\n\n   list_display ::= "[" [starred_list | comprehension] "]"\n\nA list display yields a new list object, the contents being specified\nby either a list of expressions or a comprehension.  When a comma-\nseparated list of expressions is supplied, its elements are evaluated\nfrom left to right and placed into the list object in that order.\nWhen a comprehension is supplied, the list is constructed from the\nelements resulting from the comprehension.\n',
  'naming': u'\nNaming and binding\n******************\n\n\nBinding of names\n================\n\n*Names* refer to objects.  Names are introduced by name binding\noperations.\n\nThe following constructs bind names: formal parameters to functions,\n"import" statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, "for" loop header, or after\n"as" in a "with" statement or "except" clause. The "import" statement\nof the form "from ... import *" binds all names defined in the\nimported module, except those beginning with an underscore.  This form\nmay only be used at the module level.\n\nA target occurring in a "del" statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as "nonlocal" or "global".  If a name is bound at the\nmodule level, it is a global variable.  (The variables of the module\ncode block are local and global.)  If a variable is used in a code\nblock but not defined there, it is a *free variable*.\n\nEach occurrence of a name in the program text refers to the *binding*\nof that name established by the following name resolution rules.\n\n\nResolution of names\n===================\n\nA *scope* defines the visibility of a name within a block.  If a local\nvariable is defined in a block, its scope includes that block.  If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name.\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope.  The set of all such scopes visible to a code block\nis called the block\'s *environment*.\n\nWhen a name is not found at all, a "NameError" exception is raised. If\nthe current scope is a function scope, and the name refers to a local\nvariable that has not yet been bound to a value at the point where the\nname is used, an "UnboundLocalError" exception is raised.\n"UnboundLocalError" is a subclass of "NameError".\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block.  This can lead to errors when a name is used within a\nblock before it is bound.  This rule is subtle.  Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block.  The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the "global" statement occurs within a block, all uses of the name\nspecified in the statement refer to the binding of that name in the\ntop-level namespace.  Names are resolved in the top-level namespace by\nsearching the global namespace, i.e. the namespace of the module\ncontaining the code block, and the builtins namespace, the namespace\nof the module "builtins".  The global namespace is searched first.  If\nthe name is not found there, the builtins namespace is searched.  The\n"global" statement must precede all uses of the name.\n\nThe "global" statement has the same scope as a name binding operation\nin the same block.  If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\n\nThe "nonlocal" statement causes corresponding names to refer to\npreviously bound variables in the nearest enclosing function scope.\n"SyntaxError" is raised at compile time if the given name does not\nexist in any enclosing function scope.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported.  The main module for a script is always called\n"__main__".\n\nClass definition blocks and arguments to "exec()" and "eval()" are\nspecial in the context of name resolution. A class definition is an\nexecutable statement that may use and define names. These references\nfollow the normal rules for name resolution with an exception that\nunbound local variables are looked up in the global namespace. The\nnamespace of the class definition becomes the attribute dictionary of\nthe class. The scope of names defined in a class block is limited to\nthe class block; it does not extend to the code blocks of methods --\nthis includes comprehensions and generator expressions since they are\nimplemented using a function scope.  This means that the following\nwill fail:\n\n   class A:\n       a = 42\n       b = list(a + i for i in range(10))\n\n\nBuiltins and restricted execution\n=================================\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name "__builtins__" in its global\nnamespace; this should be a dictionary or a module (in the latter case\nthe module\'s dictionary is used).  By default, when in the "__main__"\nmodule, "__builtins__" is the built-in module "builtins"; when in any\nother module, "__builtins__" is an alias for the dictionary of the\n"builtins" module itself.  "__builtins__" can be set to a user-created\ndictionary to create a weak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n"__builtins__"; it is strictly an implementation detail.  Users\nwanting to override values in the builtins namespace should "import"\nthe "builtins" module and modify its attributes appropriately.\n\n\nInteraction with dynamic features\n=================================\n\nName resolution of free variables occurs at runtime, not at compile\ntime. This means that the following code will print 42:\n\n   i = 10\n   def f():\n       print(i)\n   i = 42\n   f()\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nThe "eval()" and "exec()" functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe "exec()" and "eval()" functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n',
  'nonlocal': u'\nThe "nonlocal" statement\n************************\n\n   nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*\n\nThe "nonlocal" statement causes the listed identifiers to refer to\npreviously bound variables in the nearest enclosing scope excluding\nglobals. This is important because the default behavior for binding is\nto search the local namespace first.  The statement allows\nencapsulated code to rebind variables outside of the local scope\nbesides the global (module) scope.\n\nNames listed in a "nonlocal" statement, unlike those listed in a\n"global" statement, must refer to pre-existing bindings in an\nenclosing scope (the scope in which a new binding should be created\ncannot be determined unambiguously).\n\nNames listed in a "nonlocal" statement must not collide with pre-\nexisting bindings in the local scope.\n\nSee also: **PEP 3104** - Access to Names in Outer Scopes\n\n     The specification for the "nonlocal" statement.\n',
@@ -59,19 +59,19 @@ topics = {'assert': u'\nThe "assert" statement\n**********************\n\nAssert
  'sequence-types': u'\nEmulating container types\n*************************\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well.  The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which "0 <= k < N" where\n*N* is the length of the sequence, or slice objects, which define a\nrange of items.  It is also recommended that mappings provide the\nmethods "keys()", "values()", "items()", "get()", "clear()",\n"setdefault()", "pop()", "popitem()", "copy()", and "update()"\nbehaving similar to those for Python\'s standard dictionary objects.\nThe "collections" module provides a "MutableMapping" abstract base\nclass to help create those methods from a base set of "__getitem__()",\n"__setitem__()", "__delitem__()", and "keys()". Mutable sequences\nshould provide methods "append()", "count()", "index()", "extend()",\n"insert()", "pop()", "remove()", "reverse()" and "sort()", like Python\nstandard list objects.  Finally, sequence types should implement\naddition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods "__add__()", "__radd__()",\n"__iadd__()", "__mul__()", "__rmul__()" and "__imul__()" described\nbelow; they should not define other numerical operators.  It is\nrecommended that both mappings and sequences implement the\n"__contains__()" method to allow efficient use of the "in" operator;\nfor mappings, "in" should search the mapping\'s keys; for sequences, it\nshould search through the values.  It is further recommended that both\nmappings and sequences implement the "__iter__()" method to allow\nefficient iteration through the container; for mappings, "__iter__()"\nshould be the same as "keys()"; for sequences, it should iterate\nthrough the values.\n\nobject.__len__(self)\n\n   Called to implement the built-in function "len()".  Should return\n   the length of the object, an integer ">=" 0.  Also, an object that\n   doesn\'t define a "__bool__()" method and whose "__len__()" method\n   returns zero is considered to be false in a Boolean context.\n\nobject.__length_hint__(self)\n\n   Called to implement "operator.length_hint()". Should return an\n   estimated length for the object (which may be greater or less than\n   the actual length). The length must be an integer ">=" 0. This\n   method is purely an optimization and is never required for\n   correctness.\n\n   New in version 3.4.\n\nNote: Slicing is done exclusively with the following three methods.\n  A call like\n\n     a[1:2] = b\n\n  is translated to\n\n     a[slice(1, 2, None)] = b\n\n  and so forth.  Missing slice items are always filled in with "None".\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of "self[key]". For sequence types,\n   the accepted keys should be integers and slice objects.  Note that\n   the special interpretation of negative indexes (if the class wishes\n   to emulate a sequence type) is up to the "__getitem__()" method. If\n   *key* is of an inappropriate type, "TypeError" may be raised; if of\n   a value outside the set of indexes for the sequence (after any\n   special interpretation of negative values), "IndexError" should be\n   raised. For mapping types, if *key* is missing (not in the\n   container), "KeyError" should be raised.\n\n   Note: "for" loops expect that an "IndexError" will be raised for\n     illegal indexes to allow proper detection of the end of the\n     sequence.\n\nobject.__missing__(self, key)\n\n   Called by "dict"."__getitem__()" to implement "self[key]" for dict\n   subclasses when key is not in the dictionary.\n\nobject.__setitem__(self, key, value)\n\n   Called to implement assignment to "self[key]".  Same note as for\n   "__getitem__()".  This should only be implemented for mappings if\n   the objects support changes to the values for keys, or if new keys\n   can be added, or for sequences if elements can be replaced.  The\n   same exceptions should be raised for improper *key* values as for\n   the "__getitem__()" method.\n\nobject.__delitem__(self, key)\n\n   Called to implement deletion of "self[key]".  Same note as for\n   "__getitem__()".  This should only be implemented for mappings if\n   the objects support removal of keys, or for sequences if elements\n   can be removed from the sequence.  The same exceptions should be\n   raised for improper *key* values as for the "__getitem__()" method.\n\nobject.__iter__(self)\n\n   This method is called when an iterator is required for a container.\n   This method should return a new iterator object that can iterate\n   over all the objects in the container.  For mappings, it should\n   iterate over the keys of the container.\n\n   Iterator objects also need to implement this method; they are\n   required to return themselves.  For more information on iterator\n   objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n   Called (if present) by the "reversed()" built-in to implement\n   reverse iteration.  It should return a new iterator object that\n   iterates over all the objects in the container in reverse order.\n\n   If the "__reversed__()" method is not provided, the "reversed()"\n   built-in will fall back to using the sequence protocol ("__len__()"\n   and "__getitem__()").  Objects that support the sequence protocol\n   should only provide "__reversed__()" if they can provide an\n   implementation that is more efficient than the one provided by\n   "reversed()".\n\nThe membership test operators ("in" and "not in") are normally\nimplemented as an iteration through a sequence.  However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n   Called to implement membership test operators.  Should return true\n   if *item* is in *self*, false otherwise.  For mapping objects, this\n   should consider the keys of the mapping rather than the values or\n   the key-item pairs.\n\n   For objects that don\'t define "__contains__()", the membership test\n   first tries iteration via "__iter__()", then the old sequence\n   iteration protocol via "__getitem__()", see *this section in the\n   language reference*.\n',
  'shifting': u'\nShifting operations\n*******************\n\nThe shifting operations have lower priority than the arithmetic\noperations:\n\n   shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n\nThese operators accept integers as arguments.  They shift the first\nargument to the left or right by the number of bits given by the\nsecond argument.\n\nA right shift by *n* bits is defined as floor division by "pow(2,n)".\nA left shift by *n* bits is defined as multiplication with "pow(2,n)".\n\nNote: In the current implementation, the right-hand operand is\n  required to be at most "sys.maxsize".  If the right-hand operand is\n  larger than "sys.maxsize" an "OverflowError" exception is raised.\n',
  'slicings': u'\nSlicings\n********\n\nA slicing selects a range of items in a sequence object (e.g., a\nstring, tuple or list).  Slicings may be used as expressions or as\ntargets in assignment or "del" statements.  The syntax for a slicing:\n\n   slicing      ::= primary "[" slice_list "]"\n   slice_list   ::= slice_item ("," slice_item)* [","]\n   slice_item   ::= expression | proper_slice\n   proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]\n   lower_bound  ::= expression\n   upper_bound  ::= expression\n   stride       ::= expression\n\nThere is ambiguity in the formal syntax here: anything that looks like\nan expression list also looks like a slice list, so any subscription\ncan be interpreted as a slicing.  Rather than further complicating the\nsyntax, this is disambiguated by defining that in this case the\ninterpretation as a subscription takes priority over the\ninterpretation as a slicing (this is the case if the slice list\ncontains no proper slice).\n\nThe semantics for a slicing are as follows.  The primary is indexed\n(using the same "__getitem__()" method as normal subscription) with a\nkey that is constructed from the slice list, as follows.  If the slice\nlist contains at least one comma, the key is a tuple containing the\nconversion of the slice items; otherwise, the conversion of the lone\nslice item is the key.  The conversion of a slice item that is an\nexpression is that expression.  The conversion of a proper slice is a\nslice object (see section *The standard type hierarchy*) whose\n"start", "stop" and "step" attributes are the values of the\nexpressions given as lower bound, upper bound and stride,\nrespectively, substituting "None" for missing expressions.\n',
- 'specialattrs': u'\nSpecial Attributes\n******************\n\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant.  Some of these are not reported\nby the "dir()" built-in function.\n\nobject.__dict__\n\n   A dictionary or other mapping object used to store an object\'s\n   (writable) attributes.\n\ninstance.__class__\n\n   The class to which a class instance belongs.\n\nclass.__bases__\n\n   The tuple of base classes of a class object.\n\nclass.__name__\n\n   The name of the class or type.\n\nclass.__qualname__\n\n   The *qualified name* of the class or type.\n\n   New in version 3.3.\n\nclass.__mro__\n\n   This attribute is a tuple of classes that are considered when\n   looking for base classes during method resolution.\n\nclass.mro()\n\n   This method can be overridden by a metaclass to customize the\n   method resolution order for its instances.  It is called at class\n   instantiation, and its result is stored in "__mro__".\n\nclass.__subclasses__()\n\n   Each class keeps a list of weak references to its immediate\n   subclasses.  This method returns a list of all those references\n   still alive. Example:\n\n      >>> int.__subclasses__()\n      [<class \'bool\'>]\n\n-[ Footnotes ]-\n\n[1] Additional information on these special methods may be found\n    in the Python Reference Manual (*Basic customization*).\n\n[2] As a consequence, the list "[1, 2]" is considered equal to\n    "[1.0, 2.0]", and similarly for tuples.\n\n[3] They must have since the parser can\'t tell the type of the\n    operands.\n\n[4] Cased characters are those with general category property\n    being one of "Lu" (Letter, uppercase), "Ll" (Letter, lowercase),\n    or "Lt" (Letter, titlecase).\n\n[5] To format only a tuple you should therefore provide a\n    singleton tuple whose only element is the tuple to be formatted.\n',
- 'specialnames': u'\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators.  For instance, if a class defines\na method named "__getitem__()", and "x" is an instance of this class,\nthen "x[i]" is roughly equivalent to "type(x).__getitem__(x, i)".\nExcept where mentioned, attempts to execute an operation raise an\nexception when no appropriate method is defined (typically\n"AttributeError" or "TypeError").\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled.  For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense.  (One example of this is the\n"NodeList" interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n   Called to create a new instance of class *cls*.  "__new__()" is a\n   static method (special-cased so you need not declare it as such)\n   that takes the class of which an instance was requested as its\n   first argument.  The remaining arguments are those passed to the\n   object constructor expression (the call to the class).  The return\n   value of "__new__()" should be the new object instance (usually an\n   instance of *cls*).\n\n   Typical implementations create a new instance of the class by\n   invoking the superclass\'s "__new__()" method using\n   "super(currentclass, cls).__new__(cls[, ...])" with appropriate\n   arguments and then modifying the newly-created instance as\n   necessary before returning it.\n\n   If "__new__()" returns an instance of *cls*, then the new\n   instance\'s "__init__()" method will be invoked like\n   "__init__(self[, ...])", where *self* is the new instance and the\n   remaining arguments are the same as were passed to "__new__()".\n\n   If "__new__()" does not return an instance of *cls*, then the new\n   instance\'s "__init__()" method will not be invoked.\n\n   "__new__()" is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called after the instance has been created (by "__new__()"), but\n   before it is returned to the caller.  The arguments are those\n   passed to the class constructor expression.  If a base class has an\n   "__init__()" method, the derived class\'s "__init__()" method, if\n   any, must explicitly call it to ensure proper initialization of the\n   base class part of the instance; for example:\n   "BaseClass.__init__(self, [args...])".\n\n   Because "__new__()" and "__init__()" work together in constructing\n   objects ("__new__()" to create it, and "__init__()" to customise\n   it), no non-"None" value may be returned by "__init__()"; doing so\n   will cause a "TypeError" to be raised at runtime.\n\nobject.__del__(self)\n\n   Called when the instance is about to be destroyed.  This is also\n   called a destructor.  If a base class has a "__del__()" method, the\n   derived class\'s "__del__()" method, if any, must explicitly call it\n   to ensure proper deletion of the base class part of the instance.\n   Note that it is possible (though not recommended!) for the\n   "__del__()" method to postpone destruction of the instance by\n   creating a new reference to it.  It may then be called at a later\n   time when this new reference is deleted.  It is not guaranteed that\n   "__del__()" methods are called for objects that still exist when\n   the interpreter exits.\n\n   Note: "del x" doesn\'t directly call "x.__del__()" --- the former\n     decrements the reference count for "x" by one, and the latter is\n     only called when "x"\'s reference count reaches zero.  Some common\n     situations that may prevent the reference count of an object from\n     going to zero include: circular references between objects (e.g.,\n     a doubly-linked list or a tree data structure with parent and\n     child pointers); a reference to the object on the stack frame of\n     a function that caught an exception (the traceback stored in\n     "sys.exc_info()[2]" keeps the stack frame alive); or a reference\n     to the object on the stack frame that raised an unhandled\n     exception in interactive mode (the traceback stored in\n     "sys.last_traceback" keeps the stack frame alive).  The first\n     situation can only be remedied by explicitly breaking the cycles;\n     the second can be resolved by freeing the reference to the\n     traceback object when it is no longer useful, and the third can\n     be resolved by storing "None" in "sys.last_traceback". Circular\n     references which are garbage are detected and cleaned up when the\n     cyclic garbage collector is enabled (it\'s on by default). Refer\n     to the documentation for the "gc" module for more information\n     about this topic.\n\n   Warning: Due to the precarious circumstances under which\n     "__del__()" methods are invoked, exceptions that occur during\n     their execution are ignored, and a warning is printed to\n     "sys.stderr" instead. Also, when "__del__()" is invoked in\n     response to a module being deleted (e.g., when execution of the\n     program is done), other globals referenced by the "__del__()"\n     method may already have been deleted or in the process of being\n     torn down (e.g. the import machinery shutting down).  For this\n     reason, "__del__()" methods should do the absolute minimum needed\n     to maintain external invariants.  Starting with version 1.5,\n     Python guarantees that globals whose name begins with a single\n     underscore are deleted from their module before other globals are\n     deleted; if no other references to such globals exist, this may\n     help in assuring that imported modules are still available at the\n     time when the "__del__()" method is called.\n\nobject.__repr__(self)\n\n   Called by the "repr()" built-in function to compute the "official"\n   string representation of an object.  If at all possible, this\n   should look like a valid Python expression that could be used to\n   recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   "<...some useful description...>" should be returned. The return\n   value must be a string object. If a class defines "__repr__()" but\n   not "__str__()", then "__repr__()" is also used when an "informal"\n   string representation of instances of that class is required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by "str(object)" and the built-in functions "format()" and\n   "print()" to compute the "informal" or nicely printable string\n   representation of an object.  The return value must be a *string*\n   object.\n\n   This method differs from "object.__repr__()" in that there is no\n   expectation that "__str__()" return a valid Python expression: a\n   more convenient or concise representation can be used.\n\n   The default implementation defined by the built-in type "object"\n   calls "object.__repr__()".\n\nobject.__bytes__(self)\n\n   Called by "bytes()" to compute a byte-string representation of an\n   object. This should return a "bytes" object.\n\nobject.__format__(self, format_spec)\n\n   Called by the "format()" built-in function (and by extension, the\n   "str.format()" method of class "str") to produce a "formatted"\n   string representation of an object. The "format_spec" argument is a\n   string that contains a description of the formatting options\n   desired. The interpretation of the "format_spec" argument is up to\n   the type implementing "__format__()", however most classes will\n   either delegate formatting to one of the built-in types, or use a\n   similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\n   Changed in version 3.4: The __format__ method of "object" itself\n   raises a "TypeError" if passed any non-empty string.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",\n   "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls\n   "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n   A rich comparison method may return the singleton "NotImplemented"\n   if it does not implement the operation for a given pair of\n   arguments. By convention, "False" and "True" are returned for a\n   successful comparison. However, these methods can return any value,\n   so if the comparison operator is used in a Boolean context (e.g.,\n   in the condition of an "if" statement), Python will call "bool()"\n   on the value to determine if the result is true or false.\n\n   By default, "__ne__()" delegates to "__eq__()" and inverts the\n   result unless it is "NotImplemented".  There are no other implied\n   relationships among the comparison operators, for example, the\n   truth of "(x<y or x==y)" does not imply "x<=y". To automatically\n   generate ordering operations from a single root operation, see\n   "functools.total_ordering()".\n\n   See the paragraph on "__hash__()" for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\n\n   There are no swapped-argument versions of these methods (to be used\n   when the left argument does not support the operation but the right\n   argument does); rather, "__lt__()" and "__gt__()" are each other\'s\n   reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n   and "__eq__()" and "__ne__()" are their own reflection. If the\n   operands are of different types, and right operand\'s type is a\n   direct or indirect subclass of the left operand\'s type, the\n   reflected method of the right operand has priority, otherwise the\n   left operand\'s method has priority.  Virtual subclassing is not\n   considered.\n\nobject.__hash__(self)\n\n   Called by built-in function "hash()" and for operations on members\n   of hashed collections including "set", "frozenset", and "dict".\n   "__hash__()" should return an integer.  The only required property\n   is that objects which compare equal have the same hash value; it is\n   advised to somehow mix together (e.g. using exclusive or) the hash\n   values for the components of the object that also play a part in\n   comparison of objects.\n\n   Note: "hash()" truncates the value returned from an object\'s\n     custom "__hash__()" method to the size of a "Py_ssize_t".  This\n     is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit\n     builds. If an object\'s   "__hash__()" must interoperate on builds\n     of different bit sizes, be sure to check the width on all\n     supported builds.  An easy way to do this is with "python -c\n     "import sys; print(sys.hash_info.width)"".\n\n   If a class does not define an "__eq__()" method it should not\n   define a "__hash__()" operation either; if it defines "__eq__()"\n   but not "__hash__()", its instances will not be usable as items in\n   hashable collections.  If a class defines mutable objects and\n   implements an "__eq__()" method, it should not implement\n   "__hash__()", since the implementation of hashable collections\n   requires that a key\'s hash value is immutable (if the object\'s hash\n   value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have "__eq__()" and "__hash__()" methods by\n   default; with them, all objects compare unequal (except with\n   themselves) and "x.__hash__()" returns an appropriate value such\n   that "x == y" implies both that "x is y" and "hash(x) == hash(y)".\n\n   A class that overrides "__eq__()" and does not define "__hash__()"\n   will have its "__hash__()" implicitly set to "None".  When the\n   "__hash__()" method of a class is "None", instances of the class\n   will raise an appropriate "TypeError" when a program attempts to\n   retrieve their hash value, and will also be correctly identified as\n   unhashable when checking "isinstance(obj, collections.Hashable)".\n\n   If a class that overrides "__eq__()" needs to retain the\n   implementation of "__hash__()" from a parent class, the interpreter\n   must be told this explicitly by setting "__hash__ =\n   <ParentClass>.__hash__".\n\n   If a class that does not override "__eq__()" wishes to suppress\n   hash support, it should include "__hash__ = None" in the class\n   definition. A class which defines its own "__hash__()" that\n   explicitly raises a "TypeError" would be incorrectly identified as\n   hashable by an "isinstance(obj, collections.Hashable)" call.\n\n   Note: By default, the "__hash__()" values of str, bytes and\n     datetime objects are "salted" with an unpredictable random value.\n     Although they remain constant within an individual Python\n     process, they are not predictable between repeated invocations of\n     Python.This is intended to provide protection against a denial-\n     of-service caused by carefully-chosen inputs that exploit the\n     worst case performance of a dict insertion, O(n^2) complexity.\n     See http://www.ocert.org/advisories/ocert-2011-003.html for\n     details.Changing hash values affects the iteration order of\n     dicts, sets and other mappings.  Python has never made guarantees\n     about this ordering (and it typically varies between 32-bit and\n     64-bit builds).See also "PYTHONHASHSEED".\n\n   Changed in version 3.3: Hash randomization is enabled by default.\n\nobject.__bool__(self)\n\n   Called to implement truth value testing and the built-in operation\n   "bool()"; should return "False" or "True".  When this method is not\n   defined, "__len__()" is called, if it is defined, and the object is\n   considered true if its result is nonzero.  If a class defines\n   neither "__len__()" nor "__bool__()", all its instances are\n   considered true.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of "x.name") for\nclass instances.\n\nobject.__getattr__(self, name)\n\n   Called when an attribute lookup has not found the attribute in the\n   usual places (i.e. it is not an instance attribute nor is it found\n   in the class tree for "self").  "name" is the attribute name. This\n   method should return the (computed) attribute value or raise an\n   "AttributeError" exception.\n\n   Note that if the attribute is found through the normal mechanism,\n   "__getattr__()" is not called.  (This is an intentional asymmetry\n   between "__getattr__()" and "__setattr__()".) This is done both for\n   efficiency reasons and because otherwise "__getattr__()" would have\n   no way to access other attributes of the instance.  Note that at\n   least for instance variables, you can fake total control by not\n   inserting any values in the instance attribute dictionary (but\n   instead inserting them in another object).  See the\n   "__getattribute__()" method below for a way to actually get total\n   control over attribute access.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines "__getattr__()",\n   the latter will not be called unless "__getattribute__()" either\n   calls it explicitly or raises an "AttributeError". This method\n   should return the (computed) attribute value or raise an\n   "AttributeError" exception. In order to avoid infinite recursion in\n   this method, its implementation should always call the base class\n   method with the same name to access any attributes it needs, for\n   example, "object.__getattribute__(self, name)".\n\n   Note: This method may still be bypassed when looking up special\n     methods as the result of implicit invocation via language syntax\n     or built-in functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n   Called when an attribute assignment is attempted.  This is called\n   instead of the normal mechanism (i.e. store the value in the\n   instance dictionary). *name* is the attribute name, *value* is the\n   value to be assigned to it.\n\n   If "__setattr__()" wants to assign to an instance attribute, it\n   should call the base class method with the same name, for example,\n   "object.__setattr__(self, name, value)".\n\nobject.__delattr__(self, name)\n\n   Like "__setattr__()" but for attribute deletion instead of\n   assignment.  This should only be implemented if "del obj.name" is\n   meaningful for the object.\n\nobject.__dir__(self)\n\n   Called when "dir()" is called on the object. A sequence must be\n   returned. "dir()" converts the returned sequence to a list and\n   sorts it.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents).  In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' "__dict__".\n\nobject.__get__(self, instance, owner)\n\n   Called to get the attribute of the owner class (class attribute\n   access) or of an instance of that class (instance attribute\n   access). *owner* is always the owner class, while *instance* is the\n   instance that the attribute was accessed through, or "None" when\n   the attribute is accessed through the *owner*.  This method should\n   return the (computed) attribute value or raise an "AttributeError"\n   exception.\n\nobject.__set__(self, instance, value)\n\n   Called to set the attribute on an instance *instance* of the owner\n   class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n   Called to delete the attribute on an instance *instance* of the\n   owner class.\n\nThe attribute "__objclass__" is interpreted by the "inspect" module as\nspecifying the class where this object was defined (setting this\nappropriately can assist in runtime introspection of dynamic class\nattributes). For callables, it may indicate that an instance of the\ngiven type (or a subclass) is expected or required as the first\npositional argument (for example, CPython sets this attribute for\nunbound methods that are implemented in C).\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol:  "__get__()", "__set__()", and\n"__delete__()". If any of those methods are defined for an object, it\nis said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, "a.x" has a\nlookup chain starting with "a.__dict__[\'x\']", then\n"type(a).__dict__[\'x\']", and continuing through the base classes of\n"type(a)" excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead.  Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, "a.x". How\nthe arguments are assembled depends on "a":\n\nDirect Call\n   The simplest and least common call is when user code directly\n   invokes a descriptor method:    "x.__get__(a)".\n\nInstance Binding\n   If binding to an object instance, "a.x" is transformed into the\n   call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n\nClass Binding\n   If binding to a class, "A.x" is transformed into the call:\n   "A.__dict__[\'x\'].__get__(None, A)".\n\nSuper Binding\n   If "a" is an instance of "super", then the binding "super(B,\n   obj).m()" searches "obj.__class__.__mro__" for the base class "A"\n   immediately preceding "B" and then invokes the descriptor with the\n   call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined.  A descriptor can define\nany combination of "__get__()", "__set__()" and "__delete__()".  If it\ndoes not define "__get__()", then accessing the attribute will return\nthe descriptor object itself unless there is a value in the object\'s\ninstance dictionary.  If the descriptor defines "__set__()" and/or\n"__delete__()", it is a data descriptor; if it defines neither, it is\na non-data descriptor.  Normally, data descriptors define both\n"__get__()" and "__set__()", while non-data descriptors have just the\n"__get__()" method.  Data descriptors with "__set__()" and "__get__()"\ndefined always override a redefinition in an instance dictionary.  In\ncontrast, non-data descriptors can be overridden by instances.\n\nPython methods (including "staticmethod()" and "classmethod()") are\nimplemented as non-data descriptors.  Accordingly, instances can\nredefine and override methods.  This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe "property()" function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of classes have a dictionary for attribute\nstorage.  This wastes space for objects having very few instance\nvariables.  The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable.  Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n   This class variable can be assigned a string, iterable, or sequence\n   of strings with variable names used by instances.  *__slots__*\n   reserves space for the declared variables and prevents the\n   automatic creation of *__dict__* and *__weakref__* for each\n   instance.\n\n\nNotes on using *__slots__*\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n  attribute of that class will always be accessible, so a *__slots__*\n  definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n  variables not listed in the *__slots__* definition.  Attempts to\n  assign to an unlisted variable name raises "AttributeError". If\n  dynamic assignment of new variables is desired, then add\n  "\'__dict__\'" to the sequence of strings in the *__slots__*\n  declaration.\n\n* Without a *__weakref__* variable for each instance, classes\n  defining *__slots__* do not support weak references to its\n  instances. If weak reference support is needed, then add\n  "\'__weakref__\'" to the sequence of strings in the *__slots__*\n  declaration.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (*Implementing Descriptors*) for each variable name.  As\n  a result, class attributes cannot be used to set default values for\n  instance variables defined by *__slots__*; otherwise, the class\n  attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n  where it is defined.  As a result, subclasses will have a *__dict__*\n  unless they also define *__slots__* (which must only contain names\n  of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the\n  instance variable defined by the base class slot is inaccessible\n  (except by retrieving its descriptor directly from the base class).\n  This renders the meaning of the program undefined.  In the future, a\n  check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n  "variable-length" built-in types such as "int", "bytes" and "tuple".\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings\n  may also be used; however, in the future, special meaning may be\n  assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n  *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, classes are constructed using "type()". The class body is\nexecuted in a new namespace and the class name is bound locally to the\nresult of "type(name, bases, namespace)".\n\nThe class creation process can be customised by passing the\n"metaclass" keyword argument in the class definition line, or by\ninheriting from an existing class that included such an argument. In\nthe following example, both "MyClass" and "MySubclass" are instances\nof "Meta":\n\n   class Meta(type):\n       pass\n\n   class MyClass(metaclass=Meta):\n       pass\n\n   class MySubclass(MyClass):\n       pass\n\nAny other keyword arguments that are specified in the class definition\nare passed through to all metaclass operations described below.\n\nWhen a class definition is executed, the following steps occur:\n\n* the appropriate metaclass is determined\n\n* the class namespace is prepared\n\n* the class body is executed\n\n* the class object is created\n\n\nDetermining the appropriate metaclass\n-------------------------------------\n\nThe appropriate metaclass for a class definition is determined as\nfollows:\n\n* if no bases and no explicit metaclass are given, then "type()" is\n  used\n\n* if an explicit metaclass is given and it is *not* an instance of\n  "type()", then it is used directly as the metaclass\n\n* if an instance of "type()" is given as the explicit metaclass, or\n  bases are defined, then the most derived metaclass is used\n\nThe most derived metaclass is selected from the explicitly specified\nmetaclass (if any) and the metaclasses (i.e. "type(cls)") of all\nspecified base classes. The most derived metaclass is one which is a\nsubtype of *all* of these candidate metaclasses. If none of the\ncandidate metaclasses meets that criterion, then the class definition\nwill fail with "TypeError".\n\n\nPreparing the class namespace\n-----------------------------\n\nOnce the appropriate metaclass has been identified, then the class\nnamespace is prepared. If the metaclass has a "__prepare__" attribute,\nit is called as "namespace = metaclass.__prepare__(name, bases,\n**kwds)" (where the additional keyword arguments, if any, come from\nthe class definition).\n\nIf the metaclass has no "__prepare__" attribute, then the class\nnamespace is initialised as an empty "dict()" instance.\n\nSee also: **PEP 3115** - Metaclasses in Python 3000\n\n     Introduced the "__prepare__" namespace hook\n\n\nExecuting the class body\n------------------------\n\nThe class body is executed (approximately) as "exec(body, globals(),\nnamespace)". The key difference from a normal call to "exec()" is that\nlexical scoping allows the class body (including any methods) to\nreference names from the current and outer scopes when the class\ndefinition occurs inside a function.\n\nHowever, even when the class definition occurs inside the function,\nmethods defined inside the class still cannot see names defined at the\nclass scope. Class variables must be accessed through the first\nparameter of instance or class methods, and cannot be accessed at all\nfrom static methods.\n\n\nCreating the class object\n-------------------------\n\nOnce the class namespace has been populated by executing the class\nbody, the class object is created by calling "metaclass(name, bases,\nnamespace, **kwds)" (the additional keywords passed here are the same\nas those passed to "__prepare__").\n\nThis class object is the one that will be referenced by the zero-\nargument form of "super()". "__class__" is an implicit closure\nreference created by the compiler if any methods in a class body refer\nto either "__class__" or "super". This allows the zero argument form\nof "super()" to correctly identify the class being defined based on\nlexical scoping, while the class or instance that was used to make the\ncurrent call is identified based on the first argument passed to the\nmethod.\n\nAfter the class object is created, it is passed to the class\ndecorators included in the class definition (if any) and the resulting\nobject is bound in the local namespace as the defined class.\n\nWhen a new class is created by "type.__new__", the object provided as\nthe namespace parameter is copied to a standard Python dictionary and\nthe original object is discarded. The new copy becomes the "__dict__"\nattribute of the class object.\n\nSee also: **PEP 3135** - New super\n\n     Describes the implicit "__class__" closure reference\n\n\nMetaclass example\n-----------------\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored include logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\nHere is an example of a metaclass that uses an\n"collections.OrderedDict" to remember the order that class variables\nare defined:\n\n   class OrderedClass(type):\n\n       @classmethod\n       def __prepare__(metacls, name, bases, **kwds):\n           return collections.OrderedDict()\n\n       def __new__(cls, name, bases, namespace, **kwds):\n           result = type.__new__(cls, name, bases, dict(namespace))\n           result.members = tuple(namespace)\n           return result\n\n   class A(metaclass=OrderedClass):\n       def one(self): pass\n       def two(self): pass\n       def three(self): pass\n       def four(self): pass\n\n   >>> A.members\n   (\'__module__\', \'one\', \'two\', \'three\', \'four\')\n\nWhen the class definition for *A* gets executed, the process begins\nwith calling the metaclass\'s "__prepare__()" method which returns an\nempty "collections.OrderedDict".  That mapping records the methods and\nattributes of *A* as they are defined within the body of the class\nstatement. Once those definitions are executed, the ordered dictionary\nis fully populated and the metaclass\'s "__new__()" method gets\ninvoked.  That method builds the new type and it saves the ordered\ndictionary keys in an attribute called "members".\n\n\nCustomizing instance and subclass checks\n========================================\n\nThe following methods are used to override the default behavior of the\n"isinstance()" and "issubclass()" built-in functions.\n\nIn particular, the metaclass "abc.ABCMeta" implements these methods in\norder to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\n   Return true if *instance* should be considered a (direct or\n   indirect) instance of *class*. If defined, called to implement\n   "isinstance(instance, class)".\n\nclass.__subclasscheck__(self, subclass)\n\n   Return true if *subclass* should be considered a (direct or\n   indirect) subclass of *class*.  If defined, called to implement\n   "issubclass(subclass, class)".\n\nNote that these methods are looked up on the type (metaclass) of a\nclass.  They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also: **PEP 3119** - Introducing Abstract Base Classes\n\n     Includes the specification for customizing "isinstance()" and\n     "issubclass()" behavior through "__instancecheck__()" and\n     "__subclasscheck__()", with motivation for this functionality in\n     the context of adding Abstract Base Classes (see the "abc"\n     module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n   Called when the instance is "called" as a function; if this method\n   is defined, "x(arg1, arg2, ...)" is a shorthand for\n   "x.__call__(arg1, arg2, ...)".\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well.  The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which "0 <= k < N" where\n*N* is the length of the sequence, or slice objects, which define a\nrange of items.  It is also recommended that mappings provide the\nmethods "keys()", "values()", "items()", "get()", "clear()",\n"setdefault()", "pop()", "popitem()", "copy()", and "update()"\nbehaving similar to those for Python\'s standard dictionary objects.\nThe "collections" module provides a "MutableMapping" abstract base\nclass to help create those methods from a base set of "__getitem__()",\n"__setitem__()", "__delitem__()", and "keys()". Mutable sequences\nshould provide methods "append()", "count()", "index()", "extend()",\n"insert()", "pop()", "remove()", "reverse()" and "sort()", like Python\nstandard list objects.  Finally, sequence types should implement\naddition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods "__add__()", "__radd__()",\n"__iadd__()", "__mul__()", "__rmul__()" and "__imul__()" described\nbelow; they should not define other numerical operators.  It is\nrecommended that both mappings and sequences implement the\n"__contains__()" method to allow efficient use of the "in" operator;\nfor mappings, "in" should search the mapping\'s keys; for sequences, it\nshould search through the values.  It is further recommended that both\nmappings and sequences implement the "__iter__()" method to allow\nefficient iteration through the container; for mappings, "__iter__()"\nshould be the same as "keys()"; for sequences, it should iterate\nthrough the values.\n\nobject.__len__(self)\n\n   Called to implement the built-in function "len()".  Should return\n   the length of the object, an integer ">=" 0.  Also, an object that\n   doesn\'t define a "__bool__()" method and whose "__len__()" method\n   returns zero is considered to be false in a Boolean context.\n\nobject.__length_hint__(self)\n\n   Called to implement "operator.length_hint()". Should return an\n   estimated length for the object (which may be greater or less than\n   the actual length). The length must be an integer ">=" 0. This\n   method is purely an optimization and is never required for\n   correctness.\n\n   New in version 3.4.\n\nNote: Slicing is done exclusively with the following three methods.\n  A call like\n\n     a[1:2] = b\n\n  is translated to\n\n     a[slice(1, 2, None)] = b\n\n  and so forth.  Missing slice items are always filled in with "None".\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of "self[key]". For sequence types,\n   the accepted keys should be integers and slice objects.  Note that\n   the special interpretation of negative indexes (if the class wishes\n   to emulate a sequence type) is up to the "__getitem__()" method. If\n   *key* is of an inappropriate type, "TypeError" may be raised; if of\n   a value outside the set of indexes for the sequence (after any\n   special interpretation of negative values), "IndexError" should be\n   raised. For mapping types, if *key* is missing (not in the\n   container), "KeyError" should be raised.\n\n   Note: "for" loops expect that an "IndexError" will be raised for\n     illegal indexes to allow proper detection of the end of the\n     sequence.\n\nobject.__missing__(self, key)\n\n   Called by "dict"."__getitem__()" to implement "self[key]" for dict\n   subclasses when key is not in the dictionary.\n\nobject.__setitem__(self, key, value)\n\n   Called to implement assignment to "self[key]".  Same note as for\n   "__getitem__()".  This should only be implemented for mappings if\n   the objects support changes to the values for keys, or if new keys\n   can be added, or for sequences if elements can be replaced.  The\n   same exceptions should be raised for improper *key* values as for\n   the "__getitem__()" method.\n\nobject.__delitem__(self, key)\n\n   Called to implement deletion of "self[key]".  Same note as for\n   "__getitem__()".  This should only be implemented for mappings if\n   the objects support removal of keys, or for sequences if elements\n   can be removed from the sequence.  The same exceptions should be\n   raised for improper *key* values as for the "__getitem__()" method.\n\nobject.__iter__(self)\n\n   This method is called when an iterator is required for a container.\n   This method should return a new iterator object that can iterate\n   over all the objects in the container.  For mappings, it should\n   iterate over the keys of the container.\n\n   Iterator objects also need to implement this method; they are\n   required to return themselves.  For more information on iterator\n   objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n   Called (if present) by the "reversed()" built-in to implement\n   reverse iteration.  It should return a new iterator object that\n   iterates over all the objects in the container in reverse order.\n\n   If the "__reversed__()" method is not provided, the "reversed()"\n   built-in will fall back to using the sequence protocol ("__len__()"\n   and "__getitem__()").  Objects that support the sequence protocol\n   should only provide "__reversed__()" if they can provide an\n   implementation that is more efficient than the one provided by\n   "reversed()".\n\nThe membership test operators ("in" and "not in") are normally\nimplemented as an iteration through a sequence.  However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n   Called to implement membership test operators.  Should return true\n   if *item* is in *self*, false otherwise.  For mapping objects, this\n   should consider the keys of the mapping rather than the values or\n   the key-item pairs.\n\n   For objects that don\'t define "__contains__()", the membership test\n   first tries iteration via "__iter__()", then the old sequence\n   iteration protocol via "__getitem__()", see *this section in the\n   language reference*.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__matmul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",\n   "pow()", "**", "<<", ">>", "&", "^", "|").  For instance, to\n   evaluate the expression "x + y", where *x* is an instance of a\n   class that has an "__add__()" method, "x.__add__(y)" is called.\n   The "__divmod__()" method should be the equivalent to using\n   "__floordiv__()" and "__mod__()"; it should not be related to\n   "__truediv__()".  Note that "__pow__()" should be defined to accept\n   an optional third argument if the ternary version of the built-in\n   "pow()" function is to be supported.\n\n   If one of those methods does not support the operation with the\n   supplied arguments, it should return "NotImplemented".\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rmatmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",\n   "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)\n   operands.  These functions are only called if the left operand does\n   not support the corresponding operation and the operands are of\n   different types. [2] For instance, to evaluate the expression "x -\n   y", where *y* is an instance of a class that has an "__rsub__()"\n   method, "y.__rsub__(x)" is called if "x.__sub__(y)" returns\n   *NotImplemented*.\n\n   Note that ternary "pow()" will not try calling "__rpow__()" (the\n   coercion rules would become too complicated).\n\n   Note: If the right operand\'s type is a subclass of the left\n     operand\'s type and that subclass provides the reflected method\n     for the operation, this method will be called before the left\n     operand\'s non-reflected method.  This behavior allows subclasses\n     to override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__imatmul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n   These methods are called to implement the augmented arithmetic\n   assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",\n   "<<=", ">>=", "&=", "^=", "|=").  These methods should attempt to\n   do the operation in-place (modifying *self*) and return the result\n   (which could be, but does not have to be, *self*).  If a specific\n   method is not defined, the augmented assignment falls back to the\n   normal methods.  For instance, if *x* is an instance of a class\n   with an "__iadd__()" method, "x += y" is equivalent to "x =\n   x.__iadd__(y)" . Otherwise, "x.__add__(y)" and "y.__radd__(x)" are\n   considered, as with the evaluation of "x + y". In certain\n   situations, augmented assignment can result in unexpected errors\n   (see *Why does a_tuple[i] += [\'item\'] raise an exception when the\n   addition works?*), but this behavior is in fact part of the data\n   model.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n   Called to implement the unary arithmetic operations ("-", "+",\n   "abs()" and "~").\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n   Called to implement the built-in functions "complex()", "int()",\n   "float()" and "round()".  Should return a value of the appropriate\n   type.\n\nobject.__index__(self)\n\n   Called to implement "operator.index()", and whenever Python needs\n   to losslessly convert the numeric object to an integer object (such\n   as in slicing, or in the built-in "bin()", "hex()" and "oct()"\n   functions). Presence of this method indicates that the numeric\n   object is an integer type.  Must return an integer.\n\n   Note: In order to have a coherent integer type class, when\n     "__index__()" is defined "__int__()" should also be defined, and\n     both should return the same value.\n\n\nWith Statement Context Managers\n===============================\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a "with" statement. The context manager\nhandles the entry into, and the exit from, the desired runtime context\nfor the execution of the block of code.  Context managers are normally\ninvoked using the "with" statement (described in section *The with\nstatement*), but can also be used by directly invoking their methods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n   Enter the runtime context related to this object. The "with"\n   statement will bind this method\'s return value to the target(s)\n   specified in the "as" clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n   Exit the runtime context related to this object. The parameters\n   describe the exception that caused the context to be exited. If the\n   context was exited without an exception, all three arguments will\n   be "None".\n\n   If an exception is supplied, and the method wishes to suppress the\n   exception (i.e., prevent it from being propagated), it should\n   return a true value. Otherwise, the exception will be processed\n   normally upon exit from this method.\n\n   Note that "__exit__()" methods should not reraise the passed-in\n   exception; this is the caller\'s responsibility.\n\nSee also: **PEP 343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n\n\nSpecial method lookup\n=====================\n\nFor custom classes, implicit invocations of special methods are only\nguaranteed to work correctly if defined on an object\'s type, not in\nthe object\'s instance dictionary.  That behaviour is the reason why\nthe following code raises an exception:\n\n   >>> class C:\n   ...     pass\n   ...\n   >>> c = C()\n   >>> c.__len__ = lambda: 5\n   >>> len(c)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as "__hash__()" and "__repr__()" that are implemented by\nall objects, including type objects. If the implicit lookup of these\nmethods used the conventional lookup process, they would fail when\ninvoked on the type object itself:\n\n   >>> 1 .__hash__() == hash(1)\n   True\n   >>> int.__hash__() == hash(int)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n   >>> type(1).__hash__(1) == hash(1)\n   True\n   >>> type(int).__hash__(int) == hash(int)\n   True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe "__getattribute__()" method even of the object\'s metaclass:\n\n   >>> class Meta(type):\n   ...     def __getattribute__(*args):\n   ...         print("Metaclass getattribute invoked")\n   ...         return type.__getattribute__(*args)\n   ...\n   >>> class C(object, metaclass=Meta):\n   ...     def __len__(self):\n   ...         return 10\n   ...     def __getattribute__(*args):\n   ...         print("Class getattribute invoked")\n   ...         return object.__getattribute__(*args)\n   ...\n   >>> c = C()\n   >>> c.__len__()                 # Explicit lookup via instance\n   Class getattribute invoked\n   10\n   >>> type(c).__len__(c)          # Explicit lookup via type\n   Metaclass getattribute invoked\n   10\n   >>> len(c)                      # Implicit lookup\n   10\n\nBypassing the "__getattribute__()" machinery in this fashion provides\nsignificant scope for speed optimisations within the interpreter, at\nthe cost of some flexibility in the handling of special methods (the\nspecial method *must* be set on the class object itself in order to be\nconsistently invoked by the interpreter).\n',
- 'string-methods': u'\nString Methods\n**************\n\nStrings implement all of the *common* sequence operations, along with\nthe additional methods described below.\n\nStrings also support two styles of string formatting, one providing a\nlarge degree of flexibility and customization (see "str.format()",\n*Format String Syntax* and *Custom String Formatting*) and the other\nbased on C "printf" style formatting that handles a narrower range of\ntypes and is slightly harder to use correctly, but is often faster for\nthe cases it can handle (*printf-style String Formatting*).\n\nThe *Text Processing Services* section of the standard library covers\na number of other modules that provide various text related utilities\n(including regular expression support in the "re" module).\n\nstr.capitalize()\n\n   Return a copy of the string with its first character capitalized\n   and the rest lowercased.\n\nstr.casefold()\n\n   Return a casefolded copy of the string. Casefolded strings may be\n   used for caseless matching.\n\n   Casefolding is similar to lowercasing but more aggressive because\n   it is intended to remove all case distinctions in a string. For\n   example, the German lowercase letter "\'\xdf\'" is equivalent to ""ss"".\n   Since it is already lowercase, "lower()" would do nothing to "\'\xdf\'";\n   "casefold()" converts it to ""ss"".\n\n   The casefolding algorithm is described in section 3.13 of the\n   Unicode Standard.\n\n   New in version 3.3.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is an ASCII space). The\n   original string is returned if *width* is less than or equal to\n   "len(s)".\n\nstr.count(sub[, start[, end]])\n\n   Return the number of non-overlapping occurrences of substring *sub*\n   in the range [*start*, *end*].  Optional arguments *start* and\n   *end* are interpreted as in slice notation.\n\nstr.encode(encoding="utf-8", errors="strict")\n\n   Return an encoded version of the string as a bytes object. Default\n   encoding is "\'utf-8\'". *errors* may be given to set a different\n   error handling scheme. The default for *errors* is "\'strict\'",\n   meaning that encoding errors raise a "UnicodeError". Other possible\n   values are "\'ignore\'", "\'replace\'", "\'xmlcharrefreplace\'",\n   "\'backslashreplace\'" and any other name registered via\n   "codecs.register_error()", see section *Error Handlers*. For a list\n   of possible encodings, see section *Standard Encodings*.\n\n   Changed in version 3.1: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return "True" if the string ends with the specified *suffix*,\n   otherwise return "False".  *suffix* can also be a tuple of suffixes\n   to look for.  With optional *start*, test beginning at that\n   position.  With optional *end*, stop comparing at that position.\n\nstr.expandtabs(tabsize=8)\n\n   Return a copy of the string where all tab characters are replaced\n   by one or more spaces, depending on the current column and the\n   given tab size.  Tab positions occur every *tabsize* characters\n   (default is 8, giving tab positions at columns 0, 8, 16 and so on).\n   To expand the string, the current column is set to zero and the\n   string is examined character by character.  If the character is a\n   tab ("\\t"), one or more space characters are inserted in the result\n   until the current column is equal to the next tab position. (The\n   tab character itself is not copied.)  If the character is a newline\n   ("\\n") or return ("\\r"), it is copied and the current column is\n   reset to zero.  Any other character is copied unchanged and the\n   current column is incremented by one regardless of how the\n   character is represented when printed.\n\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs()\n   \'01      012     0123    01234\'\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs(4)\n   \'01  012 0123    01234\'\n\nstr.find(sub[, start[, end]])\n\n   Return the lowest index in the string where substring *sub* is\n   found within the slice "s[start:end]".  Optional arguments *start*\n   and *end* are interpreted as in slice notation.  Return "-1" if\n   *sub* is not found.\n\n   Note: The "find()" method should be used only if you need to know\n     the position of *sub*.  To check if *sub* is a substring or not,\n     use the "in" operator:\n\n        >>> \'Py\' in \'Python\'\n        True\n\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The string on which this\n   method is called can contain literal text or replacement fields\n   delimited by braces "{}".  Each replacement field contains either\n   the numeric index of a positional argument, or the name of a\n   keyword argument.  Returns a copy of the string where each\n   replacement field is replaced with the string value of the\n   corresponding argument.\n\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\n   \'The sum of 1 + 2 is 3\'\n\n   See *Format String Syntax* for a description of the various\n   formatting options that can be specified in format strings.\n\nstr.format_map(mapping)\n\n   Similar to "str.format(**mapping)", except that "mapping" is used\n   directly and not copied to a "dict".  This is useful if for example\n   "mapping" is a dict subclass:\n\n   >>> class Default(dict):\n   ...     def __missing__(self, key):\n   ...         return key\n   ...\n   >>> \'{name} was born in {country}\'.format_map(Default(name=\'Guido\'))\n   \'Guido was born in country\'\n\n   New in version 3.2.\n\nstr.index(sub[, start[, end]])\n\n   Like "find()", but raise "ValueError" when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.  A character "c"\n   is alphanumeric if one of the following returns "True":\n   "c.isalpha()", "c.isdecimal()", "c.isdigit()", or "c.isnumeric()".\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.  Alphabetic\n   characters are those characters defined in the Unicode character\n   database as "Letter", i.e., those with general category property\n   being one of "Lm", "Lt", "Lu", "Ll", or "Lo".  Note that this is\n   different from the "Alphabetic" property defined in the Unicode\n   Standard.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters are those from general category "Nd". This category\n   includes digit characters, and all characters that can be used to\n   form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.  Digits include decimal\n   characters and digits that need special handling, such as the\n   compatibility superscript digits.  Formally, a digit is a character\n   that has the property value Numeric_Type=Digit or\n   Numeric_Type=Decimal.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\n   Use "keyword.iskeyword()" to test for reserved identifiers such as\n   "def" and "class".\n\nstr.islower()\n\n   Return true if all cased characters [4] in the string are lowercase\n   and there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.  Formally, numeric characters are those with the\n   property value Numeric_Type=Digit, Numeric_Type=Decimal or\n   Numeric_Type=Numeric.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when "repr()" is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to "sys.stdout" or "sys.stderr".)\n\nstr.isspace()\n\n   Return true if there are only whitespace characters in the string\n   and there is at least one character, false otherwise.  Whitespace\n   characters  are those characters defined in the Unicode character\n   database as "Other" or "Separator" and those with bidirectional\n   property being one of "WS", "B", or "S".\n\nstr.istitle()\n\n   Return true if the string is a titlecased string and there is at\n   least one character, for example uppercase characters may only\n   follow uncased characters and lowercase characters only cased ones.\n   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters [4] in the string are uppercase\n   and there is at least one cased character, false otherwise.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  A "TypeError" will be raised if there are\n   any non-string values in *iterable*, including "bytes" objects.\n   The separator between elements is the string providing this method.\n\nstr.ljust(width[, fillchar])\n\n   Return the string left justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is an ASCII\n   space). The original string is returned if *width* is less than or\n   equal to "len(s)".\n\nstr.lower()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to lowercase.\n\n   The lowercasing algorithm used is described in section 3.13 of the\n   Unicode Standard.\n\nstr.lstrip([chars])\n\n   Return a copy of the string with leading characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or "None", the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n      >>> \'   spacious   \'.lstrip()\n      \'spacious   \'\n      >>> \'www.example.com\'.lstrip(\'cmowz.\')\n      \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   "str.translate()".\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or None.\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   None in the result.\n\nstr.partition(sep)\n\n   Split the string at the first occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\n\n   Return a copy of the string with all occurrences of substring *old*\n   replaced by *new*.  If the optional argument *count* is given, only\n   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n   Return the highest index in the string where substring *sub* is\n   found, such that *sub* is contained within "s[start:end]".\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return "-1" on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like "rfind()" but raises "ValueError" when the substring *sub* is\n   not found.\n\nstr.rjust(width[, fillchar])\n\n   Return the string right justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is an ASCII\n   space). The original string is returned if *width* is less than or\n   equal to "len(s)".\n\nstr.rpartition(sep)\n\n   Split the string at the last occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.rsplit(sep=None, maxsplit=-1)\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n   are done, the *rightmost* ones.  If *sep* is not specified or\n   "None", any whitespace string is a separator.  Except for splitting\n   from the right, "rsplit()" behaves like "split()" which is\n   described in detail below.\n\nstr.rstrip([chars])\n\n   Return a copy of the string with trailing characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or "None", the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n      >>> \'   spacious   \'.rstrip()\n      \'   spacious\'\n      >>> \'mississippi\'.rstrip(\'ipz\')\n      \'mississ\'\n\nstr.split(sep=None, maxsplit=-1)\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string.  If *maxsplit* is given, at most *maxsplit*\n   splits are done (thus, the list will have at most "maxsplit+1"\n   elements).  If *maxsplit* is not specified or "-1", then there is\n   no limit on the number of splits (all possible splits are made).\n\n   If *sep* is given, consecutive delimiters are not grouped together\n   and are deemed to delimit empty strings (for example,\n   "\'1,,2\'.split(\',\')" returns "[\'1\', \'\', \'2\']").  The *sep* argument\n   may consist of multiple characters (for example,\n   "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', \'3\']"). Splitting an\n   empty string with a specified separator returns "[\'\']".\n\n   For example:\n\n      >>> \'1,2,3\'.split(\',\')\n      [\'1\', \'2\', \'3\']\n      >>> \'1,2,3\'.split(\',\', maxsplit=1)\n      [\'1\', \'2,3\']\n      >>> \'1,2,,3,\'.split(\',\')\n      [\'1\', \'2\', \'\', \'3\', \'\']\n\n   If *sep* is not specified or is "None", a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no empty strings\n   at the start or end if the string has leading or trailing\n   whitespace.  Consequently, splitting an empty string or a string\n   consisting of just whitespace with a "None" separator returns "[]".\n\n   For example:\n\n      >>> \'1 2 3\'.split()\n      [\'1\', \'2\', \'3\']\n      >>> \'1 2 3\'.split(maxsplit=1)\n      [\'1\', \'2 3\']\n      >>> \'   1   2   3   \'.split()\n      [\'1\', \'2\', \'3\']\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\n   This method splits on the following line boundaries.  In\n   particular, the boundaries are a superset of *universal newlines*.\n\n   +-------------------------+-------------------------------+\n   | Representation          | Description                   |\n   +=========================+===============================+\n   | "\\n"                    | Line Feed                     |\n   +-------------------------+-------------------------------+\n   | "\\r"                    | Carriage Return               |\n   +-------------------------+-------------------------------+\n   | "\\r\\n"                  | Carriage Return + Line Feed   |\n   +-------------------------+-------------------------------+\n   | "\\v" or "\\x0b"          | Line Tabulation               |\n   +-------------------------+-------------------------------+\n   | "\\f" or "\\x0c"          | Form Feed                     |\n   +-------------------------+-------------------------------+\n   | "\\x1c"                  | File Separator                |\n   +-------------------------+-------------------------------+\n   | "\\x1d"                  | Group Separator               |\n   +-------------------------+-------------------------------+\n   | "\\x1e"                  | Record Separator              |\n   +-------------------------+-------------------------------+\n   | "\\x85"                  | Next Line (C1 Control Code)   |\n   +-------------------------+-------------------------------+\n   | "\\u2028"                | Line Separator                |\n   +-------------------------+-------------------------------+\n   | "\\u2029"                | Paragraph Separator           |\n   +-------------------------+-------------------------------+\n\n   Changed in version 3.2: "\\v" and "\\f" added to list of line\n   boundaries.\n\n   For example:\n\n      >>> \'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()\n      [\'ab c\', \'\', \'de fg\', \'kl\']\n      >>> \'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines(keepends=True)\n      [\'ab c\\n\', \'\\n\', \'de fg\\r\', \'kl\\r\\n\']\n\n   Unlike "split()" when a delimiter string *sep* is given, this\n   method returns an empty list for the empty string, and a terminal\n   line break does not result in an extra line:\n\n      >>> "".splitlines()\n      []\n      >>> "One line\\n".splitlines()\n      [\'One line\']\n\n   For comparison, "split(\'\\n\')" gives:\n\n      >>> \'\'.split(\'\\n\')\n      [\'\']\n      >>> \'Two lines\\n\'.split(\'\\n\')\n      [\'Two lines\', \'\']\n\nstr.startswith(prefix[, start[, end]])\n\n   Return "True" if string starts with the *prefix*, otherwise return\n   "False". *prefix* can also be a tuple of prefixes to look for.\n   With optional *start*, test string beginning at that position.\n   With optional *end*, stop comparing string at that position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or "None", the *chars*\n   argument defaults to removing whitespace. The *chars* argument is\n   not a prefix or suffix; rather, all combinations of its values are\n   stripped:\n\n      >>> \'   spacious   \'.strip()\n      \'spacious\'\n      >>> \'www.example.com\'.strip(\'cmowz.\')\n      \'example\'\n\n   The outermost leading and trailing *chars* argument values are\n   stripped from the string. Characters are removed from the leading\n   end until reaching a string character that is not contained in the\n   set of characters in *chars*. A similar action takes place on the\n   trailing end. For example:\n\n      >>> comment_string = \'#....... Section 3.2.1 Issue #32 .......\'\n      >>> comment_string.strip(\'.#! \')\n      \'Section 3.2.1 Issue #32\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa. Note that it is not necessarily true that\n   "s.swapcase().swapcase() == s".\n\nstr.title()\n\n   Return a titlecased version of the string where words start with an\n   uppercase character and the remaining characters are lowercase.\n\n   For example:\n\n      >>> \'Hello world\'.title()\n      \'Hello World\'\n\n   The algorithm uses a simple language-independent definition of a\n   word as groups of consecutive letters.  The definition works in\n   many contexts but it means that apostrophes in contractions and\n   possessives form word boundaries, which may not be the desired\n   result:\n\n      >>> "they\'re bill\'s friends from the UK".title()\n      "They\'Re Bill\'S Friends From The Uk"\n\n   A workaround for apostrophes can be constructed using regular\n   expressions:\n\n      >>> import re\n      >>> def titlecase(s):\n      ...     return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n      ...                   lambda mo: mo.group(0)[0].upper() +\n      ...                              mo.group(0)[1:].lower(),\n      ...                   s)\n      ...\n      >>> titlecase("they\'re bill\'s friends.")\n      "They\'re Bill\'s Friends."\n\nstr.translate(table)\n\n   Return a copy of the string in which each character has been mapped\n   through the given translation table.  The table must be an object\n   that implements indexing via "__getitem__()", typically a *mapping*\n   or *sequence*.  When indexed by a Unicode ordinal (an integer), the\n   table object can do any of the following: return a Unicode ordinal\n   or a string, to map the character to one or more other characters;\n   return "None", to delete the character from the return string; or\n   raise a "LookupError" exception, to map the character to itself.\n\n   You can use "str.maketrans()" to create a translation map from\n   character-to-character mappings in different formats.\n\n   See also the "codecs" module for a more flexible approach to custom\n   character mappings.\n\nstr.upper()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to uppercase.  Note that "str.upper().isupper()" might be\n   "False" if "s" contains uncased characters or if the Unicode\n   category of the resulting character(s) is not "Lu" (Letter,\n   uppercase), but e.g. "Lt" (Letter, titlecase).\n\n   The uppercasing algorithm used is described in section 3.13 of the\n   Unicode Standard.\n\nstr.zfill(width)\n\n   Return a copy of the string left filled with ASCII "\'0\'" digits to\n   make a string of length *width*. A leading sign prefix\n   ("\'+\'"/"\'-\'") is handled by inserting the padding *after* the sign\n   character rather than before. The original string is returned if\n   *width* is less than or equal to "len(s)".\n\n   For example:\n\n      >>> "42".zfill(5)\n      \'00042\'\n      >>> "-42".zfill(5)\n      \'-0042\'\n',
+ 'specialattrs': u'\nSpecial Attributes\n******************\n\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant.  Some of these are not reported\nby the "dir()" built-in function.\n\nobject.__dict__\n\n   A dictionary or other mapping object used to store an object\'s\n   (writable) attributes.\n\ninstance.__class__\n\n   The class to which a class instance belongs.\n\nclass.__bases__\n\n   The tuple of base classes of a class object.\n\ndefinition.__name__\n\n   The name of the class, function, method, descriptor, or generator\n   instance.\n\ndefinition.__qualname__\n\n   The *qualified name* of the class, function, method, descriptor, or\n   generator instance.\n\n   New in version 3.3.\n\nclass.__mro__\n\n   This attribute is a tuple of classes that are considered when\n   looking for base classes during method resolution.\n\nclass.mro()\n\n   This method can be overridden by a metaclass to customize the\n   method resolution order for its instances.  It is called at class\n   instantiation, and its result is stored in "__mro__".\n\nclass.__subclasses__()\n\n   Each class keeps a list of weak references to its immediate\n   subclasses.  This method returns a list of all those references\n   still alive. Example:\n\n      >>> int.__subclasses__()\n      [<class \'bool\'>]\n\n-[ Footnotes ]-\n\n[1] Additional information on these special methods may be found\n    in the Python Reference Manual (*Basic customization*).\n\n[2] As a consequence, the list "[1, 2]" is considered equal to\n    "[1.0, 2.0]", and similarly for tuples.\n\n[3] They must have since the parser can\'t tell the type of the\n    operands.\n\n[4] Cased characters are those with general category property\n    being one of "Lu" (Letter, uppercase), "Ll" (Letter, lowercase),\n    or "Lt" (Letter, titlecase).\n\n[5] To format only a tuple you should therefore provide a\n    singleton tuple whose only element is the tuple to be formatted.\n',
+ 'specialnames': u'\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators.  For instance, if a class defines\na method named "__getitem__()", and "x" is an instance of this class,\nthen "x[i]" is roughly equivalent to "type(x).__getitem__(x, i)".\nExcept where mentioned, attempts to execute an operation raise an\nexception when no appropriate method is defined (typically\n"AttributeError" or "TypeError").\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled.  For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense.  (One example of this is the\n"NodeList" interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n   Called to create a new instance of class *cls*.  "__new__()" is a\n   static method (special-cased so you need not declare it as such)\n   that takes the class of which an instance was requested as its\n   first argument.  The remaining arguments are those passed to the\n   object constructor expression (the call to the class).  The return\n   value of "__new__()" should be the new object instance (usually an\n   instance of *cls*).\n\n   Typical implementations create a new instance of the class by\n   invoking the superclass\'s "__new__()" method using\n   "super(currentclass, cls).__new__(cls[, ...])" with appropriate\n   arguments and then modifying the newly-created instance as\n   necessary before returning it.\n\n   If "__new__()" returns an instance of *cls*, then the new\n   instance\'s "__init__()" method will be invoked like\n   "__init__(self[, ...])", where *self* is the new instance and the\n   remaining arguments are the same as were passed to "__new__()".\n\n   If "__new__()" does not return an instance of *cls*, then the new\n   instance\'s "__init__()" method will not be invoked.\n\n   "__new__()" is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called after the instance has been created (by "__new__()"), but\n   before it is returned to the caller.  The arguments are those\n   passed to the class constructor expression.  If a base class has an\n   "__init__()" method, the derived class\'s "__init__()" method, if\n   any, must explicitly call it to ensure proper initialization of the\n   base class part of the instance; for example:\n   "BaseClass.__init__(self, [args...])".\n\n   Because "__new__()" and "__init__()" work together in constructing\n   objects ("__new__()" to create it, and "__init__()" to customize\n   it), no non-"None" value may be returned by "__init__()"; doing so\n   will cause a "TypeError" to be raised at runtime.\n\nobject.__del__(self)\n\n   Called when the instance is about to be destroyed.  This is also\n   called a destructor.  If a base class has a "__del__()" method, the\n   derived class\'s "__del__()" method, if any, must explicitly call it\n   to ensure proper deletion of the base class part of the instance.\n   Note that it is possible (though not recommended!) for the\n   "__del__()" method to postpone destruction of the instance by\n   creating a new reference to it.  It may then be called at a later\n   time when this new reference is deleted.  It is not guaranteed that\n   "__del__()" methods are called for objects that still exist when\n   the interpreter exits.\n\n   Note: "del x" doesn\'t directly call "x.__del__()" --- the former\n     decrements the reference count for "x" by one, and the latter is\n     only called when "x"\'s reference count reaches zero.  Some common\n     situations that may prevent the reference count of an object from\n     going to zero include: circular references between objects (e.g.,\n     a doubly-linked list or a tree data structure with parent and\n     child pointers); a reference to the object on the stack frame of\n     a function that caught an exception (the traceback stored in\n     "sys.exc_info()[2]" keeps the stack frame alive); or a reference\n     to the object on the stack frame that raised an unhandled\n     exception in interactive mode (the traceback stored in\n     "sys.last_traceback" keeps the stack frame alive).  The first\n     situation can only be remedied by explicitly breaking the cycles;\n     the second can be resolved by freeing the reference to the\n     traceback object when it is no longer useful, and the third can\n     be resolved by storing "None" in "sys.last_traceback". Circular\n     references which are garbage are detected and cleaned up when the\n     cyclic garbage collector is enabled (it\'s on by default). Refer\n     to the documentation for the "gc" module for more information\n     about this topic.\n\n   Warning: Due to the precarious circumstances under which\n     "__del__()" methods are invoked, exceptions that occur during\n     their execution are ignored, and a warning is printed to\n     "sys.stderr" instead. Also, when "__del__()" is invoked in\n     response to a module being deleted (e.g., when execution of the\n     program is done), other globals referenced by the "__del__()"\n     method may already have been deleted or in the process of being\n     torn down (e.g. the import machinery shutting down).  For this\n     reason, "__del__()" methods should do the absolute minimum needed\n     to maintain external invariants.  Starting with version 1.5,\n     Python guarantees that globals whose name begins with a single\n     underscore are deleted from their module before other globals are\n     deleted; if no other references to such globals exist, this may\n     help in assuring that imported modules are still available at the\n     time when the "__del__()" method is called.\n\nobject.__repr__(self)\n\n   Called by the "repr()" built-in function to compute the "official"\n   string representation of an object.  If at all possible, this\n   should look like a valid Python expression that could be used to\n   recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   "<...some useful description...>" should be returned. The return\n   value must be a string object. If a class defines "__repr__()" but\n   not "__str__()", then "__repr__()" is also used when an "informal"\n   string representation of instances of that class is required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by "str(object)" and the built-in functions "format()" and\n   "print()" to compute the "informal" or nicely printable string\n   representation of an object.  The return value must be a *string*\n   object.\n\n   This method differs from "object.__repr__()" in that there is no\n   expectation that "__str__()" return a valid Python expression: a\n   more convenient or concise representation can be used.\n\n   The default implementation defined by the built-in type "object"\n   calls "object.__repr__()".\n\nobject.__bytes__(self)\n\n   Called by "bytes()" to compute a byte-string representation of an\n   object. This should return a "bytes" object.\n\nobject.__format__(self, format_spec)\n\n   Called by the "format()" built-in function (and by extension, the\n   "str.format()" method of class "str") to produce a "formatted"\n   string representation of an object. The "format_spec" argument is a\n   string that contains a description of the formatting options\n   desired. The interpretation of the "format_spec" argument is up to\n   the type implementing "__format__()", however most classes will\n   either delegate formatting to one of the built-in types, or use a\n   similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\n   Changed in version 3.4: The __format__ method of "object" itself\n   raises a "TypeError" if passed any non-empty string.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: "x<y" calls "x.__lt__(y)", "x<=y" calls "x.__le__(y)",\n   "x==y" calls "x.__eq__(y)", "x!=y" calls "x.__ne__(y)", "x>y" calls\n   "x.__gt__(y)", and "x>=y" calls "x.__ge__(y)".\n\n   A rich comparison method may return the singleton "NotImplemented"\n   if it does not implement the operation for a given pair of\n   arguments. By convention, "False" and "True" are returned for a\n   successful comparison. However, these methods can return any value,\n   so if the comparison operator is used in a Boolean context (e.g.,\n   in the condition of an "if" statement), Python will call "bool()"\n   on the value to determine if the result is true or false.\n\n   By default, "__ne__()" delegates to "__eq__()" and inverts the\n   result unless it is "NotImplemented".  There are no other implied\n   relationships among the comparison operators, for example, the\n   truth of "(x<y or x==y)" does not imply "x<=y". To automatically\n   generate ordering operations from a single root operation, see\n   "functools.total_ordering()".\n\n   See the paragraph on "__hash__()" for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\n\n   There are no swapped-argument versions of these methods (to be used\n   when the left argument does not support the operation but the right\n   argument does); rather, "__lt__()" and "__gt__()" are each other\'s\n   reflection, "__le__()" and "__ge__()" are each other\'s reflection,\n   and "__eq__()" and "__ne__()" are their own reflection. If the\n   operands are of different types, and right operand\'s type is a\n   direct or indirect subclass of the left operand\'s type, the\n   reflected method of the right operand has priority, otherwise the\n   left operand\'s method has priority.  Virtual subclassing is not\n   considered.\n\nobject.__hash__(self)\n\n   Called by built-in function "hash()" and for operations on members\n   of hashed collections including "set", "frozenset", and "dict".\n   "__hash__()" should return an integer. The only required property\n   is that objects which compare equal have the same hash value; it is\n   advised to mix together the hash values of the components of the\n   object that also play a part in comparison of objects by packing\n   them into a tuple and hashing the tuple. Example:\n\n      def __hash__(self):\n          return hash((self.name, self.nick, self.color))\n\n   Note: "hash()" truncates the value returned from an object\'s\n     custom "__hash__()" method to the size of a "Py_ssize_t".  This\n     is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit\n     builds. If an object\'s   "__hash__()" must interoperate on builds\n     of different bit sizes, be sure to check the width on all\n     supported builds.  An easy way to do this is with "python -c\n     "import sys; print(sys.hash_info.width)"".\n\n   If a class does not define an "__eq__()" method it should not\n   define a "__hash__()" operation either; if it defines "__eq__()"\n   but not "__hash__()", its instances will not be usable as items in\n   hashable collections.  If a class defines mutable objects and\n   implements an "__eq__()" method, it should not implement\n   "__hash__()", since the implementation of hashable collections\n   requires that a key\'s hash value is immutable (if the object\'s hash\n   value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have "__eq__()" and "__hash__()" methods by\n   default; with them, all objects compare unequal (except with\n   themselves) and "x.__hash__()" returns an appropriate value such\n   that "x == y" implies both that "x is y" and "hash(x) == hash(y)".\n\n   A class that overrides "__eq__()" and does not define "__hash__()"\n   will have its "__hash__()" implicitly set to "None".  When the\n   "__hash__()" method of a class is "None", instances of the class\n   will raise an appropriate "TypeError" when a program attempts to\n   retrieve their hash value, and will also be correctly identified as\n   unhashable when checking "isinstance(obj, collections.Hashable)".\n\n   If a class that overrides "__eq__()" needs to retain the\n   implementation of "__hash__()" from a parent class, the interpreter\n   must be told this explicitly by setting "__hash__ =\n   <ParentClass>.__hash__".\n\n   If a class that does not override "__eq__()" wishes to suppress\n   hash support, it should include "__hash__ = None" in the class\n   definition. A class which defines its own "__hash__()" that\n   explicitly raises a "TypeError" would be incorrectly identified as\n   hashable by an "isinstance(obj, collections.Hashable)" call.\n\n   Note: By default, the "__hash__()" values of str, bytes and\n     datetime objects are "salted" with an unpredictable random value.\n     Although they remain constant within an individual Python\n     process, they are not predictable between repeated invocations of\n     Python.This is intended to provide protection against a denial-\n     of-service caused by carefully-chosen inputs that exploit the\n     worst case performance of a dict insertion, O(n^2) complexity.\n     See http://www.ocert.org/advisories/ocert-2011-003.html for\n     details.Changing hash values affects the iteration order of\n     dicts, sets and other mappings.  Python has never made guarantees\n     about this ordering (and it typically varies between 32-bit and\n     64-bit builds).See also "PYTHONHASHSEED".\n\n   Changed in version 3.3: Hash randomization is enabled by default.\n\nobject.__bool__(self)\n\n   Called to implement truth value testing and the built-in operation\n   "bool()"; should return "False" or "True".  When this method is not\n   defined, "__len__()" is called, if it is defined, and the object is\n   considered true if its result is nonzero.  If a class defines\n   neither "__len__()" nor "__bool__()", all its instances are\n   considered true.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of "x.name") for\nclass instances.\n\nobject.__getattr__(self, name)\n\n   Called when an attribute lookup has not found the attribute in the\n   usual places (i.e. it is not an instance attribute nor is it found\n   in the class tree for "self").  "name" is the attribute name. This\n   method should return the (computed) attribute value or raise an\n   "AttributeError" exception.\n\n   Note that if the attribute is found through the normal mechanism,\n   "__getattr__()" is not called.  (This is an intentional asymmetry\n   between "__getattr__()" and "__setattr__()".) This is done both for\n   efficiency reasons and because otherwise "__getattr__()" would have\n   no way to access other attributes of the instance.  Note that at\n   least for instance variables, you can fake total control by not\n   inserting any values in the instance attribute dictionary (but\n   instead inserting them in another object).  See the\n   "__getattribute__()" method below for a way to actually get total\n   control over attribute access.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines "__getattr__()",\n   the latter will not be called unless "__getattribute__()" either\n   calls it explicitly or raises an "AttributeError". This method\n   should return the (computed) attribute value or raise an\n   "AttributeError" exception. In order to avoid infinite recursion in\n   this method, its implementation should always call the base class\n   method with the same name to access any attributes it needs, for\n   example, "object.__getattribute__(self, name)".\n\n   Note: This method may still be bypassed when looking up special\n     methods as the result of implicit invocation via language syntax\n     or built-in functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n   Called when an attribute assignment is attempted.  This is called\n   instead of the normal mechanism (i.e. store the value in the\n   instance dictionary). *name* is the attribute name, *value* is the\n   value to be assigned to it.\n\n   If "__setattr__()" wants to assign to an instance attribute, it\n   should call the base class method with the same name, for example,\n   "object.__setattr__(self, name, value)".\n\nobject.__delattr__(self, name)\n\n   Like "__setattr__()" but for attribute deletion instead of\n   assignment.  This should only be implemented if "del obj.name" is\n   meaningful for the object.\n\nobject.__dir__(self)\n\n   Called when "dir()" is called on the object. A sequence must be\n   returned. "dir()" converts the returned sequence to a list and\n   sorts it.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in an\n*owner* class (the descriptor must be in either the owner\'s class\ndictionary or in the class dictionary for one of its parents).  In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' "__dict__".\n\nobject.__get__(self, instance, owner)\n\n   Called to get the attribute of the owner class (class attribute\n   access) or of an instance of that class (instance attribute\n   access). *owner* is always the owner class, while *instance* is the\n   instance that the attribute was accessed through, or "None" when\n   the attribute is accessed through the *owner*.  This method should\n   return the (computed) attribute value or raise an "AttributeError"\n   exception.\n\nobject.__set__(self, instance, value)\n\n   Called to set the attribute on an instance *instance* of the owner\n   class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n   Called to delete the attribute on an instance *instance* of the\n   owner class.\n\nThe attribute "__objclass__" is interpreted by the "inspect" module as\nspecifying the class where this object was defined (setting this\nappropriately can assist in runtime introspection of dynamic class\nattributes). For callables, it may indicate that an instance of the\ngiven type (or a subclass) is expected or required as the first\npositional argument (for example, CPython sets this attribute for\nunbound methods that are implemented in C).\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol:  "__get__()", "__set__()", and\n"__delete__()". If any of those methods are defined for an object, it\nis said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, "a.x" has a\nlookup chain starting with "a.__dict__[\'x\']", then\n"type(a).__dict__[\'x\']", and continuing through the base classes of\n"type(a)" excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead.  Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, "a.x". How\nthe arguments are assembled depends on "a":\n\nDirect Call\n   The simplest and least common call is when user code directly\n   invokes a descriptor method:    "x.__get__(a)".\n\nInstance Binding\n   If binding to an object instance, "a.x" is transformed into the\n   call: "type(a).__dict__[\'x\'].__get__(a, type(a))".\n\nClass Binding\n   If binding to a class, "A.x" is transformed into the call:\n   "A.__dict__[\'x\'].__get__(None, A)".\n\nSuper Binding\n   If "a" is an instance of "super", then the binding "super(B,\n   obj).m()" searches "obj.__class__.__mro__" for the base class "A"\n   immediately preceding "B" and then invokes the descriptor with the\n   call: "A.__dict__[\'m\'].__get__(obj, obj.__class__)".\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined.  A descriptor can define\nany combination of "__get__()", "__set__()" and "__delete__()".  If it\ndoes not define "__get__()", then accessing the attribute will return\nthe descriptor object itself unless there is a value in the object\'s\ninstance dictionary.  If the descriptor defines "__set__()" and/or\n"__delete__()", it is a data descriptor; if it defines neither, it is\na non-data descriptor.  Normally, data descriptors define both\n"__get__()" and "__set__()", while non-data descriptors have just the\n"__get__()" method.  Data descriptors with "__set__()" and "__get__()"\ndefined always override a redefinition in an instance dictionary.  In\ncontrast, non-data descriptors can be overridden by instances.\n\nPython methods (including "staticmethod()" and "classmethod()") are\nimplemented as non-data descriptors.  Accordingly, instances can\nredefine and override methods.  This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe "property()" function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of classes have a dictionary for attribute\nstorage.  This wastes space for objects having very few instance\nvariables.  The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable.  Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n   This class variable can be assigned a string, iterable, or sequence\n   of strings with variable names used by instances.  *__slots__*\n   reserves space for the declared variables and prevents the\n   automatic creation of *__dict__* and *__weakref__* for each\n   instance.\n\n\nNotes on using *__slots__*\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n  attribute of that class will always be accessible, so a *__slots__*\n  definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n  variables not listed in the *__slots__* definition.  Attempts to\n  assign to an unlisted variable name raises "AttributeError". If\n  dynamic assignment of new variables is desired, then add\n  "\'__dict__\'" to the sequence of strings in the *__slots__*\n  declaration.\n\n* Without a *__weakref__* variable for each instance, classes\n  defining *__slots__* do not support weak references to its\n  instances. If weak reference support is needed, then add\n  "\'__weakref__\'" to the sequence of strings in the *__slots__*\n  declaration.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (*Implementing Descriptors*) for each variable name.  As\n  a result, class attributes cannot be used to set default values for\n  instance variables defined by *__slots__*; otherwise, the class\n  attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n  where it is defined.  As a result, subclasses will have a *__dict__*\n  unless they also define *__slots__* (which must only contain names\n  of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the\n  instance variable defined by the base class slot is inaccessible\n  (except by retrieving its descriptor directly from the base class).\n  This renders the meaning of the program undefined.  In the future, a\n  check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n  "variable-length" built-in types such as "int", "bytes" and "tuple".\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings\n  may also be used; however, in the future, special meaning may be\n  assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n  *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, classes are constructed using "type()". The class body is\nexecuted in a new namespace and the class name is bound locally to the\nresult of "type(name, bases, namespace)".\n\nThe class creation process can be customized by passing the\n"metaclass" keyword argument in the class definition line, or by\ninheriting from an existing class that included such an argument. In\nthe following example, both "MyClass" and "MySubclass" are instances\nof "Meta":\n\n   class Meta(type):\n       pass\n\n   class MyClass(metaclass=Meta):\n       pass\n\n   class MySubclass(MyClass):\n       pass\n\nAny other keyword arguments that are specified in the class definition\nare passed through to all metaclass operations described below.\n\nWhen a class definition is executed, the following steps occur:\n\n* the appropriate metaclass is determined\n\n* the class namespace is prepared\n\n* the class body is executed\n\n* the class object is created\n\n\nDetermining the appropriate metaclass\n-------------------------------------\n\nThe appropriate metaclass for a class definition is determined as\nfollows:\n\n* if no bases and no explicit metaclass are given, then "type()" is\n  used\n\n* if an explicit metaclass is given and it is *not* an instance of\n  "type()", then it is used directly as the metaclass\n\n* if an instance of "type()" is given as the explicit metaclass, or\n  bases are defined, then the most derived metaclass is used\n\nThe most derived metaclass is selected from the explicitly specified\nmetaclass (if any) and the metaclasses (i.e. "type(cls)") of all\nspecified base classes. The most derived metaclass is one which is a\nsubtype of *all* of these candidate metaclasses. If none of the\ncandidate metaclasses meets that criterion, then the class definition\nwill fail with "TypeError".\n\n\nPreparing the class namespace\n-----------------------------\n\nOnce the appropriate metaclass has been identified, then the class\nnamespace is prepared. If the metaclass has a "__prepare__" attribute,\nit is called as "namespace = metaclass.__prepare__(name, bases,\n**kwds)" (where the additional keyword arguments, if any, come from\nthe class definition).\n\nIf the metaclass has no "__prepare__" attribute, then the class\nnamespace is initialised as an empty "dict()" instance.\n\nSee also: **PEP 3115** - Metaclasses in Python 3000\n\n     Introduced the "__prepare__" namespace hook\n\n\nExecuting the class body\n------------------------\n\nThe class body is executed (approximately) as "exec(body, globals(),\nnamespace)". The key difference from a normal call to "exec()" is that\nlexical scoping allows the class body (including any methods) to\nreference names from the current and outer scopes when the class\ndefinition occurs inside a function.\n\nHowever, even when the class definition occurs inside the function,\nmethods defined inside the class still cannot see names defined at the\nclass scope. Class variables must be accessed through the first\nparameter of instance or class methods, and cannot be accessed at all\nfrom static methods.\n\n\nCreating the class object\n-------------------------\n\nOnce the class namespace has been populated by executing the class\nbody, the class object is created by calling "metaclass(name, bases,\nnamespace, **kwds)" (the additional keywords passed here are the same\nas those passed to "__prepare__").\n\nThis class object is the one that will be referenced by the zero-\nargument form of "super()". "__class__" is an implicit closure\nreference created by the compiler if any methods in a class body refer\nto either "__class__" or "super". This allows the zero argument form\nof "super()" to correctly identify the class being defined based on\nlexical scoping, while the class or instance that was used to make the\ncurrent call is identified based on the first argument passed to the\nmethod.\n\nAfter the class object is created, it is passed to the class\ndecorators included in the class definition (if any) and the resulting\nobject is bound in the local namespace as the defined class.\n\nWhen a new class is created by "type.__new__", the object provided as\nthe namespace parameter is copied to a standard Python dictionary and\nthe original object is discarded. The new copy becomes the "__dict__"\nattribute of the class object.\n\nSee also: **PEP 3135** - New super\n\n     Describes the implicit "__class__" closure reference\n\n\nMetaclass example\n-----------------\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored include logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\nHere is an example of a metaclass that uses an\n"collections.OrderedDict" to remember the order that class variables\nare defined:\n\n   class OrderedClass(type):\n\n       @classmethod\n       def __prepare__(metacls, name, bases, **kwds):\n           return collections.OrderedDict()\n\n       def __new__(cls, name, bases, namespace, **kwds):\n           result = type.__new__(cls, name, bases, dict(namespace))\n           result.members = tuple(namespace)\n           return result\n\n   class A(metaclass=OrderedClass):\n       def one(self): pass\n       def two(self): pass\n       def three(self): pass\n       def four(self): pass\n\n   >>> A.members\n   (\'__module__\', \'one\', \'two\', \'three\', \'four\')\n\nWhen the class definition for *A* gets executed, the process begins\nwith calling the metaclass\'s "__prepare__()" method which returns an\nempty "collections.OrderedDict".  That mapping records the methods and\nattributes of *A* as they are defined within the body of the class\nstatement. Once those definitions are executed, the ordered dictionary\nis fully populated and the metaclass\'s "__new__()" method gets\ninvoked.  That method builds the new type and it saves the ordered\ndictionary keys in an attribute called "members".\n\n\nCustomizing instance and subclass checks\n========================================\n\nThe following methods are used to override the default behavior of the\n"isinstance()" and "issubclass()" built-in functions.\n\nIn particular, the metaclass "abc.ABCMeta" implements these methods in\norder to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\n   Return true if *instance* should be considered a (direct or\n   indirect) instance of *class*. If defined, called to implement\n   "isinstance(instance, class)".\n\nclass.__subclasscheck__(self, subclass)\n\n   Return true if *subclass* should be considered a (direct or\n   indirect) subclass of *class*.  If defined, called to implement\n   "issubclass(subclass, class)".\n\nNote that these methods are looked up on the type (metaclass) of a\nclass.  They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also: **PEP 3119** - Introducing Abstract Base Classes\n\n     Includes the specification for customizing "isinstance()" and\n     "issubclass()" behavior through "__instancecheck__()" and\n     "__subclasscheck__()", with motivation for this functionality in\n     the context of adding Abstract Base Classes (see the "abc"\n     module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n   Called when the instance is "called" as a function; if this method\n   is defined, "x(arg1, arg2, ...)" is a shorthand for\n   "x.__call__(arg1, arg2, ...)".\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well.  The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which "0 <= k < N" where\n*N* is the length of the sequence, or slice objects, which define a\nrange of items.  It is also recommended that mappings provide the\nmethods "keys()", "values()", "items()", "get()", "clear()",\n"setdefault()", "pop()", "popitem()", "copy()", and "update()"\nbehaving similar to those for Python\'s standard dictionary objects.\nThe "collections" module provides a "MutableMapping" abstract base\nclass to help create those methods from a base set of "__getitem__()",\n"__setitem__()", "__delitem__()", and "keys()". Mutable sequences\nshould provide methods "append()", "count()", "index()", "extend()",\n"insert()", "pop()", "remove()", "reverse()" and "sort()", like Python\nstandard list objects.  Finally, sequence types should implement\naddition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods "__add__()", "__radd__()",\n"__iadd__()", "__mul__()", "__rmul__()" and "__imul__()" described\nbelow; they should not define other numerical operators.  It is\nrecommended that both mappings and sequences implement the\n"__contains__()" method to allow efficient use of the "in" operator;\nfor mappings, "in" should search the mapping\'s keys; for sequences, it\nshould search through the values.  It is further recommended that both\nmappings and sequences implement the "__iter__()" method to allow\nefficient iteration through the container; for mappings, "__iter__()"\nshould be the same as "keys()"; for sequences, it should iterate\nthrough the values.\n\nobject.__len__(self)\n\n   Called to implement the built-in function "len()".  Should return\n   the length of the object, an integer ">=" 0.  Also, an object that\n   doesn\'t define a "__bool__()" method and whose "__len__()" method\n   returns zero is considered to be false in a Boolean context.\n\nobject.__length_hint__(self)\n\n   Called to implement "operator.length_hint()". Should return an\n   estimated length for the object (which may be greater or less than\n   the actual length). The length must be an integer ">=" 0. This\n   method is purely an optimization and is never required for\n   correctness.\n\n   New in version 3.4.\n\nNote: Slicing is done exclusively with the following three methods.\n  A call like\n\n     a[1:2] = b\n\n  is translated to\n\n     a[slice(1, 2, None)] = b\n\n  and so forth.  Missing slice items are always filled in with "None".\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of "self[key]". For sequence types,\n   the accepted keys should be integers and slice objects.  Note that\n   the special interpretation of negative indexes (if the class wishes\n   to emulate a sequence type) is up to the "__getitem__()" method. If\n   *key* is of an inappropriate type, "TypeError" may be raised; if of\n   a value outside the set of indexes for the sequence (after any\n   special interpretation of negative values), "IndexError" should be\n   raised. For mapping types, if *key* is missing (not in the\n   container), "KeyError" should be raised.\n\n   Note: "for" loops expect that an "IndexError" will be raised for\n     illegal indexes to allow proper detection of the end of the\n     sequence.\n\nobject.__missing__(self, key)\n\n   Called by "dict"."__getitem__()" to implement "self[key]" for dict\n   subclasses when key is not in the dictionary.\n\nobject.__setitem__(self, key, value)\n\n   Called to implement assignment to "self[key]".  Same note as for\n   "__getitem__()".  This should only be implemented for mappings if\n   the objects support changes to the values for keys, or if new keys\n   can be added, or for sequences if elements can be replaced.  The\n   same exceptions should be raised for improper *key* values as for\n   the "__getitem__()" method.\n\nobject.__delitem__(self, key)\n\n   Called to implement deletion of "self[key]".  Same note as for\n   "__getitem__()".  This should only be implemented for mappings if\n   the objects support removal of keys, or for sequences if elements\n   can be removed from the sequence.  The same exceptions should be\n   raised for improper *key* values as for the "__getitem__()" method.\n\nobject.__iter__(self)\n\n   This method is called when an iterator is required for a container.\n   This method should return a new iterator object that can iterate\n   over all the objects in the container.  For mappings, it should\n   iterate over the keys of the container.\n\n   Iterator objects also need to implement this method; they are\n   required to return themselves.  For more information on iterator\n   objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n   Called (if present) by the "reversed()" built-in to implement\n   reverse iteration.  It should return a new iterator object that\n   iterates over all the objects in the container in reverse order.\n\n   If the "__reversed__()" method is not provided, the "reversed()"\n   built-in will fall back to using the sequence protocol ("__len__()"\n   and "__getitem__()").  Objects that support the sequence protocol\n   should only provide "__reversed__()" if they can provide an\n   implementation that is more efficient than the one provided by\n   "reversed()".\n\nThe membership test operators ("in" and "not in") are normally\nimplemented as an iteration through a sequence.  However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n   Called to implement membership test operators.  Should return true\n   if *item* is in *self*, false otherwise.  For mapping objects, this\n   should consider the keys of the mapping rather than the values or\n   the key-item pairs.\n\n   For objects that don\'t define "__contains__()", the membership test\n   first tries iteration via "__iter__()", then the old sequence\n   iteration protocol via "__getitem__()", see *this section in the\n   language reference*.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__matmul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",\n   "pow()", "**", "<<", ">>", "&", "^", "|").  For instance, to\n   evaluate the expression "x + y", where *x* is an instance of a\n   class that has an "__add__()" method, "x.__add__(y)" is called.\n   The "__divmod__()" method should be the equivalent to using\n   "__floordiv__()" and "__mod__()"; it should not be related to\n   "__truediv__()".  Note that "__pow__()" should be defined to accept\n   an optional third argument if the ternary version of the built-in\n   "pow()" function is to be supported.\n\n   If one of those methods does not support the operation with the\n   supplied arguments, it should return "NotImplemented".\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rmatmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",\n   "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)\n   operands.  These functions are only called if the left operand does\n   not support the corresponding operation and the operands are of\n   different types. [2] For instance, to evaluate the expression "x -\n   y", where *y* is an instance of a class that has an "__rsub__()"\n   method, "y.__rsub__(x)" is called if "x.__sub__(y)" returns\n   *NotImplemented*.\n\n   Note that ternary "pow()" will not try calling "__rpow__()" (the\n   coercion rules would become too complicated).\n\n   Note: If the right operand\'s type is a subclass of the left\n     operand\'s type and that subclass provides the reflected method\n     for the operation, this method will be called before the left\n     operand\'s non-reflected method.  This behavior allows subclasses\n     to override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__imatmul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n   These methods are called to implement the augmented arithmetic\n   assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",\n   "<<=", ">>=", "&=", "^=", "|=").  These methods should attempt to\n   do the operation in-place (modifying *self*) and return the result\n   (which could be, but does not have to be, *self*).  If a specific\n   method is not defined, the augmented assignment falls back to the\n   normal methods.  For instance, if *x* is an instance of a class\n   with an "__iadd__()" method, "x += y" is equivalent to "x =\n   x.__iadd__(y)" . Otherwise, "x.__add__(y)" and "y.__radd__(x)" are\n   considered, as with the evaluation of "x + y". In certain\n   situations, augmented assignment can result in unexpected errors\n   (see *Why does a_tuple[i] += [\'item\'] raise an exception when the\n   addition works?*), but this behavior is in fact part of the data\n   model.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n   Called to implement the unary arithmetic operations ("-", "+",\n   "abs()" and "~").\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n   Called to implement the built-in functions "complex()", "int()",\n   "float()" and "round()".  Should return a value of the appropriate\n   type.\n\nobject.__index__(self)\n\n   Called to implement "operator.index()", and whenever Python needs\n   to losslessly convert the numeric object to an integer object (such\n   as in slicing, or in the built-in "bin()", "hex()" and "oct()"\n   functions). Presence of this method indicates that the numeric\n   object is an integer type.  Must return an integer.\n\n   Note: In order to have a coherent integer type class, when\n     "__index__()" is defined "__int__()" should also be defined, and\n     both should return the same value.\n\n\nWith Statement Context Managers\n===============================\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a "with" statement. The context manager\nhandles the entry into, and the exit from, the desired runtime context\nfor the execution of the block of code.  Context managers are normally\ninvoked using the "with" statement (described in section *The with\nstatement*), but can also be used by directly invoking their methods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n   Enter the runtime context related to this object. The "with"\n   statement will bind this method\'s return value to the target(s)\n   specified in the "as" clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n   Exit the runtime context related to this object. The parameters\n   describe the exception that caused the context to be exited. If the\n   context was exited without an exception, all three arguments will\n   be "None".\n\n   If an exception is supplied, and the method wishes to suppress the\n   exception (i.e., prevent it from being propagated), it should\n   return a true value. Otherwise, the exception will be processed\n   normally upon exit from this method.\n\n   Note that "__exit__()" methods should not reraise the passed-in\n   exception; this is the caller\'s responsibility.\n\nSee also: **PEP 343** - The "with" statement\n\n     The specification, background, and examples for the Python "with"\n     statement.\n\n\nSpecial method lookup\n=====================\n\nFor custom classes, implicit invocations of special methods are only\nguaranteed to work correctly if defined on an object\'s type, not in\nthe object\'s instance dictionary.  That behaviour is the reason why\nthe following code raises an exception:\n\n   >>> class C:\n   ...     pass\n   ...\n   >>> c = C()\n   >>> c.__len__ = lambda: 5\n   >>> len(c)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as "__hash__()" and "__repr__()" that are implemented by\nall objects, including type objects. If the implicit lookup of these\nmethods used the conventional lookup process, they would fail when\ninvoked on the type object itself:\n\n   >>> 1 .__hash__() == hash(1)\n   True\n   >>> int.__hash__() == hash(int)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n   >>> type(1).__hash__(1) == hash(1)\n   True\n   >>> type(int).__hash__(int) == hash(int)\n   True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe "__getattribute__()" method even of the object\'s metaclass:\n\n   >>> class Meta(type):\n   ...     def __getattribute__(*args):\n   ...         print("Metaclass getattribute invoked")\n   ...         return type.__getattribute__(*args)\n   ...\n   >>> class C(object, metaclass=Meta):\n   ...     def __len__(self):\n   ...         return 10\n   ...     def __getattribute__(*args):\n   ...         print("Class getattribute invoked")\n   ...         return object.__getattribute__(*args)\n   ...\n   >>> c = C()\n   >>> c.__len__()                 # Explicit lookup via instance\n   Class getattribute invoked\n   10\n   >>> type(c).__len__(c)          # Explicit lookup via type\n   Metaclass getattribute invoked\n   10\n   >>> len(c)                      # Implicit lookup\n   10\n\nBypassing the "__getattribute__()" machinery in this fashion provides\nsignificant scope for speed optimisations within the interpreter, at\nthe cost of some flexibility in the handling of special methods (the\nspecial method *must* be set on the class object itself in order to be\nconsistently invoked by the interpreter).\n',
+ 'string-methods': u'\nString Methods\n**************\n\nStrings implement all of the *common* sequence operations, along with\nthe additional methods described below.\n\nStrings also support two styles of string formatting, one providing a\nlarge degree of flexibility and customization (see "str.format()",\n*Format String Syntax* and *Custom String Formatting*) and the other\nbased on C "printf" style formatting that handles a narrower range of\ntypes and is slightly harder to use correctly, but is often faster for\nthe cases it can handle (*printf-style String Formatting*).\n\nThe *Text Processing Services* section of the standard library covers\na number of other modules that provide various text related utilities\n(including regular expression support in the "re" module).\n\nstr.capitalize()\n\n   Return a copy of the string with its first character capitalized\n   and the rest lowercased.\n\nstr.casefold()\n\n   Return a casefolded copy of the string. Casefolded strings may be\n   used for caseless matching.\n\n   Casefolding is similar to lowercasing but more aggressive because\n   it is intended to remove all case distinctions in a string. For\n   example, the German lowercase letter "\'\xdf\'" is equivalent to ""ss"".\n   Since it is already lowercase, "lower()" would do nothing to "\'\xdf\'";\n   "casefold()" converts it to ""ss"".\n\n   The casefolding algorithm is described in section 3.13 of the\n   Unicode Standard.\n\n   New in version 3.3.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is an ASCII space). The\n   original string is returned if *width* is less than or equal to\n   "len(s)".\n\nstr.count(sub[, start[, end]])\n\n   Return the number of non-overlapping occurrences of substring *sub*\n   in the range [*start*, *end*].  Optional arguments *start* and\n   *end* are interpreted as in slice notation.\n\nstr.encode(encoding="utf-8", errors="strict")\n\n   Return an encoded version of the string as a bytes object. Default\n   encoding is "\'utf-8\'". *errors* may be given to set a different\n   error handling scheme. The default for *errors* is "\'strict\'",\n   meaning that encoding errors raise a "UnicodeError". Other possible\n   values are "\'ignore\'", "\'replace\'", "\'xmlcharrefreplace\'",\n   "\'backslashreplace\'" and any other name registered via\n   "codecs.register_error()", see section *Error Handlers*. For a list\n   of possible encodings, see section *Standard Encodings*.\n\n   Changed in version 3.1: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return "True" if the string ends with the specified *suffix*,\n   otherwise return "False".  *suffix* can also be a tuple of suffixes\n   to look for.  With optional *start*, test beginning at that\n   position.  With optional *end*, stop comparing at that position.\n\nstr.expandtabs(tabsize=8)\n\n   Return a copy of the string where all tab characters are replaced\n   by one or more spaces, depending on the current column and the\n   given tab size.  Tab positions occur every *tabsize* characters\n   (default is 8, giving tab positions at columns 0, 8, 16 and so on).\n   To expand the string, the current column is set to zero and the\n   string is examined character by character.  If the character is a\n   tab ("\\t"), one or more space characters are inserted in the result\n   until the current column is equal to the next tab position. (The\n   tab character itself is not copied.)  If the character is a newline\n   ("\\n") or return ("\\r"), it is copied and the current column is\n   reset to zero.  Any other character is copied unchanged and the\n   current column is incremented by one regardless of how the\n   character is represented when printed.\n\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs()\n   \'01      012     0123    01234\'\n   >>> \'01\\t012\\t0123\\t01234\'.expandtabs(4)\n   \'01  012 0123    01234\'\n\nstr.find(sub[, start[, end]])\n\n   Return the lowest index in the string where substring *sub* is\n   found within the slice "s[start:end]".  Optional arguments *start*\n   and *end* are interpreted as in slice notation.  Return "-1" if\n   *sub* is not found.\n\n   Note: The "find()" method should be used only if you need to know\n     the position of *sub*.  To check if *sub* is a substring or not,\n     use the "in" operator:\n\n        >>> \'Py\' in \'Python\'\n        True\n\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The string on which this\n   method is called can contain literal text or replacement fields\n   delimited by braces "{}".  Each replacement field contains either\n   the numeric index of a positional argument, or the name of a\n   keyword argument.  Returns a copy of the string where each\n   replacement field is replaced with the string value of the\n   corresponding argument.\n\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\n   \'The sum of 1 + 2 is 3\'\n\n   See *Format String Syntax* for a description of the various\n   formatting options that can be specified in format strings.\n\nstr.format_map(mapping)\n\n   Similar to "str.format(**mapping)", except that "mapping" is used\n   directly and not copied to a "dict".  This is useful if for example\n   "mapping" is a dict subclass:\n\n   >>> class Default(dict):\n   ...     def __missing__(self, key):\n   ...         return key\n   ...\n   >>> \'{name} was born in {country}\'.format_map(Default(name=\'Guido\'))\n   \'Guido was born in country\'\n\n   New in version 3.2.\n\nstr.index(sub[, start[, end]])\n\n   Like "find()", but raise "ValueError" when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.  A character "c"\n   is alphanumeric if one of the following returns "True":\n   "c.isalpha()", "c.isdecimal()", "c.isdigit()", or "c.isnumeric()".\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.  Alphabetic\n   characters are those characters defined in the Unicode character\n   database as "Letter", i.e., those with general category property\n   being one of "Lm", "Lt", "Lu", "Ll", or "Lo".  Note that this is\n   different from the "Alphabetic" property defined in the Unicode\n   Standard.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters are those that can be used to form numbers in base 10,\n   e.g. U+0660, ARABIC-INDIC DIGIT ZERO.  Formally a decimal character\n   is a character in the Unicode General Category "Nd".\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.  Digits include decimal\n   characters and digits that need special handling, such as the\n   compatibility superscript digits. This covers digits which cannot\n   be used to form numbers in base 10, like the Kharosthi numbers.\n   Formally, a digit is a character that has the property value\n   Numeric_Type=Digit or Numeric_Type=Decimal.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\n   Use "keyword.iskeyword()" to test for reserved identifiers such as\n   "def" and "class".\n\nstr.islower()\n\n   Return true if all cased characters [4] in the string are lowercase\n   and there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.  Formally, numeric characters are those with the\n   property value Numeric_Type=Digit, Numeric_Type=Decimal or\n   Numeric_Type=Numeric.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when "repr()" is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to "sys.stdout" or "sys.stderr".)\n\nstr.isspace()\n\n   Return true if there are only whitespace characters in the string\n   and there is at least one character, false otherwise.  Whitespace\n   characters  are those characters defined in the Unicode character\n   database as "Other" or "Separator" and those with bidirectional\n   property being one of "WS", "B", or "S".\n\nstr.istitle()\n\n   Return true if the string is a titlecased string and there is at\n   least one character, for example uppercase characters may only\n   follow uncased characters and lowercase characters only cased ones.\n   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters [4] in the string are uppercase\n   and there is at least one cased character, false otherwise.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  A "TypeError" will be raised if there are\n   any non-string values in *iterable*, including "bytes" objects.\n   The separator between elements is the string providing this method.\n\nstr.ljust(width[, fillchar])\n\n   Return the string left justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is an ASCII\n   space). The original string is returned if *width* is less than or\n   equal to "len(s)".\n\nstr.lower()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to lowercase.\n\n   The lowercasing algorithm used is described in section 3.13 of the\n   Unicode Standard.\n\nstr.lstrip([chars])\n\n   Return a copy of the string with leading characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or "None", the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n      >>> \'   spacious   \'.lstrip()\n      \'spacious   \'\n      >>> \'www.example.com\'.lstrip(\'cmowz.\')\n      \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   "str.translate()".\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or "None".\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   "None" in the result.\n\nstr.partition(sep)\n\n   Split the string at the first occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\n\n   Return a copy of the string with all occurrences of substring *old*\n   replaced by *new*.  If the optional argument *count* is given, only\n   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n   Return the highest index in the string where substring *sub* is\n   found, such that *sub* is contained within "s[start:end]".\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return "-1" on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like "rfind()" but raises "ValueError" when the substring *sub* is\n   not found.\n\nstr.rjust(width[, fillchar])\n\n   Return the string right justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is an ASCII\n   space). The original string is returned if *width* is less than or\n   equal to "len(s)".\n\nstr.rpartition(sep)\n\n   Split the string at the last occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.rsplit(sep=None, maxsplit=-1)\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n   are done, the *rightmost* ones.  If *sep* is not specified or\n   "None", any whitespace string is a separator.  Except for splitting\n   from the right, "rsplit()" behaves like "split()" which is\n   described in detail below.\n\nstr.rstrip([chars])\n\n   Return a copy of the string with trailing characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or "None", the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n      >>> \'   spacious   \'.rstrip()\n      \'   spacious\'\n      >>> \'mississippi\'.rstrip(\'ipz\')\n      \'mississ\'\n\nstr.split(sep=None, maxsplit=-1)\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string.  If *maxsplit* is given, at most *maxsplit*\n   splits are done (thus, the list will have at most "maxsplit+1"\n   elements).  If *maxsplit* is not specified or "-1", then there is\n   no limit on the number of splits (all possible splits are made).\n\n   If *sep* is given, consecutive delimiters are not grouped together\n   and are deemed to delimit empty strings (for example,\n   "\'1,,2\'.split(\',\')" returns "[\'1\', \'\', \'2\']").  The *sep* argument\n   may consist of multiple characters (for example,\n   "\'1<>2<>3\'.split(\'<>\')" returns "[\'1\', \'2\', \'3\']"). Splitting an\n   empty string with a specified separator returns "[\'\']".\n\n   For example:\n\n      >>> \'1,2,3\'.split(\',\')\n      [\'1\', \'2\', \'3\']\n      >>> \'1,2,3\'.split(\',\', maxsplit=1)\n      [\'1\', \'2,3\']\n      >>> \'1,2,,3,\'.split(\',\')\n      [\'1\', \'2\', \'\', \'3\', \'\']\n\n   If *sep* is not specified or is "None", a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no empty strings\n   at the start or end if the string has leading or trailing\n   whitespace.  Consequently, splitting an empty string or a string\n   consisting of just whitespace with a "None" separator returns "[]".\n\n   For example:\n\n      >>> \'1 2 3\'.split()\n      [\'1\', \'2\', \'3\']\n      >>> \'1 2 3\'.split(maxsplit=1)\n      [\'1\', \'2 3\']\n      >>> \'   1   2   3   \'.split()\n      [\'1\', \'2\', \'3\']\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\n   This method splits on the following line boundaries.  In\n   particular, the boundaries are a superset of *universal newlines*.\n\n   +-------------------------+-------------------------------+\n   | Representation          | Description                   |\n   +=========================+===============================+\n   | "\\n"                    | Line Feed                     |\n   +-------------------------+-------------------------------+\n   | "\\r"                    | Carriage Return               |\n   +-------------------------+-------------------------------+\n   | "\\r\\n"                  | Carriage Return + Line Feed   |\n   +-------------------------+-------------------------------+\n   | "\\v" or "\\x0b"          | Line Tabulation               |\n   +-------------------------+-------------------------------+\n   | "\\f" or "\\x0c"          | Form Feed                     |\n   +-------------------------+-------------------------------+\n   | "\\x1c"                  | File Separator                |\n   +-------------------------+-------------------------------+\n   | "\\x1d"                  | Group Separator               |\n   +-------------------------+-------------------------------+\n   | "\\x1e"                  | Record Separator              |\n   +-------------------------+-------------------------------+\n   | "\\x85"                  | Next Line (C1 Control Code)   |\n   +-------------------------+-------------------------------+\n   | "\\u2028"                | Line Separator                |\n   +-------------------------+-------------------------------+\n   | "\\u2029"                | Paragraph Separator           |\n   +-------------------------+-------------------------------+\n\n   Changed in version 3.2: "\\v" and "\\f" added to list of line\n   boundaries.\n\n   For example:\n\n      >>> \'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines()\n      [\'ab c\', \'\', \'de fg\', \'kl\']\n      >>> \'ab c\\n\\nde fg\\rkl\\r\\n\'.splitlines(keepends=True)\n      [\'ab c\\n\', \'\\n\', \'de fg\\r\', \'kl\\r\\n\']\n\n   Unlike "split()" when a delimiter string *sep* is given, this\n   method returns an empty list for the empty string, and a terminal\n   line break does not result in an extra line:\n\n      >>> "".splitlines()\n      []\n      >>> "One line\\n".splitlines()\n      [\'One line\']\n\n   For comparison, "split(\'\\n\')" gives:\n\n      >>> \'\'.split(\'\\n\')\n      [\'\']\n      >>> \'Two lines\\n\'.split(\'\\n\')\n      [\'Two lines\', \'\']\n\nstr.startswith(prefix[, start[, end]])\n\n   Return "True" if string starts with the *prefix*, otherwise return\n   "False". *prefix* can also be a tuple of prefixes to look for.\n   With optional *start*, test string beginning at that position.\n   With optional *end*, stop comparing string at that position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or "None", the *chars*\n   argument defaults to removing whitespace. The *chars* argument is\n   not a prefix or suffix; rather, all combinations of its values are\n   stripped:\n\n      >>> \'   spacious   \'.strip()\n      \'spacious\'\n      >>> \'www.example.com\'.strip(\'cmowz.\')\n      \'example\'\n\n   The outermost leading and trailing *chars* argument values are\n   stripped from the string. Characters are removed from the leading\n   end until reaching a string character that is not contained in the\n   set of characters in *chars*. A similar action takes place on the\n   trailing end. For example:\n\n      >>> comment_string = \'#....... Section 3.2.1 Issue #32 .......\'\n      >>> comment_string.strip(\'.#! \')\n      \'Section 3.2.1 Issue #32\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa. Note that it is not necessarily true that\n   "s.swapcase().swapcase() == s".\n\nstr.title()\n\n   Return a titlecased version of the string where words start with an\n   uppercase character and the remaining characters are lowercase.\n\n   For example:\n\n      >>> \'Hello world\'.title()\n      \'Hello World\'\n\n   The algorithm uses a simple language-independent definition of a\n   word as groups of consecutive letters.  The definition works in\n   many contexts but it means that apostrophes in contractions and\n   possessives form word boundaries, which may not be the desired\n   result:\n\n      >>> "they\'re bill\'s friends from the UK".title()\n      "They\'Re Bill\'S Friends From The Uk"\n\n   A workaround for apostrophes can be constructed using regular\n   expressions:\n\n      >>> import re\n      >>> def titlecase(s):\n      ...     return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n      ...                   lambda mo: mo.group(0)[0].upper() +\n      ...                              mo.group(0)[1:].lower(),\n      ...                   s)\n      ...\n      >>> titlecase("they\'re bill\'s friends.")\n      "They\'re Bill\'s Friends."\n\nstr.translate(table)\n\n   Return a copy of the string in which each character has been mapped\n   through the given translation table.  The table must be an object\n   that implements indexing via "__getitem__()", typically a *mapping*\n   or *sequence*.  When indexed by a Unicode ordinal (an integer), the\n   table object can do any of the following: return a Unicode ordinal\n   or a string, to map the character to one or more other characters;\n   return "None", to delete the character from the return string; or\n   raise a "LookupError" exception, to map the character to itself.\n\n   You can use "str.maketrans()" to create a translation map from\n   character-to-character mappings in different formats.\n\n   See also the "codecs" module for a more flexible approach to custom\n   character mappings.\n\nstr.upper()\n\n   Return a copy of the string with all the cased characters [4]\n   converted to uppercase.  Note that "str.upper().isupper()" might be\n   "False" if "s" contains uncased characters or if the Unicode\n   category of the resulting character(s) is not "Lu" (Letter,\n   uppercase), but e.g. "Lt" (Letter, titlecase).\n\n   The uppercasing algorithm used is described in section 3.13 of the\n   Unicode Standard.\n\nstr.zfill(width)\n\n   Return a copy of the string left filled with ASCII "\'0\'" digits to\n   make a string of length *width*. A leading sign prefix\n   ("\'+\'"/"\'-\'") is handled by inserting the padding *after* the sign\n   character rather than before. The original string is returned if\n   *width* is less than or equal to "len(s)".\n\n   For example:\n\n      >>> "42".zfill(5)\n      \'00042\'\n      >>> "-42".zfill(5)\n      \'-0042\'\n',
  'strings': u'\nString and Bytes literals\n*************************\n\nString literals are described by the following lexical definitions:\n\n   stringliteral   ::= [stringprefix](shortstring | longstring)\n   stringprefix    ::= "r" | "u" | "R" | "U"\n   shortstring     ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n   longstring      ::= "\'\'\'" longstringitem* "\'\'\'" | \'"""\' longstringitem* \'"""\'\n   shortstringitem ::= shortstringchar | stringescapeseq\n   longstringitem  ::= longstringchar | stringescapeseq\n   shortstringchar ::= <any source character except "\\" or newline or the quote>\n   longstringchar  ::= <any source character except "\\">\n   stringescapeseq ::= "\\" <any source character>\n\n   bytesliteral   ::= bytesprefix(shortbytes | longbytes)\n   bytesprefix    ::= "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"\n   shortbytes     ::= "\'" shortbytesitem* "\'" | \'"\' shortbytesitem* \'"\'\n   longbytes      ::= "\'\'\'" longbytesitem* "\'\'\'" | \'"""\' longbytesitem* \'"""\'\n   shortbytesitem ::= shortbyteschar | bytesescapeseq\n   longbytesitem  ::= longbyteschar | bytesescapeseq\n   shortbyteschar ::= <any ASCII character except "\\" or newline or the quote>\n   longbyteschar  ::= <any ASCII character except "\\">\n   bytesescapeseq ::= "\\" <any ASCII character>\n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the "stringprefix" or "bytesprefix"\nand the rest of the literal. The source character set is defined by\nthe encoding declaration; it is UTF-8 if no encoding declaration is\ngiven in the source file; see section *Encoding declarations*.\n\nIn plain English: Both types of literals can be enclosed in matching\nsingle quotes ("\'") or double quotes (""").  They can also be enclosed\nin matching groups of three single or double quotes (these are\ngenerally referred to as *triple-quoted strings*).  The backslash\n("\\") character is used to escape characters that otherwise have a\nspecial meaning, such as newline, backslash itself, or the quote\ncharacter.\n\nBytes literals are always prefixed with "\'b\'" or "\'B\'"; they produce\nan instance of the "bytes" type instead of the "str" type.  They may\nonly contain ASCII characters; bytes with a numeric value of 128 or\ngreater must be expressed with escapes.\n\nAs of Python 3.3 it is possible again to prefix string literals with a\n"u" prefix to simplify maintenance of dual 2.x and 3.x codebases.\n\nBoth string and bytes literals may optionally be prefixed with a\nletter "\'r\'" or "\'R\'"; such strings are called *raw strings* and treat\nbackslashes as literal characters.  As a result, in string literals,\n"\'\\U\'" and "\'\\u\'" escapes in raw strings are not treated specially.\nGiven that Python 2.x\'s raw unicode literals behave differently than\nPython 3.x\'s the "\'ur\'" syntax is not supported.\n\nNew in version 3.3: The "\'rb\'" prefix of raw bytes literals has been\nadded as a synonym of "\'br\'".\n\nNew in version 3.3: Support for the unicode legacy literal\n("u\'value\'") was reintroduced to simplify the maintenance of dual\nPython 2.x and 3.x codebases. See **PEP 414** for more information.\n\nIn triple-quoted literals, unescaped newlines and quotes are allowed\n(and are retained), except that three unescaped quotes in a row\nterminate the literal.  (A "quote" is the character used to open the\nliteral, i.e. either "\'" or """.)\n\nUnless an "\'r\'" or "\'R\'" prefix is present, escape sequences in string\nand bytes literals are interpreted according to rules similar to those\nused by Standard C.  The recognized escape sequences are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence   | Meaning                           | Notes   |\n+===================+===================================+=========+\n| "\\newline"        | Backslash and newline ignored     |         |\n+-------------------+-----------------------------------+---------+\n| "\\\\"              | Backslash ("\\")                   |         |\n+-------------------+-----------------------------------+---------+\n| "\\\'"              | Single quote ("\'")                |         |\n+-------------------+-----------------------------------+---------+\n| "\\""              | Double quote (""")                |         |\n+-------------------+-----------------------------------+---------+\n| "\\a"              | ASCII Bell (BEL)                  |         |\n+-------------------+-----------------------------------+---------+\n| "\\b"              | ASCII Backspace (BS)              |         |\n+-------------------+-----------------------------------+---------+\n| "\\f"              | ASCII Formfeed (FF)               |         |\n+-------------------+-----------------------------------+---------+\n| "\\n"              | ASCII Linefeed (LF)               |         |\n+-------------------+-----------------------------------+---------+\n| "\\r"              | ASCII Carriage Return (CR)        |         |\n+-------------------+-----------------------------------+---------+\n| "\\t"              | ASCII Horizontal Tab (TAB)        |         |\n+-------------------+-----------------------------------+---------+\n| "\\v"              | ASCII Vertical Tab (VT)           |         |\n+-------------------+-----------------------------------+---------+\n| "\\ooo"            | Character with octal value *ooo*  | (1,3)   |\n+-------------------+-----------------------------------+---------+\n| "\\xhh"            | Character with hex value *hh*     | (2,3)   |\n+-------------------+-----------------------------------+---------+\n\nEscape sequences only recognized in string literals are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence   | Meaning                           | Notes   |\n+===================+===================================+=========+\n| "\\N{name}"        | Character named *name* in the     | (4)     |\n|                   | Unicode database                  |         |\n+-------------------+-----------------------------------+---------+\n| "\\uxxxx"          | Character with 16-bit hex value   | (5)     |\n|                   | *xxxx*                            |         |\n+-------------------+-----------------------------------+---------+\n| "\\Uxxxxxxxx"      | Character with 32-bit hex value   | (6)     |\n|                   | *xxxxxxxx*                        |         |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. As in Standard C, up to three octal digits are accepted.\n\n2. Unlike in Standard C, exactly two hex digits are required.\n\n3. In a bytes literal, hexadecimal and octal escapes denote the\n   byte with the given value. In a string literal, these escapes\n   denote a Unicode character with the given value.\n\n4. Changed in version 3.3: Support for name aliases [1] has been\n   added.\n\n5. Exactly four hex digits are required.\n\n6. Any Unicode character can be encoded this way.  Exactly eight\n   hex digits are required.\n\nUnlike Standard C, all unrecognized escape sequences are left in the\nstring unchanged, i.e., *the backslash is left in the result*.  (This\nbehavior is useful when debugging: if an escape sequence is mistyped,\nthe resulting output is more easily recognized as broken.)  It is also\nimportant to note that the escape sequences only recognized in string\nliterals fall into the category of unrecognized escapes for bytes\nliterals.\n\nEven in a raw literal, quotes can be escaped with a backslash, but the\nbackslash remains in the result; for example, "r"\\""" is a valid\nstring literal consisting of two characters: a backslash and a double\nquote; "r"\\"" is not a valid string literal (even a raw string cannot\nend in an odd number of backslashes).  Specifically, *a raw literal\ncannot end in a single backslash* (since the backslash would escape\nthe following quote character).  Note also that a single backslash\nfollowed by a newline is interpreted as those two characters as part\nof the literal, *not* as a line continuation.\n',
  'subscriptions': u'\nSubscriptions\n*************\n\nA subscription selects an item of a sequence (string, tuple or list)\nor mapping (dictionary) object:\n\n   subscription ::= primary "[" expression_list "]"\n\nThe primary must evaluate to an object that supports subscription\n(lists or dictionaries for example).  User-defined objects can support\nsubscription by defining a "__getitem__()" method.\n\nFor built-in objects, there are two types of objects that support\nsubscription:\n\nIf the primary is a mapping, the expression list must evaluate to an\nobject whose value is one of the keys of the mapping, and the\nsubscription selects the value in the mapping that corresponds to that\nkey.  (The expression list is a tuple except if it has exactly one\nitem.)\n\nIf the primary is a sequence, the expression (list) must evaluate to\nan integer or a slice (as discussed in the following section).\n\nThe formal syntax makes no special provision for negative indices in\nsequences; however, built-in sequences all provide a "__getitem__()"\nmethod that interprets negative indices by adding the length of the\nsequence to the index (so that "x[-1]" selects the last item of "x").\nThe resulting value must be a nonnegative integer less than the number\nof items in the sequence, and the subscription selects the item whose\nindex is that value (counting from zero). Since the support for\nnegative indices and slicing occurs in the object\'s "__getitem__()"\nmethod, subclasses overriding this method will need to explicitly add\nthat support.\n\nA string\'s items are characters.  A character is not a separate data\ntype but a string of exactly one character.\n',
  'truth': u'\nTruth Value Testing\n*******************\n\nAny object can be tested for truth value, for use in an "if" or\n"while" condition or as operand of the Boolean operations below. The\nfollowing values are considered false:\n\n* "None"\n\n* "False"\n\n* zero of any numeric type, for example, "0", "0.0", "0j".\n\n* any empty sequence, for example, "\'\'", "()", "[]".\n\n* any empty mapping, for example, "{}".\n\n* instances of user-defined classes, if the class defines a\n  "__bool__()" or "__len__()" method, when that method returns the\n  integer zero or "bool" value "False". [1]\n\nAll other values are considered true --- so objects of many types are\nalways true.\n\nOperations and built-in functions that have a Boolean result always\nreturn "0" or "False" for false and "1" or "True" for true, unless\notherwise stated. (Important exception: the Boolean operations "or"\nand "and" always return one of their operands.)\n',
  'try': u'\nThe "try" statement\n*******************\n\nThe "try" statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" identifier]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe "except" clause(s) specify one or more exception handlers. When no\nexception occurs in the "try" clause, no exception handler is\nexecuted. When an exception occurs in the "try" suite, a search for an\nexception handler is started.  This search inspects the except clauses\nin turn until one is found that matches the exception.  An expression-\nless except clause, if present, must be last; it matches any\nexception.  For an except clause with an expression, that expression\nis evaluated, and the clause matches the exception if the resulting\nobject is "compatible" with the exception.  An object is compatible\nwith an exception if it is the class or a base class of the exception\nobject or a tuple containing an item compatible with the exception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire "try" statement raised\nthe exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the "as" keyword in that except clause, if\npresent, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using "as target", it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause.  Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the "sys" module and can be accessed via\n"sys.exc_info()". "sys.exc_info()" returns a 3-tuple consisting of the\nexception class, the exception instance and a traceback object (see\nsection *The standard type hierarchy*) identifying the point in the\nprogram where the exception occurred.  "sys.exc_info()" values are\nrestored to their previous values (before the call) when returning\nfrom a function that handled an exception.\n\nThe optional "else" clause is executed if and when control flows off\nthe end of the "try" clause. [2] Exceptions in the "else" clause are\nnot handled by the preceding "except" clauses.\n\nIf "finally" is present, it specifies a \'cleanup\' handler.  The "try"\nclause is executed, including any "except" and "else" clauses.  If an\nexception occurs in any of the clauses and is not handled, the\nexception is temporarily saved. The "finally" clause is executed.  If\nthere is a saved exception it is re-raised at the end of the "finally"\nclause.  If the "finally" clause raises another exception, the saved\nexception is set as the context of the new exception. If the "finally"\nclause executes a "return" or "break" statement, the saved exception\nis discarded:\n\n   >>> def f():\n   ...     try:\n   ...         1/0\n   ...     finally:\n   ...         return 42\n   ...\n   >>> f()\n   42\n\nThe exception information is not available to the program during\nexecution of the "finally" clause.\n\nWhen a "return", "break" or "continue" statement is executed in the\n"try" suite of a "try"..."finally" statement, the "finally" clause is\nalso executed \'on the way out.\' A "continue" statement is illegal in\nthe "finally" clause. (The reason is a problem with the current\nimplementation --- this restriction may be lifted in the future).\n\nThe return value of a function is determined by the last "return"\nstatement executed.  Since the "finally" clause always executes, a\n"return" statement executed in the "finally" clause will always be the\nlast one executed:\n\n   >>> def foo():\n   ...     try:\n   ...         return \'try\'\n   ...     finally:\n   ...         return \'finally\'\n   ...\n   >>> foo()\n   \'finally\'\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the "raise" statement to\ngenerate exceptions may be found in section *The raise statement*.\n',
- 'types': u'\nThe standard type hierarchy\n***************************\n\nBelow is a list of the types that are built into Python.  Extension\nmodules (written in C, Java, or other languages, depending on the\nimplementation) can define additional types.  Future versions of\nPython may add types to the type hierarchy (e.g., rational numbers,\nefficiently stored arrays of integers, etc.), although such additions\nwill often be provided via the standard library instead.\n\nSome of the type descriptions below contain a paragraph listing\n\'special attributes.\'  These are attributes that provide access to the\nimplementation and are not intended for general use.  Their definition\nmay change in the future.\n\nNone\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the built-in name "None". It\n   is used to signify the absence of a value in many situations, e.g.,\n   it is returned from functions that don\'t explicitly return\n   anything. Its truth value is false.\n\nNotImplemented\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the built-in name\n   "NotImplemented". Numeric methods and rich comparison methods\n   should return this value if they do not implement the operation for\n   the operands provided.  (The interpreter will then try the\n   reflected operation, or some other fallback, depending on the\n   operator.)  Its truth value is true.\n\n   See *Implementing the arithmetic operations* for more details.\n\nEllipsis\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the literal "..." or the\n   built-in name "Ellipsis".  Its truth value is true.\n\n"numbers.Number"\n   These are created by numeric literals and returned as results by\n   arithmetic operators and arithmetic built-in functions.  Numeric\n   objects are immutable; once created their value never changes.\n   Python numbers are of course strongly related to mathematical\n   numbers, but subject to the limitations of numerical representation\n   in computers.\n\n   Python distinguishes between integers, floating point numbers, and\n   complex numbers:\n\n   "numbers.Integral"\n      These represent elements from the mathematical set of integers\n      (positive and negative).\n\n      There are two types of integers:\n\n      Integers ("int")\n\n         These represent numbers in an unlimited range, subject to\n         available (virtual) memory only.  For the purpose of shift\n         and mask operations, a binary representation is assumed, and\n         negative numbers are represented in a variant of 2\'s\n         complement which gives the illusion of an infinite string of\n         sign bits extending to the left.\n\n      Booleans ("bool")\n         These represent the truth values False and True.  The two\n         objects representing the values "False" and "True" are the\n         only Boolean objects. The Boolean type is a subtype of the\n         integer type, and Boolean values behave like the values 0 and\n         1, respectively, in almost all contexts, the exception being\n         that when converted to a string, the strings ""False"" or\n         ""True"" are returned, respectively.\n\n      The rules for integer representation are intended to give the\n      most meaningful interpretation of shift and mask operations\n      involving negative integers.\n\n   "numbers.Real" ("float")\n      These represent machine-level double precision floating point\n      numbers. You are at the mercy of the underlying machine\n      architecture (and C or Java implementation) for the accepted\n      range and handling of overflow. Python does not support single-\n      precision floating point numbers; the savings in processor and\n      memory usage that are usually the reason for using these are\n      dwarfed by the overhead of using objects in Python, so there is\n      no reason to complicate the language with two kinds of floating\n      point numbers.\n\n   "numbers.Complex" ("complex")\n      These represent complex numbers as a pair of machine-level\n      double precision floating point numbers.  The same caveats apply\n      as for floating point numbers. The real and imaginary parts of a\n      complex number "z" can be retrieved through the read-only\n      attributes "z.real" and "z.imag".\n\nSequences\n   These represent finite ordered sets indexed by non-negative\n   numbers. The built-in function "len()" returns the number of items\n   of a sequence. When the length of a sequence is *n*, the index set\n   contains the numbers 0, 1, ..., *n*-1.  Item *i* of sequence *a* is\n   selected by "a[i]".\n\n   Sequences also support slicing: "a[i:j]" selects all items with\n   index *k* such that *i* "<=" *k* "<" *j*.  When used as an\n   expression, a slice is a sequence of the same type.  This implies\n   that the index set is renumbered so that it starts at 0.\n\n   Some sequences also support "extended slicing" with a third "step"\n   parameter: "a[i:j:k]" selects all items of *a* with index *x* where\n   "x = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *j*.\n\n   Sequences are distinguished according to their mutability:\n\n   Immutable sequences\n      An object of an immutable sequence type cannot change once it is\n      created.  (If the object contains references to other objects,\n      these other objects may be mutable and may be changed; however,\n      the collection of objects directly referenced by an immutable\n      object cannot change.)\n\n      The following types are immutable sequences:\n\n      Strings\n         A string is a sequence of values that represent Unicode code\n         points. All the code points in the range "U+0000 - U+10FFFF"\n         can be represented in a string.  Python doesn\'t have a "char"\n         type; instead, every code point in the string is represented\n         as a string object with length "1".  The built-in function\n         "ord()" converts a code point from its string form to an\n         integer in the range "0 - 10FFFF"; "chr()" converts an\n         integer in the range "0 - 10FFFF" to the corresponding length\n         "1" string object. "str.encode()" can be used to convert a\n         "str" to "bytes" using the given text encoding, and\n         "bytes.decode()" can be used to achieve the opposite.\n\n      Tuples\n         The items of a tuple are arbitrary Python objects. Tuples of\n         two or more items are formed by comma-separated lists of\n         expressions.  A tuple of one item (a \'singleton\') can be\n         formed by affixing a comma to an expression (an expression by\n         itself does not create a tuple, since parentheses must be\n         usable for grouping of expressions).  An empty tuple can be\n         formed by an empty pair of parentheses.\n\n      Bytes\n         A bytes object is an immutable array.  The items are 8-bit\n         bytes, represented by integers in the range 0 <= x < 256.\n         Bytes literals (like "b\'abc\'") and the built-in function\n         "bytes()" can be used to construct bytes objects.  Also,\n         bytes objects can be decoded to strings via the "decode()"\n         method.\n\n   Mutable sequences\n      Mutable sequences can be changed after they are created.  The\n      subscription and slicing notations can be used as the target of\n      assignment and "del" (delete) statements.\n\n      There are currently two intrinsic mutable sequence types:\n\n      Lists\n         The items of a list are arbitrary Python objects.  Lists are\n         formed by placing a comma-separated list of expressions in\n         square brackets. (Note that there are no special cases needed\n         to form lists of length 0 or 1.)\n\n      Byte Arrays\n         A bytearray object is a mutable array. They are created by\n         the built-in "bytearray()" constructor.  Aside from being\n         mutable (and hence unhashable), byte arrays otherwise provide\n         the same interface and functionality as immutable bytes\n         objects.\n\n      The extension module "array" provides an additional example of a\n      mutable sequence type, as does the "collections" module.\n\nSet types\n   These represent unordered, finite sets of unique, immutable\n   objects. As such, they cannot be indexed by any subscript. However,\n   they can be iterated over, and the built-in function "len()"\n   returns the number of items in a set. Common uses for sets are fast\n   membership testing, removing duplicates from a sequence, and\n   computing mathematical operations such as intersection, union,\n   difference, and symmetric difference.\n\n   For set elements, the same immutability rules apply as for\n   dictionary keys. Note that numeric types obey the normal rules for\n   numeric comparison: if two numbers compare equal (e.g., "1" and\n   "1.0"), only one of them can be contained in a set.\n\n   There are currently two intrinsic set types:\n\n   Sets\n      These represent a mutable set. They are created by the built-in\n      "set()" constructor and can be modified afterwards by several\n      methods, such as "add()".\n\n   Frozen sets\n      These represent an immutable set.  They are created by the\n      built-in "frozenset()" constructor.  As a frozenset is immutable\n      and *hashable*, it can be used again as an element of another\n      set, or as a dictionary key.\n\nMappings\n   These represent finite sets of objects indexed by arbitrary index\n   sets. The subscript notation "a[k]" selects the item indexed by "k"\n   from the mapping "a"; this can be used in expressions and as the\n   target of assignments or "del" statements. The built-in function\n   "len()" returns the number of items in a mapping.\n\n   There is currently a single intrinsic mapping type:\n\n   Dictionaries\n      These represent finite sets of objects indexed by nearly\n      arbitrary values.  The only types of values not acceptable as\n      keys are values containing lists or dictionaries or other\n      mutable types that are compared by value rather than by object\n      identity, the reason being that the efficient implementation of\n      dictionaries requires a key\'s hash value to remain constant.\n      Numeric types used for keys obey the normal rules for numeric\n      comparison: if two numbers compare equal (e.g., "1" and "1.0")\n      then they can be used interchangeably to index the same\n      dictionary entry.\n\n      Dictionaries are mutable; they can be created by the "{...}"\n      notation (see section *Dictionary displays*).\n\n      The extension modules "dbm.ndbm" and "dbm.gnu" provide\n      additional examples of mapping types, as does the "collections"\n      module.\n\nCallable types\n   These are the types to which the function call operation (see\n   section *Calls*) can be applied:\n\n   User-defined functions\n      A user-defined function object is created by a function\n      definition (see section *Function definitions*).  It should be\n      called with an argument list containing the same number of items\n      as the function\'s formal parameter list.\n\n      Special attributes:\n\n      +---------------------------+---------------------------------+-------------+\n      | Attribute                 | Meaning                         |             |\n      +===========================+=================================+=============+\n      | "__doc__"                 | The function\'s documentation    | Writable    |\n      |                           | string, or "None" if            |             |\n      |                           | unavailable; not inherited by   |             |\n      |                           | subclasses                      |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__name__"                | The function\'s name             | Writable    |\n      +---------------------------+---------------------------------+-------------+\n      | "__qualname__"            | The function\'s *qualified name* | Writable    |\n      |                           | New in version 3.3.             |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__module__"              | The name of the module the      | Writable    |\n      |                           | function was defined in, or     |             |\n      |                           | "None" if unavailable.          |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__defaults__"            | A tuple containing default      | Writable    |\n      |                           | argument values for those       |             |\n      |                           | arguments that have defaults,   |             |\n      |                           | or "None" if no arguments have  |             |\n      |                           | a default value                 |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__code__"                | The code object representing    | Writable    |\n      |                           | the compiled function body.     |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__globals__"             | A reference to the dictionary   | Read-only   |\n      |                           | that holds the function\'s       |             |\n      |                           | global variables --- the global |             |\n      |                           | namespace of the module in      |             |\n      |                           | which the function was defined. |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__dict__"                | The namespace supporting        | Writable    |\n      |                           | arbitrary function attributes.  |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__closure__"             | "None" or a tuple of cells that | Read-only   |\n      |                           | contain bindings for the        |             |\n      |                           | function\'s free variables.      |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__annotations__"         | A dict containing annotations   | Writable    |\n      |                           | of parameters.  The keys of the |             |\n      |                           | dict are the parameter names,   |             |\n      |                           | and "\'return\'" for the return   |             |\n      |                           | annotation, if provided.        |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__kwdefaults__"          | A dict containing defaults for  | Writable    |\n      |                           | keyword-only parameters.        |             |\n      +---------------------------+---------------------------------+-------------+\n\n      Most of the attributes labelled "Writable" check the type of the\n      assigned value.\n\n      Function objects also support getting and setting arbitrary\n      attributes, which can be used, for example, to attach metadata\n      to functions.  Regular attribute dot-notation is used to get and\n      set such attributes. *Note that the current implementation only\n      supports function attributes on user-defined functions. Function\n      attributes on built-in functions may be supported in the\n      future.*\n\n      Additional information about a function\'s definition can be\n      retrieved from its code object; see the description of internal\n      types below.\n\n   Instance methods\n      An instance method object combines a class, a class instance and\n      any callable object (normally a user-defined function).\n\n      Special read-only attributes: "__self__" is the class instance\n      object, "__func__" is the function object; "__doc__" is the\n      method\'s documentation (same as "__func__.__doc__"); "__name__"\n      is the method name (same as "__func__.__name__"); "__module__"\n      is the name of the module the method was defined in, or "None"\n      if unavailable.\n\n      Methods also support accessing (but not setting) the arbitrary\n      function attributes on the underlying function object.\n\n      User-defined method objects may be created when getting an\n      attribute of a class (perhaps via an instance of that class), if\n      that attribute is a user-defined function object or a class\n      method object.\n\n      When an instance method object is created by retrieving a user-\n      defined function object from a class via one of its instances,\n      its "__self__" attribute is the instance, and the method object\n      is said to be bound.  The new method\'s "__func__" attribute is\n      the original function object.\n\n      When a user-defined method object is created by retrieving\n      another method object from a class or instance, the behaviour is\n      the same as for a function object, except that the "__func__"\n      attribute of the new instance is not the original method object\n      but its "__func__" attribute.\n\n      When an instance method object is created by retrieving a class\n      method object from a class or instance, its "__self__" attribute\n      is the class itself, and its "__func__" attribute is the\n      function object underlying the class method.\n\n      When an instance method object is called, the underlying\n      function ("__func__") is called, inserting the class instance\n      ("__self__") in front of the argument list.  For instance, when\n      "C" is a class which contains a definition for a function "f()",\n      and "x" is an instance of "C", calling "x.f(1)" is equivalent to\n      calling "C.f(x, 1)".\n\n      When an instance method object is derived from a class method\n      object, the "class instance" stored in "__self__" will actually\n      be the class itself, so that calling either "x.f(1)" or "C.f(1)"\n      is equivalent to calling "f(C,1)" where "f" is the underlying\n      function.\n\n      Note that the transformation from function object to instance\n      method object happens each time the attribute is retrieved from\n      the instance.  In some cases, a fruitful optimization is to\n      assign the attribute to a local variable and call that local\n      variable. Also notice that this transformation only happens for\n      user-defined functions; other callable objects (and all non-\n      callable objects) are retrieved without transformation.  It is\n      also important to note that user-defined functions which are\n      attributes of a class instance are not converted to bound\n      methods; this *only* happens when the function is an attribute\n      of the class.\n\n   Generator functions\n      A function or method which uses the "yield" statement (see\n      section *The yield statement*) is called a *generator function*.\n      Such a function, when called, always returns an iterator object\n      which can be used to execute the body of the function:  calling\n      the iterator\'s "iterator.__next__()" method will cause the\n      function to execute until it provides a value using the "yield"\n      statement.  When the function executes a "return" statement or\n      falls off the end, a "StopIteration" exception is raised and the\n      iterator will have reached the end of the set of values to be\n      returned.\n\n   Coroutine functions\n      A function or method which is defined using "async def" is\n      called a *coroutine function*.  Such a function, when called,\n      returns a *coroutine* object.  It may contain "await"\n      expressions, as well as "async with" and "async for" statements.\n      See also the *Coroutine Objects* section.\n\n   Built-in functions\n      A built-in function object is a wrapper around a C function.\n      Examples of built-in functions are "len()" and "math.sin()"\n      ("math" is a standard built-in module). The number and type of\n      the arguments are determined by the C function. Special read-\n      only attributes: "__doc__" is the function\'s documentation\n      string, or "None" if unavailable; "__name__" is the function\'s\n      name; "__self__" is set to "None" (but see the next item);\n      "__module__" is the name of the module the function was defined\n      in or "None" if unavailable.\n\n   Built-in methods\n      This is really a different disguise of a built-in function, this\n      time containing an object passed to the C function as an\n      implicit extra argument.  An example of a built-in method is\n      "alist.append()", assuming *alist* is a list object. In this\n      case, the special read-only attribute "__self__" is set to the\n      object denoted by *alist*.\n\n   Classes\n      Classes are callable.  These objects normally act as factories\n      for new instances of themselves, but variations are possible for\n      class types that override "__new__()".  The arguments of the\n      call are passed to "__new__()" and, in the typical case, to\n      "__init__()" to initialize the new instance.\n\n   Class Instances\n      Instances of arbitrary classes can be made callable by defining\n      a "__call__()" method in their class.\n\nModules\n   Modules are a basic organizational unit of Python code, and are\n   created by the *import system* as invoked either by the "import"\n   statement (see "import"), or by calling functions such as\n   "importlib.import_module()" and built-in "__import__()".  A module\n   object has a namespace implemented by a dictionary object (this is\n   the dictionary referenced by the "__globals__" attribute of\n   functions defined in the module).  Attribute references are\n   translated to lookups in this dictionary, e.g., "m.x" is equivalent\n   to "m.__dict__["x"]". A module object does not contain the code\n   object used to initialize the module (since it isn\'t needed once\n   the initialization is done).\n\n   Attribute assignment updates the module\'s namespace dictionary,\n   e.g., "m.x = 1" is equivalent to "m.__dict__["x"] = 1".\n\n   Special read-only attribute: "__dict__" is the module\'s namespace\n   as a dictionary object.\n\n   **CPython implementation detail:** Because of the way CPython\n   clears module dictionaries, the module dictionary will be cleared\n   when the module falls out of scope even if the dictionary still has\n   live references.  To avoid this, copy the dictionary or keep the\n   module around while using its dictionary directly.\n\n   Predefined (writable) attributes: "__name__" is the module\'s name;\n   "__doc__" is the module\'s documentation string, or "None" if\n   unavailable; "__file__" is the pathname of the file from which the\n   module was loaded, if it was loaded from a file. The "__file__"\n   attribute may be missing for certain types of modules, such as C\n   modules that are statically linked into the interpreter; for\n   extension modules loaded dynamically from a shared library, it is\n   the pathname of the shared library file.\n\nCustom classes\n   Custom class types are typically created by class definitions (see\n   section *Class definitions*).  A class has a namespace implemented\n   by a dictionary object. Class attribute references are translated\n   to lookups in this dictionary, e.g., "C.x" is translated to\n   "C.__dict__["x"]" (although there are a number of hooks which allow\n   for other means of locating attributes). When the attribute name is\n   not found there, the attribute search continues in the base\n   classes. This search of the base classes uses the C3 method\n   resolution order which behaves correctly even in the presence of\n   \'diamond\' inheritance structures where there are multiple\n   inheritance paths leading back to a common ancestor. Additional\n   details on the C3 MRO used by Python can be found in the\n   documentation accompanying the 2.3 release at\n   https://www.python.org/download/releases/2.3/mro/.\n\n   When a class attribute reference (for class "C", say) would yield a\n   class method object, it is transformed into an instance method\n   object whose "__self__" attributes is "C".  When it would yield a\n   static method object, it is transformed into the object wrapped by\n   the static method object. See section *Implementing Descriptors*\n   for another way in which attributes retrieved from a class may\n   differ from those actually contained in its "__dict__".\n\n   Class attribute assignments update the class\'s dictionary, never\n   the dictionary of a base class.\n\n   A class object can be called (see above) to yield a class instance\n   (see below).\n\n   Special attributes: "__name__" is the class name; "__module__" is\n   the module name in which the class was defined; "__dict__" is the\n   dictionary containing the class\'s namespace; "__bases__" is a tuple\n   (possibly empty or a singleton) containing the base classes, in the\n   order of their occurrence in the base class list; "__doc__" is the\n   class\'s documentation string, or None if undefined.\n\nClass instances\n   A class instance is created by calling a class object (see above).\n   A class instance has a namespace implemented as a dictionary which\n   is the first place in which attribute references are searched.\n   When an attribute is not found there, and the instance\'s class has\n   an attribute by that name, the search continues with the class\n   attributes.  If a class attribute is found that is a user-defined\n   function object, it is transformed into an instance method object\n   whose "__self__" attribute is the instance.  Static method and\n   class method objects are also transformed; see above under\n   "Classes".  See section *Implementing Descriptors* for another way\n   in which attributes of a class retrieved via its instances may\n   differ from the objects actually stored in the class\'s "__dict__".\n   If no class attribute is found, and the object\'s class has a\n   "__getattr__()" method, that is called to satisfy the lookup.\n\n   Attribute assignments and deletions update the instance\'s\n   dictionary, never a class\'s dictionary.  If the class has a\n   "__setattr__()" or "__delattr__()" method, this is called instead\n   of updating the instance dictionary directly.\n\n   Class instances can pretend to be numbers, sequences, or mappings\n   if they have methods with certain special names.  See section\n   *Special method names*.\n\n   Special attributes: "__dict__" is the attribute dictionary;\n   "__class__" is the instance\'s class.\n\nI/O objects (also known as file objects)\n   A *file object* represents an open file.  Various shortcuts are\n   available to create file objects: the "open()" built-in function,\n   and also "os.popen()", "os.fdopen()", and the "makefile()" method\n   of socket objects (and perhaps by other functions or methods\n   provided by extension modules).\n\n   The objects "sys.stdin", "sys.stdout" and "sys.stderr" are\n   initialized to file objects corresponding to the interpreter\'s\n   standard input, output and error streams; they are all open in text\n   mode and therefore follow the interface defined by the\n   "io.TextIOBase" abstract class.\n\nInternal types\n   A few types used internally by the interpreter are exposed to the\n   user. Their definitions may change with future versions of the\n   interpreter, but they are mentioned here for completeness.\n\n   Code objects\n      Code objects represent *byte-compiled* executable Python code,\n      or *bytecode*. The difference between a code object and a\n      function object is that the function object contains an explicit\n      reference to the function\'s globals (the module in which it was\n      defined), while a code object contains no context; also the\n      default argument values are stored in the function object, not\n      in the code object (because they represent values calculated at\n      run-time).  Unlike function objects, code objects are immutable\n      and contain no references (directly or indirectly) to mutable\n      objects.\n\n      Special read-only attributes: "co_name" gives the function name;\n      "co_argcount" is the number of positional arguments (including\n      arguments with default values); "co_nlocals" is the number of\n      local variables used by the function (including arguments);\n      "co_varnames" is a tuple containing the names of the local\n      variables (starting with the argument names); "co_cellvars" is a\n      tuple containing the names of local variables that are\n      referenced by nested functions; "co_freevars" is a tuple\n      containing the names of free variables; "co_code" is a string\n      representing the sequence of bytecode instructions; "co_consts"\n      is a tuple containing the literals used by the bytecode;\n      "co_names" is a tuple containing the names used by the bytecode;\n      "co_filename" is the filename from which the code was compiled;\n      "co_firstlineno" is the first line number of the function;\n      "co_lnotab" is a string encoding the mapping from bytecode\n      offsets to line numbers (for details see the source code of the\n      interpreter); "co_stacksize" is the required stack size\n      (including local variables); "co_flags" is an integer encoding a\n      number of flags for the interpreter.\n\n      The following flag bits are defined for "co_flags": bit "0x04"\n      is set if the function uses the "*arguments" syntax to accept an\n      arbitrary number of positional arguments; bit "0x08" is set if\n      the function uses the "**keywords" syntax to accept arbitrary\n      keyword arguments; bit "0x20" is set if the function is a\n      generator.\n\n      Future feature declarations ("from __future__ import division")\n      also use bits in "co_flags" to indicate whether a code object\n      was compiled with a particular feature enabled: bit "0x2000" is\n      set if the function was compiled with future division enabled;\n      bits "0x10" and "0x1000" were used in earlier versions of\n      Python.\n\n      Other bits in "co_flags" are reserved for internal use.\n\n      If a code object represents a function, the first item in\n      "co_consts" is the documentation string of the function, or\n      "None" if undefined.\n\n   Frame objects\n      Frame objects represent execution frames.  They may occur in\n      traceback objects (see below).\n\n      Special read-only attributes: "f_back" is to the previous stack\n      frame (towards the caller), or "None" if this is the bottom\n      stack frame; "f_code" is the code object being executed in this\n      frame; "f_locals" is the dictionary used to look up local\n      variables; "f_globals" is used for global variables;\n      "f_builtins" is used for built-in (intrinsic) names; "f_lasti"\n      gives the precise instruction (this is an index into the\n      bytecode string of the code object).\n\n      Special writable attributes: "f_trace", if not "None", is a\n      function called at the start of each source code line (this is\n      used by the debugger); "f_lineno" is the current line number of\n      the frame --- writing to this from within a trace function jumps\n      to the given line (only for the bottom-most frame).  A debugger\n      can implement a Jump command (aka Set Next Statement) by writing\n      to f_lineno.\n\n      Frame objects support one method:\n\n      frame.clear()\n\n         This method clears all references to local variables held by\n         the frame.  Also, if the frame belonged to a generator, the\n         generator is finalized.  This helps break reference cycles\n         involving frame objects (for example when catching an\n         exception and storing its traceback for later use).\n\n         "RuntimeError" is raised if the frame is currently executing.\n\n         New in version 3.4.\n\n   Traceback objects\n      Traceback objects represent a stack trace of an exception.  A\n      traceback object is created when an exception occurs.  When the\n      search for an exception handler unwinds the execution stack, at\n      each unwound level a traceback object is inserted in front of\n      the current traceback.  When an exception handler is entered,\n      the stack trace is made available to the program. (See section\n      *The try statement*.) It is accessible as the third item of the\n      tuple returned by "sys.exc_info()". When the program contains no\n      suitable handler, the stack trace is written (nicely formatted)\n      to the standard error stream; if the interpreter is interactive,\n      it is also made available to the user as "sys.last_traceback".\n\n      Special read-only attributes: "tb_next" is the next level in the\n      stack trace (towards the frame where the exception occurred), or\n      "None" if there is no next level; "tb_frame" points to the\n      execution frame of the current level; "tb_lineno" gives the line\n      number where the exception occurred; "tb_lasti" indicates the\n      precise instruction.  The line number and last instruction in\n      the traceback may differ from the line number of its frame\n      object if the exception occurred in a "try" statement with no\n      matching except clause or with a finally clause.\n\n   Slice objects\n      Slice objects are used to represent slices for "__getitem__()"\n      methods.  They are also created by the built-in "slice()"\n      function.\n\n      Special read-only attributes: "start" is the lower bound; "stop"\n      is the upper bound; "step" is the step value; each is "None" if\n      omitted.  These attributes can have any type.\n\n      Slice objects support one method:\n\n      slice.indices(self, length)\n\n         This method takes a single integer argument *length* and\n         computes information about the slice that the slice object\n         would describe if applied to a sequence of *length* items.\n         It returns a tuple of three integers; respectively these are\n         the *start* and *stop* indices and the *step* or stride\n         length of the slice. Missing or out-of-bounds indices are\n         handled in a manner consistent with regular slices.\n\n   Static method objects\n      Static method objects provide a way of defeating the\n      transformation of function objects to method objects described\n      above. A static method object is a wrapper around any other\n      object, usually a user-defined method object. When a static\n      method object is retrieved from a class or a class instance, the\n      object actually returned is the wrapped object, which is not\n      subject to any further transformation. Static method objects are\n      not themselves callable, although the objects they wrap usually\n      are. Static method objects are created by the built-in\n      "staticmethod()" constructor.\n\n   Class method objects\n      A class method object, like a static method object, is a wrapper\n      around another object that alters the way in which that object\n      is retrieved from classes and class instances. The behaviour of\n      class method objects upon such retrieval is described above,\n      under "User-defined methods". Class method objects are created\n      by the built-in "classmethod()" constructor.\n',
+ 'types': u'\nThe standard type hierarchy\n***************************\n\nBelow is a list of the types that are built into Python.  Extension\nmodules (written in C, Java, or other languages, depending on the\nimplementation) can define additional types.  Future versions of\nPython may add types to the type hierarchy (e.g., rational numbers,\nefficiently stored arrays of integers, etc.), although such additions\nwill often be provided via the standard library instead.\n\nSome of the type descriptions below contain a paragraph listing\n\'special attributes.\'  These are attributes that provide access to the\nimplementation and are not intended for general use.  Their definition\nmay change in the future.\n\nNone\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the built-in name "None". It\n   is used to signify the absence of a value in many situations, e.g.,\n   it is returned from functions that don\'t explicitly return\n   anything. Its truth value is false.\n\nNotImplemented\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the built-in name\n   "NotImplemented". Numeric methods and rich comparison methods\n   should return this value if they do not implement the operation for\n   the operands provided.  (The interpreter will then try the\n   reflected operation, or some other fallback, depending on the\n   operator.)  Its truth value is true.\n\n   See *Implementing the arithmetic operations* for more details.\n\nEllipsis\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the literal "..." or the\n   built-in name "Ellipsis".  Its truth value is true.\n\n"numbers.Number"\n   These are created by numeric literals and returned as results by\n   arithmetic operators and arithmetic built-in functions.  Numeric\n   objects are immutable; once created their value never changes.\n   Python numbers are of course strongly related to mathematical\n   numbers, but subject to the limitations of numerical representation\n   in computers.\n\n   Python distinguishes between integers, floating point numbers, and\n   complex numbers:\n\n   "numbers.Integral"\n      These represent elements from the mathematical set of integers\n      (positive and negative).\n\n      There are two types of integers:\n\n      Integers ("int")\n\n         These represent numbers in an unlimited range, subject to\n         available (virtual) memory only.  For the purpose of shift\n         and mask operations, a binary representation is assumed, and\n         negative numbers are represented in a variant of 2\'s\n         complement which gives the illusion of an infinite string of\n         sign bits extending to the left.\n\n      Booleans ("bool")\n         These represent the truth values False and True.  The two\n         objects representing the values "False" and "True" are the\n         only Boolean objects. The Boolean type is a subtype of the\n         integer type, and Boolean values behave like the values 0 and\n         1, respectively, in almost all contexts, the exception being\n         that when converted to a string, the strings ""False"" or\n         ""True"" are returned, respectively.\n\n      The rules for integer representation are intended to give the\n      most meaningful interpretation of shift and mask operations\n      involving negative integers.\n\n   "numbers.Real" ("float")\n      These represent machine-level double precision floating point\n      numbers. You are at the mercy of the underlying machine\n      architecture (and C or Java implementation) for the accepted\n      range and handling of overflow. Python does not support single-\n      precision floating point numbers; the savings in processor and\n      memory usage that are usually the reason for using these are\n      dwarfed by the overhead of using objects in Python, so there is\n      no reason to complicate the language with two kinds of floating\n      point numbers.\n\n   "numbers.Complex" ("complex")\n      These represent complex numbers as a pair of machine-level\n      double precision floating point numbers.  The same caveats apply\n      as for floating point numbers. The real and imaginary parts of a\n      complex number "z" can be retrieved through the read-only\n      attributes "z.real" and "z.imag".\n\nSequences\n   These represent finite ordered sets indexed by non-negative\n   numbers. The built-in function "len()" returns the number of items\n   of a sequence. When the length of a sequence is *n*, the index set\n   contains the numbers 0, 1, ..., *n*-1.  Item *i* of sequence *a* is\n   selected by "a[i]".\n\n   Sequences also support slicing: "a[i:j]" selects all items with\n   index *k* such that *i* "<=" *k* "<" *j*.  When used as an\n   expression, a slice is a sequence of the same type.  This implies\n   that the index set is renumbered so that it starts at 0.\n\n   Some sequences also support "extended slicing" with a third "step"\n   parameter: "a[i:j:k]" selects all items of *a* with index *x* where\n   "x = i + n*k", *n* ">=" "0" and *i* "<=" *x* "<" *j*.\n\n   Sequences are distinguished according to their mutability:\n\n   Immutable sequences\n      An object of an immutable sequence type cannot change once it is\n      created.  (If the object contains references to other objects,\n      these other objects may be mutable and may be changed; however,\n      the collection of objects directly referenced by an immutable\n      object cannot change.)\n\n      The following types are immutable sequences:\n\n      Strings\n         A string is a sequence of values that represent Unicode code\n         points. All the code points in the range "U+0000 - U+10FFFF"\n         can be represented in a string.  Python doesn\'t have a "char"\n         type; instead, every code point in the string is represented\n         as a string object with length "1".  The built-in function\n         "ord()" converts a code point from its string form to an\n         integer in the range "0 - 10FFFF"; "chr()" converts an\n         integer in the range "0 - 10FFFF" to the corresponding length\n         "1" string object. "str.encode()" can be used to convert a\n         "str" to "bytes" using the given text encoding, and\n         "bytes.decode()" can be used to achieve the opposite.\n\n      Tuples\n         The items of a tuple are arbitrary Python objects. Tuples of\n         two or more items are formed by comma-separated lists of\n         expressions.  A tuple of one item (a \'singleton\') can be\n         formed by affixing a comma to an expression (an expression by\n         itself does not create a tuple, since parentheses must be\n         usable for grouping of expressions).  An empty tuple can be\n         formed by an empty pair of parentheses.\n\n      Bytes\n         A bytes object is an immutable array.  The items are 8-bit\n         bytes, represented by integers in the range 0 <= x < 256.\n         Bytes literals (like "b\'abc\'") and the built-in function\n         "bytes()" can be used to construct bytes objects.  Also,\n         bytes objects can be decoded to strings via the "decode()"\n         method.\n\n   Mutable sequences\n      Mutable sequences can be changed after they are created.  The\n      subscription and slicing notations can be used as the target of\n      assignment and "del" (delete) statements.\n\n      There are currently two intrinsic mutable sequence types:\n\n      Lists\n         The items of a list are arbitrary Python objects.  Lists are\n         formed by placing a comma-separated list of expressions in\n         square brackets. (Note that there are no special cases needed\n         to form lists of length 0 or 1.)\n\n      Byte Arrays\n         A bytearray object is a mutable array. They are created by\n         the built-in "bytearray()" constructor.  Aside from being\n         mutable (and hence unhashable), byte arrays otherwise provide\n         the same interface and functionality as immutable bytes\n         objects.\n\n      The extension module "array" provides an additional example of a\n      mutable sequence type, as does the "collections" module.\n\nSet types\n   These represent unordered, finite sets of unique, immutable\n   objects. As such, they cannot be indexed by any subscript. However,\n   they can be iterated over, and the built-in function "len()"\n   returns the number of items in a set. Common uses for sets are fast\n   membership testing, removing duplicates from a sequence, and\n   computing mathematical operations such as intersection, union,\n   difference, and symmetric difference.\n\n   For set elements, the same immutability rules apply as for\n   dictionary keys. Note that numeric types obey the normal rules for\n   numeric comparison: if two numbers compare equal (e.g., "1" and\n   "1.0"), only one of them can be contained in a set.\n\n   There are currently two intrinsic set types:\n\n   Sets\n      These represent a mutable set. They are created by the built-in\n      "set()" constructor and can be modified afterwards by several\n      methods, such as "add()".\n\n   Frozen sets\n      These represent an immutable set.  They are created by the\n      built-in "frozenset()" constructor.  As a frozenset is immutable\n      and *hashable*, it can be used again as an element of another\n      set, or as a dictionary key.\n\nMappings\n   These represent finite sets of objects indexed by arbitrary index\n   sets. The subscript notation "a[k]" selects the item indexed by "k"\n   from the mapping "a"; this can be used in expressions and as the\n   target of assignments or "del" statements. The built-in function\n   "len()" returns the number of items in a mapping.\n\n   There is currently a single intrinsic mapping type:\n\n   Dictionaries\n      These represent finite sets of objects indexed by nearly\n      arbitrary values.  The only types of values not acceptable as\n      keys are values containing lists or dictionaries or other\n      mutable types that are compared by value rather than by object\n      identity, the reason being that the efficient implementation of\n      dictionaries requires a key\'s hash value to remain constant.\n      Numeric types used for keys obey the normal rules for numeric\n      comparison: if two numbers compare equal (e.g., "1" and "1.0")\n      then they can be used interchangeably to index the same\n      dictionary entry.\n\n      Dictionaries are mutable; they can be created by the "{...}"\n      notation (see section *Dictionary displays*).\n\n      The extension modules "dbm.ndbm" and "dbm.gnu" provide\n      additional examples of mapping types, as does the "collections"\n      module.\n\nCallable types\n   These are the types to which the function call operation (see\n   section *Calls*) can be applied:\n\n   User-defined functions\n      A user-defined function object is created by a function\n      definition (see section *Function definitions*).  It should be\n      called with an argument list containing the same number of items\n      as the function\'s formal parameter list.\n\n      Special attributes:\n\n      +---------------------------+---------------------------------+-------------+\n      | Attribute                 | Meaning                         |             |\n      +===========================+=================================+=============+\n      | "__doc__"                 | The function\'s documentation    | Writable    |\n      |                           | string, or "None" if            |             |\n      |                           | unavailable; not inherited by   |             |\n      |                           | subclasses                      |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__name__"                | The function\'s name             | Writable    |\n      +---------------------------+---------------------------------+-------------+\n      | "__qualname__"            | The function\'s *qualified name* | Writable    |\n      |                           | New in version 3.3.             |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__module__"              | The name of the module the      | Writable    |\n      |                           | function was defined in, or     |             |\n      |                           | "None" if unavailable.          |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__defaults__"            | A tuple containing default      | Writable    |\n      |                           | argument values for those       |             |\n      |                           | arguments that have defaults,   |             |\n      |                           | or "None" if no arguments have  |             |\n      |                           | a default value                 |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__code__"                | The code object representing    | Writable    |\n      |                           | the compiled function body.     |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__globals__"             | A reference to the dictionary   | Read-only   |\n      |                           | that holds the function\'s       |             |\n      |                           | global variables --- the global |             |\n      |                           | namespace of the module in      |             |\n      |                           | which the function was defined. |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__dict__"                | The namespace supporting        | Writable    |\n      |                           | arbitrary function attributes.  |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__closure__"             | "None" or a tuple of cells that | Read-only   |\n      |                           | contain bindings for the        |             |\n      |                           | function\'s free variables.      |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__annotations__"         | A dict containing annotations   | Writable    |\n      |                           | of parameters.  The keys of the |             |\n      |                           | dict are the parameter names,   |             |\n      |                           | and "\'return\'" for the return   |             |\n      |                           | annotation, if provided.        |             |\n      +---------------------------+---------------------------------+-------------+\n      | "__kwdefaults__"          | A dict containing defaults for  | Writable    |\n      |                           | keyword-only parameters.        |             |\n      +---------------------------+---------------------------------+-------------+\n\n      Most of the attributes labelled "Writable" check the type of the\n      assigned value.\n\n      Function objects also support getting and setting arbitrary\n      attributes, which can be used, for example, to attach metadata\n      to functions.  Regular attribute dot-notation is used to get and\n      set such attributes. *Note that the current implementation only\n      supports function attributes on user-defined functions. Function\n      attributes on built-in functions may be supported in the\n      future.*\n\n      Additional information about a function\'s definition can be\n      retrieved from its code object; see the description of internal\n      types below.\n\n   Instance methods\n      An instance method object combines a class, a class instance and\n      any callable object (normally a user-defined function).\n\n      Special read-only attributes: "__self__" is the class instance\n      object, "__func__" is the function object; "__doc__" is the\n      method\'s documentation (same as "__func__.__doc__"); "__name__"\n      is the method name (same as "__func__.__name__"); "__module__"\n      is the name of the module the method was defined in, or "None"\n      if unavailable.\n\n      Methods also support accessing (but not setting) the arbitrary\n      function attributes on the underlying function object.\n\n      User-defined method objects may be created when getting an\n      attribute of a class (perhaps via an instance of that class), if\n      that attribute is a user-defined function object or a class\n      method object.\n\n      When an instance method object is created by retrieving a user-\n      defined function object from a class via one of its instances,\n      its "__self__" attribute is the instance, and the method object\n      is said to be bound.  The new method\'s "__func__" attribute is\n      the original function object.\n\n      When a user-defined method object is created by retrieving\n      another method object from a class or instance, the behaviour is\n      the same as for a function object, except that the "__func__"\n      attribute of the new instance is not the original method object\n      but its "__func__" attribute.\n\n      When an instance method object is created by retrieving a class\n      method object from a class or instance, its "__self__" attribute\n      is the class itself, and its "__func__" attribute is the\n      function object underlying the class method.\n\n      When an instance method object is called, the underlying\n      function ("__func__") is called, inserting the class instance\n      ("__self__") in front of the argument list.  For instance, when\n      "C" is a class which contains a definition for a function "f()",\n      and "x" is an instance of "C", calling "x.f(1)" is equivalent to\n      calling "C.f(x, 1)".\n\n      When an instance method object is derived from a class method\n      object, the "class instance" stored in "__self__" will actually\n      be the class itself, so that calling either "x.f(1)" or "C.f(1)"\n      is equivalent to calling "f(C,1)" where "f" is the underlying\n      function.\n\n      Note that the transformation from function object to instance\n      method object happens each time the attribute is retrieved from\n      the instance.  In some cases, a fruitful optimization is to\n      assign the attribute to a local variable and call that local\n      variable. Also notice that this transformation only happens for\n      user-defined functions; other callable objects (and all non-\n      callable objects) are retrieved without transformation.  It is\n      also important to note that user-defined functions which are\n      attributes of a class instance are not converted to bound\n      methods; this *only* happens when the function is an attribute\n      of the class.\n\n   Generator functions\n      A function or method which uses the "yield" statement (see\n      section *The yield statement*) is called a *generator function*.\n      Such a function, when called, always returns an iterator object\n      which can be used to execute the body of the function:  calling\n      the iterator\'s "iterator.__next__()" method will cause the\n      function to execute until it provides a value using the "yield"\n      statement.  When the function executes a "return" statement or\n      falls off the end, a "StopIteration" exception is raised and the\n      iterator will have reached the end of the set of values to be\n      returned.\n\n   Coroutine functions\n      A function or method which is defined using "async def" is\n      called a *coroutine function*.  Such a function, when called,\n      returns a *coroutine* object.  It may contain "await"\n      expressions, as well as "async with" and "async for" statements.\n      See also the *Coroutine Objects* section.\n\n   Built-in functions\n      A built-in function object is a wrapper around a C function.\n      Examples of built-in functions are "len()" and "math.sin()"\n      ("math" is a standard built-in module). The number and type of\n      the arguments are determined by the C function. Special read-\n      only attributes: "__doc__" is the function\'s documentation\n      string, or "None" if unavailable; "__name__" is the function\'s\n      name; "__self__" is set to "None" (but see the next item);\n      "__module__" is the name of the module the function was defined\n      in or "None" if unavailable.\n\n   Built-in methods\n      This is really a different disguise of a built-in function, this\n      time containing an object passed to the C function as an\n      implicit extra argument.  An example of a built-in method is\n      "alist.append()", assuming *alist* is a list object. In this\n      case, the special read-only attribute "__self__" is set to the\n      object denoted by *alist*.\n\n   Classes\n      Classes are callable.  These objects normally act as factories\n      for new instances of themselves, but variations are possible for\n      class types that override "__new__()".  The arguments of the\n      call are passed to "__new__()" and, in the typical case, to\n      "__init__()" to initialize the new instance.\n\n   Class Instances\n      Instances of arbitrary classes can be made callable by defining\n      a "__call__()" method in their class.\n\nModules\n   Modules are a basic organizational unit of Python code, and are\n   created by the *import system* as invoked either by the "import"\n   statement (see "import"), or by calling functions such as\n   "importlib.import_module()" and built-in "__import__()".  A module\n   object has a namespace implemented by a dictionary object (this is\n   the dictionary referenced by the "__globals__" attribute of\n   functions defined in the module).  Attribute references are\n   translated to lookups in this dictionary, e.g., "m.x" is equivalent\n   to "m.__dict__["x"]". A module object does not contain the code\n   object used to initialize the module (since it isn\'t needed once\n   the initialization is done).\n\n   Attribute assignment updates the module\'s namespace dictionary,\n   e.g., "m.x = 1" is equivalent to "m.__dict__["x"] = 1".\n\n   Special read-only attribute: "__dict__" is the module\'s namespace\n   as a dictionary object.\n\n   **CPython implementation detail:** Because of the way CPython\n   clears module dictionaries, the module dictionary will be cleared\n   when the module falls out of scope even if the dictionary still has\n   live references.  To avoid this, copy the dictionary or keep the\n   module around while using its dictionary directly.\n\n   Predefined (writable) attributes: "__name__" is the module\'s name;\n   "__doc__" is the module\'s documentation string, or "None" if\n   unavailable; "__file__" is the pathname of the file from which the\n   module was loaded, if it was loaded from a file. The "__file__"\n   attribute may be missing for certain types of modules, such as C\n   modules that are statically linked into the interpreter; for\n   extension modules loaded dynamically from a shared library, it is\n   the pathname of the shared library file.\n\nCustom classes\n   Custom class types are typically created by class definitions (see\n   section *Class definitions*).  A class has a namespace implemented\n   by a dictionary object. Class attribute references are translated\n   to lookups in this dictionary, e.g., "C.x" is translated to\n   "C.__dict__["x"]" (although there are a number of hooks which allow\n   for other means of locating attributes). When the attribute name is\n   not found there, the attribute search continues in the base\n   classes. This search of the base classes uses the C3 method\n   resolution order which behaves correctly even in the presence of\n   \'diamond\' inheritance structures where there are multiple\n   inheritance paths leading back to a common ancestor. Additional\n   details on the C3 MRO used by Python can be found in the\n   documentation accompanying the 2.3 release at\n   https://www.python.org/download/releases/2.3/mro/.\n\n   When a class attribute reference (for class "C", say) would yield a\n   class method object, it is transformed into an instance method\n   object whose "__self__" attributes is "C".  When it would yield a\n   static method object, it is transformed into the object wrapped by\n   the static method object. See section *Implementing Descriptors*\n   for another way in which attributes retrieved from a class may\n   differ from those actually contained in its "__dict__".\n\n   Class attribute assignments update the class\'s dictionary, never\n   the dictionary of a base class.\n\n   A class object can be called (see above) to yield a class instance\n   (see below).\n\n   Special attributes: "__name__" is the class name; "__module__" is\n   the module name in which the class was defined; "__dict__" is the\n   dictionary containing the class\'s namespace; "__bases__" is a tuple\n   (possibly a singleton) containing the base classes, in the order of\n   their occurrence in the base class list; "__doc__" is the class\'s\n   documentation string, or "None" if undefined.\n\nClass instances\n   A class instance is created by calling a class object (see above).\n   A class instance has a namespace implemented as a dictionary which\n   is the first place in which attribute references are searched.\n   When an attribute is not found there, and the instance\'s class has\n   an attribute by that name, the search continues with the class\n   attributes.  If a class attribute is found that is a user-defined\n   function object, it is transformed into an instance method object\n   whose "__self__" attribute is the instance.  Static method and\n   class method objects are also transformed; see above under\n   "Classes".  See section *Implementing Descriptors* for another way\n   in which attributes of a class retrieved via its instances may\n   differ from the objects actually stored in the class\'s "__dict__".\n   If no class attribute is found, and the object\'s class has a\n   "__getattr__()" method, that is called to satisfy the lookup.\n\n   Attribute assignments and deletions update the instance\'s\n   dictionary, never a class\'s dictionary.  If the class has a\n   "__setattr__()" or "__delattr__()" method, this is called instead\n   of updating the instance dictionary directly.\n\n   Class instances can pretend to be numbers, sequences, or mappings\n   if they have methods with certain special names.  See section\n   *Special method names*.\n\n   Special attributes: "__dict__" is the attribute dictionary;\n   "__class__" is the instance\'s class.\n\nI/O objects (also known as file objects)\n   A *file object* represents an open file.  Various shortcuts are\n   available to create file objects: the "open()" built-in function,\n   and also "os.popen()", "os.fdopen()", and the "makefile()" method\n   of socket objects (and perhaps by other functions or methods\n   provided by extension modules).\n\n   The objects "sys.stdin", "sys.stdout" and "sys.stderr" are\n   initialized to file objects corresponding to the interpreter\'s\n   standard input, output and error streams; they are all open in text\n   mode and therefore follow the interface defined by the\n   "io.TextIOBase" abstract class.\n\nInternal types\n   A few types used internally by the interpreter are exposed to the\n   user. Their definitions may change with future versions of the\n   interpreter, but they are mentioned here for completeness.\n\n   Code objects\n      Code objects represent *byte-compiled* executable Python code,\n      or *bytecode*. The difference between a code object and a\n      function object is that the function object contains an explicit\n      reference to the function\'s globals (the module in which it was\n      defined), while a code object contains no context; also the\n      default argument values are stored in the function object, not\n      in the code object (because they represent values calculated at\n      run-time).  Unlike function objects, code objects are immutable\n      and contain no references (directly or indirectly) to mutable\n      objects.\n\n      Special read-only attributes: "co_name" gives the function name;\n      "co_argcount" is the number of positional arguments (including\n      arguments with default values); "co_nlocals" is the number of\n      local variables used by the function (including arguments);\n      "co_varnames" is a tuple containing the names of the local\n      variables (starting with the argument names); "co_cellvars" is a\n      tuple containing the names of local variables that are\n      referenced by nested functions; "co_freevars" is a tuple\n      containing the names of free variables; "co_code" is a string\n      representing the sequence of bytecode instructions; "co_consts"\n      is a tuple containing the literals used by the bytecode;\n      "co_names" is a tuple containing the names used by the bytecode;\n      "co_filename" is the filename from which the code was compiled;\n      "co_firstlineno" is the first line number of the function;\n      "co_lnotab" is a string encoding the mapping from bytecode\n      offsets to line numbers (for details see the source code of the\n      interpreter); "co_stacksize" is the required stack size\n      (including local variables); "co_flags" is an integer encoding a\n      number of flags for the interpreter.\n\n      The following flag bits are defined for "co_flags": bit "0x04"\n      is set if the function uses the "*arguments" syntax to accept an\n      arbitrary number of positional arguments; bit "0x08" is set if\n      the function uses the "**keywords" syntax to accept arbitrary\n      keyword arguments; bit "0x20" is set if the function is a\n      generator.\n\n      Future feature declarations ("from __future__ import division")\n      also use bits in "co_flags" to indicate whether a code object\n      was compiled with a particular feature enabled: bit "0x2000" is\n      set if the function was compiled with future division enabled;\n      bits "0x10" and "0x1000" were used in earlier versions of\n      Python.\n\n      Other bits in "co_flags" are reserved for internal use.\n\n      If a code object represents a function, the first item in\n      "co_consts" is the documentation string of the function, or\n      "None" if undefined.\n\n   Frame objects\n      Frame objects represent execution frames.  They may occur in\n      traceback objects (see below).\n\n      Special read-only attributes: "f_back" is to the previous stack\n      frame (towards the caller), or "None" if this is the bottom\n      stack frame; "f_code" is the code object being executed in this\n      frame; "f_locals" is the dictionary used to look up local\n      variables; "f_globals" is used for global variables;\n      "f_builtins" is used for built-in (intrinsic) names; "f_lasti"\n      gives the precise instruction (this is an index into the\n      bytecode string of the code object).\n\n      Special writable attributes: "f_trace", if not "None", is a\n      function called at the start of each source code line (this is\n      used by the debugger); "f_lineno" is the current line number of\n      the frame --- writing to this from within a trace function jumps\n      to the given line (only for the bottom-most frame).  A debugger\n      can implement a Jump command (aka Set Next Statement) by writing\n      to f_lineno.\n\n      Frame objects support one method:\n\n      frame.clear()\n\n         This method clears all references to local variables held by\n         the frame.  Also, if the frame belonged to a generator, the\n         generator is finalized.  This helps break reference cycles\n         involving frame objects (for example when catching an\n         exception and storing its traceback for later use).\n\n         "RuntimeError" is raised if the frame is currently executing.\n\n         New in version 3.4.\n\n   Traceback objects\n      Traceback objects represent a stack trace of an exception.  A\n      traceback object is created when an exception occurs.  When the\n      search for an exception handler unwinds the execution stack, at\n      each unwound level a traceback object is inserted in front of\n      the current traceback.  When an exception handler is entered,\n      the stack trace is made available to the program. (See section\n      *The try statement*.) It is accessible as the third item of the\n      tuple returned by "sys.exc_info()". When the program contains no\n      suitable handler, the stack trace is written (nicely formatted)\n      to the standard error stream; if the interpreter is interactive,\n      it is also made available to the user as "sys.last_traceback".\n\n      Special read-only attributes: "tb_next" is the next level in the\n      stack trace (towards the frame where the exception occurred), or\n      "None" if there is no next level; "tb_frame" points to the\n      execution frame of the current level; "tb_lineno" gives the line\n      number where the exception occurred; "tb_lasti" indicates the\n      precise instruction.  The line number and last instruction in\n      the traceback may differ from the line number of its frame\n      object if the exception occurred in a "try" statement with no\n      matching except clause or with a finally clause.\n\n   Slice objects\n      Slice objects are used to represent slices for "__getitem__()"\n      methods.  They are also created by the built-in "slice()"\n      function.\n\n      Special read-only attributes: "start" is the lower bound; "stop"\n      is the upper bound; "step" is the step value; each is "None" if\n      omitted.  These attributes can have any type.\n\n      Slice objects support one method:\n\n      slice.indices(self, length)\n\n         This method takes a single integer argument *length* and\n         computes information about the slice that the slice object\n         would describe if applied to a sequence of *length* items.\n         It returns a tuple of three integers; respectively these are\n         the *start* and *stop* indices and the *step* or stride\n         length of the slice. Missing or out-of-bounds indices are\n         handled in a manner consistent with regular slices.\n\n   Static method objects\n      Static method objects provide a way of defeating the\n      transformation of function objects to method objects described\n      above. A static method object is a wrapper around any other\n      object, usually a user-defined method object. When a static\n      method object is retrieved from a class or a class instance, the\n      object actually returned is the wrapped object, which is not\n      subject to any further transformation. Static method objects are\n      not themselves callable, although the objects they wrap usually\n      are. Static method objects are created by the built-in\n      "staticmethod()" constructor.\n\n   Class method objects\n      A class method object, like a static method object, is a wrapper\n      around another object that alters the way in which that object\n      is retrieved from classes and class instances. The behaviour of\n      class method objects upon such retrieval is described above,\n      under "User-defined methods". Class method objects are created\n      by the built-in "classmethod()" constructor.\n',
  'typesfunctions': u'\nFunctions\n*********\n\nFunction objects are created by function definitions.  The only\noperation on a function object is to call it: "func(argument-list)".\n\nThere are really two flavors of function objects: built-in functions\nand user-defined functions.  Both support the same operation (to call\nthe function), but the implementation is different, hence the\ndifferent object types.\n\nSee *Function definitions* for more information.\n',
  'typesmapping': u'\nMapping Types --- "dict"\n************************\n\nA *mapping* object maps *hashable* values to arbitrary objects.\nMappings are mutable objects.  There is currently only one standard\nmapping type, the *dictionary*.  (For other containers see the built-\nin "list", "set", and "tuple" classes, and the "collections" module.)\n\nA dictionary\'s keys are *almost* arbitrary values.  Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys.  Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as "1" and "1.0") then they can be used interchangeably to index\nthe same dictionary entry.  (Note however, that since computers store\nfloating-point numbers as approximations it is usually unwise to use\nthem as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of "key:\nvalue" pairs within braces, for example: "{\'jack\': 4098, \'sjoerd\':\n4127}" or "{4098: \'jack\', 4127: \'sjoerd\'}", or by the "dict"\nconstructor.\n\nclass class dict(**kwarg)\nclass class dict(mapping, **kwarg)\nclass class dict(iterable, **kwarg)\n\n   Return a new dictionary initialized from an optional positional\n   argument and a possibly empty set of keyword arguments.\n\n   If no positional argument is given, an empty dictionary is created.\n   If a positional argument is given and it is a mapping object, a\n   dictionary is created with the same key-value pairs as the mapping\n   object.  Otherwise, the positional argument must be an *iterable*\n   object.  Each item in the iterable must itself be an iterable with\n   exactly two objects.  The first object of each item becomes a key\n   in the new dictionary, and the second object the corresponding\n   value.  If a key occurs more than once, the last value for that key\n   becomes the corresponding value in the new dictionary.\n\n   If keyword arguments are given, the keyword arguments and their\n   values are added to the dictionary created from the positional\n   argument.  If a key being added is already present, the value from\n   the keyword argument replaces the value from the positional\n   argument.\n\n   To illustrate, the following examples all return a dictionary equal\n   to "{"one": 1, "two": 2, "three": 3}":\n\n      >>> a = dict(one=1, two=2, three=3)\n      >>> b = {\'one\': 1, \'two\': 2, \'three\': 3}\n      >>> c = dict(zip([\'one\', \'two\', \'three\'], [1, 2, 3]))\n      >>> d = dict([(\'two\', 2), (\'one\', 1), (\'three\', 3)])\n      >>> e = dict({\'three\': 3, \'one\': 1, \'two\': 2})\n      >>> a == b == c == d == e\n      True\n\n   Providing keyword arguments as in the first example only works for\n   keys that are valid Python identifiers.  Otherwise, any valid keys\n   can be used.\n\n   These are the operations that dictionaries support (and therefore,\n   custom mapping types should support too):\n\n   len(d)\n\n      Return the number of items in the dictionary *d*.\n\n   d[key]\n\n      Return the item of *d* with key *key*.  Raises a "KeyError" if\n      *key* is not in the map.\n\n      If a subclass of dict defines a method "__missing__()" and *key*\n      is not present, the "d[key]" operation calls that method with\n      the key *key* as argument.  The "d[key]" operation then returns\n      or raises whatever is returned or raised by the\n      "__missing__(key)" call. No other operations or methods invoke\n      "__missing__()". If "__missing__()" is not defined, "KeyError"\n      is raised. "__missing__()" must be a method; it cannot be an\n      instance variable:\n\n         >>> class Counter(dict):\n         ...     def __missing__(self, key):\n         ...         return 0\n         >>> c = Counter()\n         >>> c[\'red\']\n         0\n         >>> c[\'red\'] += 1\n         >>> c[\'red\']\n         1\n\n      The example above shows part of the implementation of\n      "collections.Counter".  A different "__missing__" method is used\n      by "collections.defaultdict".\n\n   d[key] = value\n\n      Set "d[key]" to *value*.\n\n   del d[key]\n\n      Remove "d[key]" from *d*.  Raises a "KeyError" if *key* is not\n      in the map.\n\n   key in d\n\n      Return "True" if *d* has a key *key*, else "False".\n\n   key not in d\n\n      Equivalent to "not key in d".\n\n   iter(d)\n\n      Return an iterator over the keys of the dictionary.  This is a\n      shortcut for "iter(d.keys())".\n\n   clear()\n\n      Remove all items from the dictionary.\n\n   copy()\n\n      Return a shallow copy of the dictionary.\n\n   classmethod fromkeys(seq[, value])\n\n      Create a new dictionary with keys from *seq* and values set to\n      *value*.\n\n      "fromkeys()" is a class method that returns a new dictionary.\n      *value* defaults to "None".\n\n   get(key[, default])\n\n      Return the value for *key* if *key* is in the dictionary, else\n      *default*. If *default* is not given, it defaults to "None", so\n      that this method never raises a "KeyError".\n\n   items()\n\n      Return a new view of the dictionary\'s items ("(key, value)"\n      pairs). See the *documentation of view objects*.\n\n   keys()\n\n      Return a new view of the dictionary\'s keys.  See the\n      *documentation of view objects*.\n\n   pop(key[, default])\n\n      If *key* is in the dictionary, remove it and return its value,\n      else return *default*.  If *default* is not given and *key* is\n      not in the dictionary, a "KeyError" is raised.\n\n   popitem()\n\n      Remove and return an arbitrary "(key, value)" pair from the\n      dictionary.\n\n      "popitem()" is useful to destructively iterate over a\n      dictionary, as often used in set algorithms.  If the dictionary\n      is empty, calling "popitem()" raises a "KeyError".\n\n   setdefault(key[, default])\n\n      If *key* is in the dictionary, return its value.  If not, insert\n      *key* with a value of *default* and return *default*.  *default*\n      defaults to "None".\n\n   update([other])\n\n      Update the dictionary with the key/value pairs from *other*,\n      overwriting existing keys.  Return "None".\n\n      "update()" accepts either another dictionary object or an\n      iterable of key/value pairs (as tuples or other iterables of\n      length two).  If keyword arguments are specified, the dictionary\n      is then updated with those key/value pairs: "d.update(red=1,\n      blue=2)".\n\n   values()\n\n      Return a new view of the dictionary\'s values.  See the\n      *documentation of view objects*.\n\n   Dictionaries compare equal if and only if they have the same "(key,\n   value)" pairs. Order comparisons (\'<\', \'<=\', \'>=\', \'>\') raise\n   "TypeError".\n\nSee also: "types.MappingProxyType" can be used to create a read-only\n  view of a "dict".\n\n\nDictionary view objects\n=======================\n\nThe objects returned by "dict.keys()", "dict.values()" and\n"dict.items()" are *view objects*.  They provide a dynamic view on the\ndictionary\'s entries, which means that when the dictionary changes,\nthe view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n   Return the number of entries in the dictionary.\n\niter(dictview)\n\n   Return an iterator over the keys, values or items (represented as\n   tuples of "(key, value)") in the dictionary.\n\n   Keys and values are iterated over in an arbitrary order which is\n   non-random, varies across Python implementations, and depends on\n   the dictionary\'s history of insertions and deletions. If keys,\n   values and items views are iterated over with no intervening\n   modifications to the dictionary, the order of items will directly\n   correspond.  This allows the creation of "(value, key)" pairs using\n   "zip()": "pairs = zip(d.values(), d.keys())".  Another way to\n   create the same list is "pairs = [(v, k) for (k, v) in d.items()]".\n\n   Iterating views while adding or deleting entries in the dictionary\n   may raise a "RuntimeError" or fail to iterate over all entries.\n\nx in dictview\n\n   Return "True" if *x* is in the underlying dictionary\'s keys, values\n   or items (in the latter case, *x* should be a "(key, value)"\n   tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that "(key, value)" pairs are unique\nand hashable, then the items view is also set-like.  (Values views are\nnot treated as set-like since the entries are generally not unique.)\nFor set-like views, all of the operations defined for the abstract\nbase class "collections.abc.Set" are available (for example, "==",\n"<", or "^").\n\nAn example of dictionary view usage:\n\n   >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n   >>> keys = dishes.keys()\n   >>> values = dishes.values()\n\n   >>> # iteration\n   >>> n = 0\n   >>> for val in values:\n   ...     n += val\n   >>> print(n)\n   504\n\n   >>> # keys and values are iterated over in the same order\n   >>> list(keys)\n   [\'eggs\', \'bacon\', \'sausage\', \'spam\']\n   >>> list(values)\n   [2, 1, 1, 500]\n\n   >>> # view objects are dynamic and reflect dict changes\n   >>> del dishes[\'eggs\']\n   >>> del dishes[\'sausage\']\n   >>> list(keys)\n   [\'spam\', \'bacon\']\n\n   >>> # set operations\n   >>> keys & {\'eggs\', \'bacon\', \'salad\'}\n   {\'bacon\'}\n   >>> keys ^ {\'sausage\', \'juice\'}\n   {\'juice\', \'sausage\', \'bacon\', \'spam\'}\n',
  'typesmethods': u'\nMethods\n*******\n\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as "append()" on lists)\nand class instance methods.  Built-in methods are described with the\ntypes that support them.\n\nIf you access a method (a function defined in a class namespace)\nthrough an instance, you get a special object: a *bound method* (also\ncalled *instance method*) object. When called, it will add the "self"\nargument to the argument list.  Bound methods have two special read-\nonly attributes: "m.__self__" is the object on which the method\noperates, and "m.__func__" is the function implementing the method.\nCalling "m(arg-1, arg-2, ..., arg-n)" is completely equivalent to\ncalling "m.__func__(m.__self__, arg-1, arg-2, ..., arg-n)".\n\nLike function objects, bound method objects support getting arbitrary\nattributes.  However, since method attributes are actually stored on\nthe underlying function object ("meth.__func__"), setting method\nattributes on bound methods is disallowed.  Attempting to set an\nattribute on a method results in an "AttributeError" being raised.  In\norder to set a method attribute, you need to explicitly set it on the\nunderlying function object:\n\n   >>> class C:\n   ...     def method(self):\n   ...         pass\n   ...\n   >>> c = C()\n   >>> c.method.whoami = \'my name is method\'  # can\'t set on the method\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   AttributeError: \'method\' object has no attribute \'whoami\'\n   >>> c.method.__func__.whoami = \'my name is method\'\n   >>> c.method.whoami\n   \'my name is method\'\n\nSee *The standard type hierarchy* for more information.\n',
  'typesmodules': u'\nModules\n*******\n\nThe only special operation on a module is attribute access: "m.name",\nwhere *m* is a module and *name* accesses a name defined in *m*\'s\nsymbol table. Module attributes can be assigned to.  (Note that the\n"import" statement is not, strictly speaking, an operation on a module\nobject; "import foo" does not require a module object named *foo* to\nexist, rather it requires an (external) *definition* for a module\nnamed *foo* somewhere.)\n\nA special attribute of every module is "__dict__". This is the\ndictionary containing the module\'s symbol table. Modifying this\ndictionary will actually change the module\'s symbol table, but direct\nassignment to the "__dict__" attribute is not possible (you can write\n"m.__dict__[\'a\'] = 1", which defines "m.a" to be "1", but you can\'t\nwrite "m.__dict__ = {}").  Modifying "__dict__" directly is not\nrecommended.\n\nModules built into the interpreter are written like this: "<module\n\'sys\' (built-in)>".  If loaded from a file, they are written as\n"<module \'os\' from \'/usr/local/lib/pythonX.Y/os.pyc\'>".\n',
- 'typesseq': u'\nSequence Types --- "list", "tuple", "range"\n*******************************************\n\nThere are three basic sequence types: lists, tuples, and range\nobjects. Additional sequence types tailored for processing of *binary\ndata* and *text strings* are described in dedicated sections.\n\n\nCommon Sequence Operations\n==========================\n\nThe operations in the following table are supported by most sequence\ntypes, both mutable and immutable. The "collections.abc.Sequence" ABC\nis provided to make it easier to correctly implement these operations\non custom sequence types.\n\nThis table lists the sequence operations sorted in ascending priority.\nIn the table, *s* and *t* are sequences of the same type, *n*, *i*,\n*j* and *k* are integers and *x* is an arbitrary object that meets any\ntype and value restrictions imposed by *s*.\n\nThe "in" and "not in" operations have the same priorities as the\ncomparison operations. The "+" (concatenation) and "*" (repetition)\noperations have the same priority as the corresponding numeric\noperations.\n\n+----------------------------+----------------------------------+------------+\n| Operation                  | Result                           | Notes      |\n+============================+==================================+============+\n| "x in s"                   | "True" if an item of *s* is      | (1)        |\n|                            | equal to *x*, else "False"       |            |\n+----------------------------+----------------------------------+------------+\n| "x not in s"               | "False" if an item of *s* is     | (1)        |\n|                            | equal to *x*, else "True"        |            |\n+----------------------------+----------------------------------+------------+\n| "s + t"                    | the concatenation of *s* and *t* | (6)(7)     |\n+----------------------------+----------------------------------+------------+\n| "s * n" or "n * s"         | equivalent to adding *s* to      | (2)(7)     |\n|                            | itself *n* times                 |            |\n+----------------------------+----------------------------------+------------+\n| "s[i]"                     | *i*th item of *s*, origin 0      | (3)        |\n+----------------------------+----------------------------------+------------+\n| "s[i:j]"                   | slice of *s* from *i* to *j*     | (3)(4)     |\n+----------------------------+----------------------------------+------------+\n| "s[i:j:k]"                 | slice of *s* from *i* to *j*     | (3)(5)     |\n|                            | with step *k*                    |            |\n+----------------------------+----------------------------------+------------+\n| "len(s)"                   | length of *s*                    |            |\n+----------------------------+----------------------------------+------------+\n| "min(s)"                   | smallest item of *s*             |            |\n+----------------------------+----------------------------------+------------+\n| "max(s)"                   | largest item of *s*              |            |\n+----------------------------+----------------------------------+------------+\n| "s.index(x[, i[, j]])"     | index of the first occurrence of | (8)        |\n|                            | *x* in *s* (at or after index    |            |\n|                            | *i* and before index *j*)        |            |\n+----------------------------+----------------------------------+------------+\n| "s.count(x)"               | total number of occurrences of   |            |\n|                            | *x* in *s*                       |            |\n+----------------------------+----------------------------------+------------+\n\nSequences of the same type also support comparisons.  In particular,\ntuples and lists are compared lexicographically by comparing\ncorresponding elements. This means that to compare equal, every\nelement must compare equal and the two sequences must be of the same\ntype and have the same length.  (For full details see *Comparisons* in\nthe language reference.)\n\nNotes:\n\n1. While the "in" and "not in" operations are used only for simple\n   containment testing in the general case, some specialised sequences\n   (such as "str", "bytes" and "bytearray") also use them for\n   subsequence testing:\n\n      >>> "gg" in "eggs"\n      True\n\n2. Values of *n* less than "0" are treated as "0" (which yields an\n   empty sequence of the same type as *s*).  Note that items in the\n   sequence *s* are not copied; they are referenced multiple times.\n   This often haunts new Python programmers; consider:\n\n      >>> lists = [[]] * 3\n      >>> lists\n      [[], [], []]\n      >>> lists[0].append(3)\n      >>> lists\n      [[3], [3], [3]]\n\n   What has happened is that "[[]]" is a one-element list containing\n   an empty list, so all three elements of "[[]] * 3" are references\n   to this single empty list.  Modifying any of the elements of\n   "lists" modifies this single list. You can create a list of\n   different lists this way:\n\n      >>> lists = [[] for i in range(3)]\n      >>> lists[0].append(3)\n      >>> lists[1].append(5)\n      >>> lists[2].append(7)\n      >>> lists\n      [[3], [5], [7]]\n\n   Further explanation is available in the FAQ entry *How do I create\n   a multidimensional list?*.\n\n3. If *i* or *j* is negative, the index is relative to the end of\n   the string: "len(s) + i" or "len(s) + j" is substituted.  But note\n   that "-0" is still "0".\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n   items with index *k* such that "i <= k < j".  If *i* or *j* is\n   greater than "len(s)", use "len(s)".  If *i* is omitted or "None",\n   use "0".  If *j* is omitted or "None", use "len(s)".  If *i* is\n   greater than or equal to *j*, the slice is empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n   sequence of items with index  "x = i + n*k" such that "0 <= n <\n   (j-i)/k".  In other words, the indices are "i", "i+k", "i+2*k",\n   "i+3*k" and so on, stopping when *j* is reached (but never\n   including *j*).  If *i* or *j* is greater than "len(s)", use\n   "len(s)".  If *i* or *j* are omitted or "None", they become "end"\n   values (which end depends on the sign of *k*).  Note, *k* cannot be\n   zero. If *k* is "None", it is treated like "1".\n\n6. Concatenating immutable sequences always results in a new\n   object. This means that building up a sequence by repeated\n   concatenation will have a quadratic runtime cost in the total\n   sequence length. To get a linear runtime cost, you must switch to\n   one of the alternatives below:\n\n   * if concatenating "str" objects, you can build a list and use\n     "str.join()" at the end or else write to an "io.StringIO"\n     instance and retrieve its value when complete\n\n   * if concatenating "bytes" objects, you can similarly use\n     "bytes.join()" or "io.BytesIO", or you can do in-place\n     concatenation with a "bytearray" object.  "bytearray" objects are\n     mutable and have an efficient overallocation mechanism\n\n   * if concatenating "tuple" objects, extend a "list" instead\n\n   * for other types, investigate the relevant class documentation\n\n7. Some sequence types (such as "range") only support item\n   sequences that follow specific patterns, and hence don\'t support\n   sequence concatenation or repetition.\n\n8. "index" raises "ValueError" when *x* is not found in *s*. When\n   supported, the additional arguments to the index method allow\n   efficient searching of subsections of the sequence. Passing the\n   extra arguments is roughly equivalent to using "s[i:j].index(x)",\n   only without copying any data and with the returned index being\n   relative to the start of the sequence rather than the start of the\n   slice.\n\n\nImmutable Sequence Types\n========================\n\nThe only operation that immutable sequence types generally implement\nthat is not also implemented by mutable sequence types is support for\nthe "hash()" built-in.\n\nThis support allows immutable sequences, such as "tuple" instances, to\nbe used as "dict" keys and stored in "set" and "frozenset" instances.\n\nAttempting to hash an immutable sequence that contains unhashable\nvalues will result in "TypeError".\n\n\nMutable Sequence Types\n======================\n\nThe operations in the following table are defined on mutable sequence\ntypes. The "collections.abc.MutableSequence" ABC is provided to make\nit easier to correctly implement these operations on custom sequence\ntypes.\n\nIn the table *s* is an instance of a mutable sequence type, *t* is any\niterable object and *x* is an arbitrary object that meets any type and\nvalue restrictions imposed by *s* (for example, "bytearray" only\naccepts integers that meet the value restriction "0 <= x <= 255").\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| "s[i] = x"                     | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s[i:j] = t"                   | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "del s[i:j]"                   | same as "s[i:j] = []"            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s[i:j:k] = t"                 | the elements of "s[i:j:k]" are   | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "del s[i:j:k]"                 | removes the elements of          |                       |\n|                                | "s[i:j:k]" from the list         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.append(x)"                  | appends *x* to the end of the    |                       |\n|                                | sequence (same as                |                       |\n|                                | "s[len(s):len(s)] = [x]")        |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.clear()"                    | removes all items from "s" (same | (5)                   |\n|                                | as "del s[:]")                   |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.copy()"                     | creates a shallow copy of "s"    | (5)                   |\n|                                | (same as "s[:]")                 |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.extend(t)" or "s += t"      | extends *s* with the contents of |                       |\n|                                | *t* (for the most part the same  |                       |\n|                                | as "s[len(s):len(s)] = t")       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s *= n"                       | updates *s* with its contents    | (6)                   |\n|                                | repeated *n* times               |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.insert(i, x)"               | inserts *x* into *s* at the      |                       |\n|                                | index given by *i* (same as      |                       |\n|                                | "s[i:i] = [x]")                  |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.pop([i])"                   | retrieves the item at *i* and    | (2)                   |\n|                                | also removes it from *s*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.remove(x)"                  | remove the first item from *s*   | (3)                   |\n|                                | where "s[i] == x"                |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.reverse()"                  | reverses the items of *s* in     | (4)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The optional argument *i* defaults to "-1", so that by default\n   the last item is removed and returned.\n\n3. "remove" raises "ValueError" when *x* is not found in *s*.\n\n4. The "reverse()" method modifies the sequence in place for\n   economy of space when reversing a large sequence.  To remind users\n   that it operates by side effect, it does not return the reversed\n   sequence.\n\n5. "clear()" and "copy()" are included for consistency with the\n   interfaces of mutable containers that don\'t support slicing\n   operations (such as "dict" and "set")\n\n   New in version 3.3: "clear()" and "copy()" methods.\n\n6. The value *n* is an integer, or an object implementing\n   "__index__()".  Zero and negative values of *n* clear the sequence.\n   Items in the sequence are not copied; they are referenced multiple\n   times, as explained for "s * n" under *Common Sequence Operations*.\n\n\nLists\n=====\n\nLists are mutable sequences, typically used to store collections of\nhomogeneous items (where the precise degree of similarity will vary by\napplication).\n\nclass class list([iterable])\n\n   Lists may be constructed in several ways:\n\n   * Using a pair of square brackets to denote the empty list: "[]"\n\n   * Using square brackets, separating items with commas: "[a]",\n     "[a, b, c]"\n\n   * Using a list comprehension: "[x for x in iterable]"\n\n   * Using the type constructor: "list()" or "list(iterable)"\n\n   The constructor builds a list whose items are the same and in the\n   same order as *iterable*\'s items.  *iterable* may be either a\n   sequence, a container that supports iteration, or an iterator\n   object.  If *iterable* is already a list, a copy is made and\n   returned, similar to "iterable[:]". For example, "list(\'abc\')"\n   returns "[\'a\', \'b\', \'c\']" and "list( (1, 2, 3) )" returns "[1, 2,\n   3]". If no argument is given, the constructor creates a new empty\n   list, "[]".\n\n   Many other operations also produce lists, including the "sorted()"\n   built-in.\n\n   Lists implement all of the *common* and *mutable* sequence\n   operations. Lists also provide the following additional method:\n\n   sort(*, key=None, reverse=None)\n\n      This method sorts the list in place, using only "<" comparisons\n      between items. Exceptions are not suppressed - if any comparison\n      operations fail, the entire sort operation will fail (and the\n      list will likely be left in a partially modified state).\n\n      "sort()" accepts two arguments that can only be passed by\n      keyword (*keyword-only arguments*):\n\n      *key* specifies a function of one argument that is used to\n      extract a comparison key from each list element (for example,\n      "key=str.lower"). The key corresponding to each item in the list\n      is calculated once and then used for the entire sorting process.\n      The default value of "None" means that list items are sorted\n      directly without calculating a separate key value.\n\n      The "functools.cmp_to_key()" utility is available to convert a\n      2.x style *cmp* function to a *key* function.\n\n      *reverse* is a boolean value.  If set to "True", then the list\n      elements are sorted as if each comparison were reversed.\n\n      This method modifies the sequence in place for economy of space\n      when sorting a large sequence.  To remind users that it operates\n      by side effect, it does not return the sorted sequence (use\n      "sorted()" to explicitly request a new sorted list instance).\n\n      The "sort()" method is guaranteed to be stable.  A sort is\n      stable if it guarantees not to change the relative order of\n      elements that compare equal --- this is helpful for sorting in\n      multiple passes (for example, sort by department, then by salary\n      grade).\n\n      **CPython implementation detail:** While a list is being sorted,\n      the effect of attempting to mutate, or even inspect, the list is\n      undefined.  The C implementation of Python makes the list appear\n      empty for the duration, and raises "ValueError" if it can detect\n      that the list has been mutated during a sort.\n\n\nTuples\n======\n\nTuples are immutable sequences, typically used to store collections of\nheterogeneous data (such as the 2-tuples produced by the "enumerate()"\nbuilt-in). Tuples are also used for cases where an immutable sequence\nof homogeneous data is needed (such as allowing storage in a "set" or\n"dict" instance).\n\nclass class tuple([iterable])\n\n   Tuples may be constructed in a number of ways:\n\n   * Using a pair of parentheses to denote the empty tuple: "()"\n\n   * Using a trailing comma for a singleton tuple: "a," or "(a,)"\n\n   * Separating items with commas: "a, b, c" or "(a, b, c)"\n\n   * Using the "tuple()" built-in: "tuple()" or "tuple(iterable)"\n\n   The constructor builds a tuple whose items are the same and in the\n   same order as *iterable*\'s items.  *iterable* may be either a\n   sequence, a container that supports iteration, or an iterator\n   object.  If *iterable* is already a tuple, it is returned\n   unchanged. For example, "tuple(\'abc\')" returns "(\'a\', \'b\', \'c\')"\n   and "tuple( [1, 2, 3] )" returns "(1, 2, 3)". If no argument is\n   given, the constructor creates a new empty tuple, "()".\n\n   Note that it is actually the comma which makes a tuple, not the\n   parentheses. The parentheses are optional, except in the empty\n   tuple case, or when they are needed to avoid syntactic ambiguity.\n   For example, "f(a, b, c)" is a function call with three arguments,\n   while "f((a, b, c))" is a function call with a 3-tuple as the sole\n   argument.\n\n   Tuples implement all of the *common* sequence operations.\n\nFor heterogeneous collections of data where access by name is clearer\nthan access by index, "collections.namedtuple()" may be a more\nappropriate choice than a simple tuple object.\n\n\nRanges\n======\n\nThe "range" type represents an immutable sequence of numbers and is\ncommonly used for looping a specific number of times in "for" loops.\n\nclass class range(stop)\nclass class range(start, stop[, step])\n\n   The arguments to the range constructor must be integers (either\n   built-in "int" or any object that implements the "__index__"\n   special method).  If the *step* argument is omitted, it defaults to\n   "1". If the *start* argument is omitted, it defaults to "0". If\n   *step* is zero, "ValueError" is raised.\n\n   For a positive *step*, the contents of a range "r" are determined\n   by the formula "r[i] = start + step*i" where "i >= 0" and "r[i] <\n   stop".\n\n   For a negative *step*, the contents of the range are still\n   determined by the formula "r[i] = start + step*i", but the\n   constraints are "i >= 0" and "r[i] > stop".\n\n   A range object will be empty if "r[0]" does not meet the value\n   constraint. Ranges do support negative indices, but these are\n   interpreted as indexing from the end of the sequence determined by\n   the positive indices.\n\n   Ranges containing absolute values larger than "sys.maxsize" are\n   permitted but some features (such as "len()") may raise\n   "OverflowError".\n\n   Range examples:\n\n      >>> list(range(10))\n      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n      >>> list(range(1, 11))\n      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n      >>> list(range(0, 30, 5))\n      [0, 5, 10, 15, 20, 25]\n      >>> list(range(0, 10, 3))\n      [0, 3, 6, 9]\n      >>> list(range(0, -10, -1))\n      [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n      >>> list(range(0))\n      []\n      >>> list(range(1, 0))\n      []\n\n   Ranges implement all of the *common* sequence operations except\n   concatenation and repetition (due to the fact that range objects\n   can only represent sequences that follow a strict pattern and\n   repetition and concatenation will usually violate that pattern).\n\n   start\n\n      The value of the *start* parameter (or "0" if the parameter was\n      not supplied)\n\n   stop\n\n      The value of the *stop* parameter\n\n   step\n\n      The value of the *step* parameter (or "1" if the parameter was\n      not supplied)\n\nThe advantage of the "range" type over a regular "list" or "tuple" is\nthat a "range" object will always take the same (small) amount of\nmemory, no matter the size of the range it represents (as it only\nstores the "start", "stop" and "step" values, calculating individual\nitems and subranges as needed).\n\nRange objects implement the "collections.abc.Sequence" ABC, and\nprovide features such as containment tests, element index lookup,\nslicing and support for negative indices (see *Sequence Types ---\nlist, tuple, range*):\n\n>>> r = range(0, 20, 2)\n>>> r\nrange(0, 20, 2)\n>>> 11 in r\nFalse\n>>> 10 in r\nTrue\n>>> r.index(10)\n5\n>>> r[5]\n10\n>>> r[:5]\nrange(0, 10, 2)\n>>> r[-1]\n18\n\nTesting range objects for equality with "==" and "!=" compares them as\nsequences.  That is, two range objects are considered equal if they\nrepresent the same sequence of values.  (Note that two range objects\nthat compare equal might have different "start", "stop" and "step"\nattributes, for example "range(0) == range(2, 1, 3)" or "range(0, 3,\n2) == range(0, 4, 2)".)\n\nChanged in version 3.2: Implement the Sequence ABC. Support slicing\nand negative indices. Test "int" objects for membership in constant\ntime instead of iterating through all items.\n\nChanged in version 3.3: Define \'==\' and \'!=\' to compare range objects\nbased on the sequence of values they define (instead of comparing\nbased on object identity).\n\nNew in version 3.3: The "start", "stop" and "step" attributes.\n',
+ 'typesseq': u'\nSequence Types --- "list", "tuple", "range"\n*******************************************\n\nThere are three basic sequence types: lists, tuples, and range\nobjects. Additional sequence types tailored for processing of *binary\ndata* and *text strings* are described in dedicated sections.\n\n\nCommon Sequence Operations\n==========================\n\nThe operations in the following table are supported by most sequence\ntypes, both mutable and immutable. The "collections.abc.Sequence" ABC\nis provided to make it easier to correctly implement these operations\non custom sequence types.\n\nThis table lists the sequence operations sorted in ascending priority.\nIn the table, *s* and *t* are sequences of the same type, *n*, *i*,\n*j* and *k* are integers and *x* is an arbitrary object that meets any\ntype and value restrictions imposed by *s*.\n\nThe "in" and "not in" operations have the same priorities as the\ncomparison operations. The "+" (concatenation) and "*" (repetition)\noperations have the same priority as the corresponding numeric\noperations.\n\n+----------------------------+----------------------------------+------------+\n| Operation                  | Result                           | Notes      |\n+============================+==================================+============+\n| "x in s"                   | "True" if an item of *s* is      | (1)        |\n|                            | equal to *x*, else "False"       |            |\n+----------------------------+----------------------------------+------------+\n| "x not in s"               | "False" if an item of *s* is     | (1)        |\n|                            | equal to *x*, else "True"        |            |\n+----------------------------+----------------------------------+------------+\n| "s + t"                    | the concatenation of *s* and *t* | (6)(7)     |\n+----------------------------+----------------------------------+------------+\n| "s * n" or "n * s"         | equivalent to adding *s* to      | (2)(7)     |\n|                            | itself *n* times                 |            |\n+----------------------------+----------------------------------+------------+\n| "s[i]"                     | *i*th item of *s*, origin 0      | (3)        |\n+----------------------------+----------------------------------+------------+\n| "s[i:j]"                   | slice of *s* from *i* to *j*     | (3)(4)     |\n+----------------------------+----------------------------------+------------+\n| "s[i:j:k]"                 | slice of *s* from *i* to *j*     | (3)(5)     |\n|                            | with step *k*                    |            |\n+----------------------------+----------------------------------+------------+\n| "len(s)"                   | length of *s*                    |            |\n+----------------------------+----------------------------------+------------+\n| "min(s)"                   | smallest item of *s*             |            |\n+----------------------------+----------------------------------+------------+\n| "max(s)"                   | largest item of *s*              |            |\n+----------------------------+----------------------------------+------------+\n| "s.index(x[, i[, j]])"     | index of the first occurrence of | (8)        |\n|                            | *x* in *s* (at or after index    |            |\n|                            | *i* and before index *j*)        |            |\n+----------------------------+----------------------------------+------------+\n| "s.count(x)"               | total number of occurrences of   |            |\n|                            | *x* in *s*                       |            |\n+----------------------------+----------------------------------+------------+\n\nSequences of the same type also support comparisons.  In particular,\ntuples and lists are compared lexicographically by comparing\ncorresponding elements. This means that to compare equal, every\nelement must compare equal and the two sequences must be of the same\ntype and have the same length.  (For full details see *Comparisons* in\nthe language reference.)\n\nNotes:\n\n1. While the "in" and "not in" operations are used only for simple\n   containment testing in the general case, some specialised sequences\n   (such as "str", "bytes" and "bytearray") also use them for\n   subsequence testing:\n\n      >>> "gg" in "eggs"\n      True\n\n2. Values of *n* less than "0" are treated as "0" (which yields an\n   empty sequence of the same type as *s*).  Note that items in the\n   sequence *s* are not copied; they are referenced multiple times.\n   This often haunts new Python programmers; consider:\n\n      >>> lists = [[]] * 3\n      >>> lists\n      [[], [], []]\n      >>> lists[0].append(3)\n      >>> lists\n      [[3], [3], [3]]\n\n   What has happened is that "[[]]" is a one-element list containing\n   an empty list, so all three elements of "[[]] * 3" are references\n   to this single empty list.  Modifying any of the elements of\n   "lists" modifies this single list. You can create a list of\n   different lists this way:\n\n      >>> lists = [[] for i in range(3)]\n      >>> lists[0].append(3)\n      >>> lists[1].append(5)\n      >>> lists[2].append(7)\n      >>> lists\n      [[3], [5], [7]]\n\n   Further explanation is available in the FAQ entry *How do I create\n   a multidimensional list?*.\n\n3. If *i* or *j* is negative, the index is relative to the end of\n   sequence *s*: "len(s) + i" or "len(s) + j" is substituted.  But\n   note that "-0" is still "0".\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n   items with index *k* such that "i <= k < j".  If *i* or *j* is\n   greater than "len(s)", use "len(s)".  If *i* is omitted or "None",\n   use "0".  If *j* is omitted or "None", use "len(s)".  If *i* is\n   greater than or equal to *j*, the slice is empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n   sequence of items with index  "x = i + n*k" such that "0 <= n <\n   (j-i)/k".  In other words, the indices are "i", "i+k", "i+2*k",\n   "i+3*k" and so on, stopping when *j* is reached (but never\n   including *j*).  When *k* is positive, *i* and *j* are reduced to\n   "len(s)" if they are greater. When *k* is negative, *i* and *j* are\n   reduced to "len(s) - 1" if they are greater.  If *i* or *j* are\n   omitted or "None", they become "end" values (which end depends on\n   the sign of *k*).  Note, *k* cannot be zero. If *k* is "None", it\n   is treated like "1".\n\n6. Concatenating immutable sequences always results in a new\n   object. This means that building up a sequence by repeated\n   concatenation will have a quadratic runtime cost in the total\n   sequence length. To get a linear runtime cost, you must switch to\n   one of the alternatives below:\n\n   * if concatenating "str" objects, you can build a list and use\n     "str.join()" at the end or else write to an "io.StringIO"\n     instance and retrieve its value when complete\n\n   * if concatenating "bytes" objects, you can similarly use\n     "bytes.join()" or "io.BytesIO", or you can do in-place\n     concatenation with a "bytearray" object.  "bytearray" objects are\n     mutable and have an efficient overallocation mechanism\n\n   * if concatenating "tuple" objects, extend a "list" instead\n\n   * for other types, investigate the relevant class documentation\n\n7. Some sequence types (such as "range") only support item\n   sequences that follow specific patterns, and hence don\'t support\n   sequence concatenation or repetition.\n\n8. "index" raises "ValueError" when *x* is not found in *s*. When\n   supported, the additional arguments to the index method allow\n   efficient searching of subsections of the sequence. Passing the\n   extra arguments is roughly equivalent to using "s[i:j].index(x)",\n   only without copying any data and with the returned index being\n   relative to the start of the sequence rather than the start of the\n   slice.\n\n\nImmutable Sequence Types\n========================\n\nThe only operation that immutable sequence types generally implement\nthat is not also implemented by mutable sequence types is support for\nthe "hash()" built-in.\n\nThis support allows immutable sequences, such as "tuple" instances, to\nbe used as "dict" keys and stored in "set" and "frozenset" instances.\n\nAttempting to hash an immutable sequence that contains unhashable\nvalues will result in "TypeError".\n\n\nMutable Sequence Types\n======================\n\nThe operations in the following table are defined on mutable sequence\ntypes. The "collections.abc.MutableSequence" ABC is provided to make\nit easier to correctly implement these operations on custom sequence\ntypes.\n\nIn the table *s* is an instance of a mutable sequence type, *t* is any\niterable object and *x* is an arbitrary object that meets any type and\nvalue restrictions imposed by *s* (for example, "bytearray" only\naccepts integers that meet the value restriction "0 <= x <= 255").\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| "s[i] = x"                     | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s[i:j] = t"                   | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "del s[i:j]"                   | same as "s[i:j] = []"            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s[i:j:k] = t"                 | the elements of "s[i:j:k]" are   | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "del s[i:j:k]"                 | removes the elements of          |                       |\n|                                | "s[i:j:k]" from the list         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.append(x)"                  | appends *x* to the end of the    |                       |\n|                                | sequence (same as                |                       |\n|                                | "s[len(s):len(s)] = [x]")        |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.clear()"                    | removes all items from "s" (same | (5)                   |\n|                                | as "del s[:]")                   |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.copy()"                     | creates a shallow copy of "s"    | (5)                   |\n|                                | (same as "s[:]")                 |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.extend(t)" or "s += t"      | extends *s* with the contents of |                       |\n|                                | *t* (for the most part the same  |                       |\n|                                | as "s[len(s):len(s)] = t")       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s *= n"                       | updates *s* with its contents    | (6)                   |\n|                                | repeated *n* times               |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.insert(i, x)"               | inserts *x* into *s* at the      |                       |\n|                                | index given by *i* (same as      |                       |\n|                                | "s[i:i] = [x]")                  |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.pop([i])"                   | retrieves the item at *i* and    | (2)                   |\n|                                | also removes it from *s*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.remove(x)"                  | remove the first item from *s*   | (3)                   |\n|                                | where "s[i] == x"                |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.reverse()"                  | reverses the items of *s* in     | (4)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The optional argument *i* defaults to "-1", so that by default\n   the last item is removed and returned.\n\n3. "remove" raises "ValueError" when *x* is not found in *s*.\n\n4. The "reverse()" method modifies the sequence in place for\n   economy of space when reversing a large sequence.  To remind users\n   that it operates by side effect, it does not return the reversed\n   sequence.\n\n5. "clear()" and "copy()" are included for consistency with the\n   interfaces of mutable containers that don\'t support slicing\n   operations (such as "dict" and "set")\n\n   New in version 3.3: "clear()" and "copy()" methods.\n\n6. The value *n* is an integer, or an object implementing\n   "__index__()".  Zero and negative values of *n* clear the sequence.\n   Items in the sequence are not copied; they are referenced multiple\n   times, as explained for "s * n" under *Common Sequence Operations*.\n\n\nLists\n=====\n\nLists are mutable sequences, typically used to store collections of\nhomogeneous items (where the precise degree of similarity will vary by\napplication).\n\nclass class list([iterable])\n\n   Lists may be constructed in several ways:\n\n   * Using a pair of square brackets to denote the empty list: "[]"\n\n   * Using square brackets, separating items with commas: "[a]",\n     "[a, b, c]"\n\n   * Using a list comprehension: "[x for x in iterable]"\n\n   * Using the type constructor: "list()" or "list(iterable)"\n\n   The constructor builds a list whose items are the same and in the\n   same order as *iterable*\'s items.  *iterable* may be either a\n   sequence, a container that supports iteration, or an iterator\n   object.  If *iterable* is already a list, a copy is made and\n   returned, similar to "iterable[:]". For example, "list(\'abc\')"\n   returns "[\'a\', \'b\', \'c\']" and "list( (1, 2, 3) )" returns "[1, 2,\n   3]". If no argument is given, the constructor creates a new empty\n   list, "[]".\n\n   Many other operations also produce lists, including the "sorted()"\n   built-in.\n\n   Lists implement all of the *common* and *mutable* sequence\n   operations. Lists also provide the following additional method:\n\n   sort(*, key=None, reverse=None)\n\n      This method sorts the list in place, using only "<" comparisons\n      between items. Exceptions are not suppressed - if any comparison\n      operations fail, the entire sort operation will fail (and the\n      list will likely be left in a partially modified state).\n\n      "sort()" accepts two arguments that can only be passed by\n      keyword (*keyword-only arguments*):\n\n      *key* specifies a function of one argument that is used to\n      extract a comparison key from each list element (for example,\n      "key=str.lower"). The key corresponding to each item in the list\n      is calculated once and then used for the entire sorting process.\n      The default value of "None" means that list items are sorted\n      directly without calculating a separate key value.\n\n      The "functools.cmp_to_key()" utility is available to convert a\n      2.x style *cmp* function to a *key* function.\n\n      *reverse* is a boolean value.  If set to "True", then the list\n      elements are sorted as if each comparison were reversed.\n\n      This method modifies the sequence in place for economy of space\n      when sorting a large sequence.  To remind users that it operates\n      by side effect, it does not return the sorted sequence (use\n      "sorted()" to explicitly request a new sorted list instance).\n\n      The "sort()" method is guaranteed to be stable.  A sort is\n      stable if it guarantees not to change the relative order of\n      elements that compare equal --- this is helpful for sorting in\n      multiple passes (for example, sort by department, then by salary\n      grade).\n\n      **CPython implementation detail:** While a list is being sorted,\n      the effect of attempting to mutate, or even inspect, the list is\n      undefined.  The C implementation of Python makes the list appear\n      empty for the duration, and raises "ValueError" if it can detect\n      that the list has been mutated during a sort.\n\n\nTuples\n======\n\nTuples are immutable sequences, typically used to store collections of\nheterogeneous data (such as the 2-tuples produced by the "enumerate()"\nbuilt-in). Tuples are also used for cases where an immutable sequence\nof homogeneous data is needed (such as allowing storage in a "set" or\n"dict" instance).\n\nclass class tuple([iterable])\n\n   Tuples may be constructed in a number of ways:\n\n   * Using a pair of parentheses to denote the empty tuple: "()"\n\n   * Using a trailing comma for a singleton tuple: "a," or "(a,)"\n\n   * Separating items with commas: "a, b, c" or "(a, b, c)"\n\n   * Using the "tuple()" built-in: "tuple()" or "tuple(iterable)"\n\n   The constructor builds a tuple whose items are the same and in the\n   same order as *iterable*\'s items.  *iterable* may be either a\n   sequence, a container that supports iteration, or an iterator\n   object.  If *iterable* is already a tuple, it is returned\n   unchanged. For example, "tuple(\'abc\')" returns "(\'a\', \'b\', \'c\')"\n   and "tuple( [1, 2, 3] )" returns "(1, 2, 3)". If no argument is\n   given, the constructor creates a new empty tuple, "()".\n\n   Note that it is actually the comma which makes a tuple, not the\n   parentheses. The parentheses are optional, except in the empty\n   tuple case, or when they are needed to avoid syntactic ambiguity.\n   For example, "f(a, b, c)" is a function call with three arguments,\n   while "f((a, b, c))" is a function call with a 3-tuple as the sole\n   argument.\n\n   Tuples implement all of the *common* sequence operations.\n\nFor heterogeneous collections of data where access by name is clearer\nthan access by index, "collections.namedtuple()" may be a more\nappropriate choice than a simple tuple object.\n\n\nRanges\n======\n\nThe "range" type represents an immutable sequence of numbers and is\ncommonly used for looping a specific number of times in "for" loops.\n\nclass class range(stop)\nclass class range(start, stop[, step])\n\n   The arguments to the range constructor must be integers (either\n   built-in "int" or any object that implements the "__index__"\n   special method).  If the *step* argument is omitted, it defaults to\n   "1". If the *start* argument is omitted, it defaults to "0". If\n   *step* is zero, "ValueError" is raised.\n\n   For a positive *step*, the contents of a range "r" are determined\n   by the formula "r[i] = start + step*i" where "i >= 0" and "r[i] <\n   stop".\n\n   For a negative *step*, the contents of the range are still\n   determined by the formula "r[i] = start + step*i", but the\n   constraints are "i >= 0" and "r[i] > stop".\n\n   A range object will be empty if "r[0]" does not meet the value\n   constraint. Ranges do support negative indices, but these are\n   interpreted as indexing from the end of the sequence determined by\n   the positive indices.\n\n   Ranges containing absolute values larger than "sys.maxsize" are\n   permitted but some features (such as "len()") may raise\n   "OverflowError".\n\n   Range examples:\n\n      >>> list(range(10))\n      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n      >>> list(range(1, 11))\n      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n      >>> list(range(0, 30, 5))\n      [0, 5, 10, 15, 20, 25]\n      >>> list(range(0, 10, 3))\n      [0, 3, 6, 9]\n      >>> list(range(0, -10, -1))\n      [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]\n      >>> list(range(0))\n      []\n      >>> list(range(1, 0))\n      []\n\n   Ranges implement all of the *common* sequence operations except\n   concatenation and repetition (due to the fact that range objects\n   can only represent sequences that follow a strict pattern and\n   repetition and concatenation will usually violate that pattern).\n\n   start\n\n      The value of the *start* parameter (or "0" if the parameter was\n      not supplied)\n\n   stop\n\n      The value of the *stop* parameter\n\n   step\n\n      The value of the *step* parameter (or "1" if the parameter was\n      not supplied)\n\nThe advantage of the "range" type over a regular "list" or "tuple" is\nthat a "range" object will always take the same (small) amount of\nmemory, no matter the size of the range it represents (as it only\nstores the "start", "stop" and "step" values, calculating individual\nitems and subranges as needed).\n\nRange objects implement the "collections.abc.Sequence" ABC, and\nprovide features such as containment tests, element index lookup,\nslicing and support for negative indices (see *Sequence Types ---\nlist, tuple, range*):\n\n>>> r = range(0, 20, 2)\n>>> r\nrange(0, 20, 2)\n>>> 11 in r\nFalse\n>>> 10 in r\nTrue\n>>> r.index(10)\n5\n>>> r[5]\n10\n>>> r[:5]\nrange(0, 10, 2)\n>>> r[-1]\n18\n\nTesting range objects for equality with "==" and "!=" compares them as\nsequences.  That is, two range objects are considered equal if they\nrepresent the same sequence of values.  (Note that two range objects\nthat compare equal might have different "start", "stop" and "step"\nattributes, for example "range(0) == range(2, 1, 3)" or "range(0, 3,\n2) == range(0, 4, 2)".)\n\nChanged in version 3.2: Implement the Sequence ABC. Support slicing\nand negative indices. Test "int" objects for membership in constant\ntime instead of iterating through all items.\n\nChanged in version 3.3: Define \'==\' and \'!=\' to compare range objects\nbased on the sequence of values they define (instead of comparing\nbased on object identity).\n\nNew in version 3.3: The "start", "stop" and "step" attributes.\n',
  'typesseq-mutable': u'\nMutable Sequence Types\n**********************\n\nThe operations in the following table are defined on mutable sequence\ntypes. The "collections.abc.MutableSequence" ABC is provided to make\nit easier to correctly implement these operations on custom sequence\ntypes.\n\nIn the table *s* is an instance of a mutable sequence type, *t* is any\niterable object and *x* is an arbitrary object that meets any type and\nvalue restrictions imposed by *s* (for example, "bytearray" only\naccepts integers that meet the value restriction "0 <= x <= 255").\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| "s[i] = x"                     | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s[i:j] = t"                   | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "del s[i:j]"                   | same as "s[i:j] = []"            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s[i:j:k] = t"                 | the elements of "s[i:j:k]" are   | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "del s[i:j:k]"                 | removes the elements of          |                       |\n|                                | "s[i:j:k]" from the list         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.append(x)"                  | appends *x* to the end of the    |                       |\n|                                | sequence (same as                |                       |\n|                                | "s[len(s):len(s)] = [x]")        |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.clear()"                    | removes all items from "s" (same | (5)                   |\n|                                | as "del s[:]")                   |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.copy()"                     | creates a shallow copy of "s"    | (5)                   |\n|                                | (same as "s[:]")                 |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.extend(t)" or "s += t"      | extends *s* with the contents of |                       |\n|                                | *t* (for the most part the same  |                       |\n|                                | as "s[len(s):len(s)] = t")       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s *= n"                       | updates *s* with its contents    | (6)                   |\n|                                | repeated *n* times               |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.insert(i, x)"               | inserts *x* into *s* at the      |                       |\n|                                | index given by *i* (same as      |                       |\n|                                | "s[i:i] = [x]")                  |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.pop([i])"                   | retrieves the item at *i* and    | (2)                   |\n|                                | also removes it from *s*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.remove(x)"                  | remove the first item from *s*   | (3)                   |\n|                                | where "s[i] == x"                |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| "s.reverse()"                  | reverses the items of *s* in     | (4)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. The optional argument *i* defaults to "-1", so that by default\n   the last item is removed and returned.\n\n3. "remove" raises "ValueError" when *x* is not found in *s*.\n\n4. The "reverse()" method modifies the sequence in place for\n   economy of space when reversing a large sequence.  To remind users\n   that it operates by side effect, it does not return the reversed\n   sequence.\n\n5. "clear()" and "copy()" are included for consistency with the\n   interfaces of mutable containers that don\'t support slicing\n   operations (such as "dict" and "set")\n\n   New in version 3.3: "clear()" and "copy()" methods.\n\n6. The value *n* is an integer, or an object implementing\n   "__index__()".  Zero and negative values of *n* clear the sequence.\n   Items in the sequence are not copied; they are referenced multiple\n   times, as explained for "s * n" under *Common Sequence Operations*.\n',
  'unary': u'\nUnary arithmetic and bitwise operations\n***************************************\n\nAll unary arithmetic and bitwise operations have the same priority:\n\n   u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n\nThe unary "-" (minus) operator yields the negation of its numeric\nargument.\n\nThe unary "+" (plus) operator yields its numeric argument unchanged.\n\nThe unary "~" (invert) operator yields the bitwise inversion of its\ninteger argument.  The bitwise inversion of "x" is defined as\n"-(x+1)".  It only applies to integral numbers.\n\nIn all three cases, if the argument does not have the proper type, a\n"TypeError" exception is raised.\n',
  'while': u'\nThe "while" statement\n*********************\n\nThe "while" statement is used for repeated execution as long as an\nexpression is true:\n\n   while_stmt ::= "while" expression ":" suite\n                  ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the "else" clause, if present, is executed\nand the loop terminates.\n\nA "break" statement executed in the first suite terminates the loop\nwithout executing the "else" clause\'s suite.  A "continue" statement\nexecuted in the first suite skips the rest of the suite and goes back\nto testing the expression.\n',
index 5950735..4efbb0a 100644 (file)
@@ -96,11 +96,13 @@ class Random(_random.Random):
         None or no argument seeds from current time or from an operating
         system specific randomness source if available.
 
-        For version 2 (the default), all of the bits are used if *a* is a str,
-        bytes, or bytearray.  For version 1, the hash() of *a* is used instead.
-
         If *a* is an int, all bits are used.
 
+        For version 2 (the default), all of the bits are used if *a* is a str,
+        bytes, or bytearray.  For version 1 (provided for reproducing random
+        sequences from older versions of Python), the algorithm for str and
+        bytes generates a narrower range of seeds.
+
         """
 
         if a is None:
@@ -112,6 +114,13 @@ class Random(_random.Random):
                 import time
                 a = int(time.time() * 256) # use fractional seconds
 
+        if version == 1 and isinstance(a, (str, bytes)):
+            x = ord(a[0]) << 7 if a else 0
+            for c in a:
+                x = ((1000003 * x) ^ ord(c)) & 0xFFFFFFFFFFFFFFFF
+            x ^= len(a)
+            a = -2 if x == -1 else x
+
         if version == 2:
             if isinstance(a, (str, bytes, bytearray)):
                 if isinstance(a, str):
index af6205d..d86f0e4 100644 (file)
@@ -98,7 +98,7 @@ def _run_module_code(code, init_globals=None,
     # may be cleared when the temporary module goes away
     return mod_globals.copy()
 
-# Helper to get the loader, code and filename for a module
+# Helper to get the full name, spec and code for a module
 def _get_module_details(mod_name, error=ImportError):
     if mod_name.startswith("."):
         raise error("Relative module names not supported")
@@ -114,6 +114,15 @@ def _get_module_details(mod_name, error=ImportError):
             if e.name is None or (e.name != pkg_name and
                     not pkg_name.startswith(e.name + ".")):
                 raise
+        # Warn if the module has already been imported under its normal name
+        existing = sys.modules.get(mod_name)
+        if existing is not None and not hasattr(existing, "__path__"):
+            from warnings import warn
+            msg = "{mod_name!r} found in sys.modules after import of " \
+                "package {pkg_name!r}, but prior to execution of " \
+                "{mod_name!r}; this may result in unpredictable " \
+                "behaviour".format(mod_name=mod_name, pkg_name=pkg_name)
+            warn(RuntimeWarning(msg))
 
     try:
         spec = importlib.util.find_spec(mod_name)
@@ -121,7 +130,7 @@ def _get_module_details(mod_name, error=ImportError):
         # This hack fixes an impedance mismatch between pkgutil and
         # importlib, where the latter raises other errors for cases where
         # pkgutil previously raised ImportError
-        msg = "Error while finding spec for {!r} ({}: {})"
+        msg = "Error while finding module specification for {!r} ({}: {})"
         raise error(msg.format(mod_name, type(ex).__name__, ex)) from ex
     if spec is None:
         raise error("No module named %s" % mod_name)
@@ -253,7 +262,7 @@ def run_path(path_name, init_globals=None, run_name=None):
         return _run_module_code(code, init_globals, run_name,
                                 pkg_name=pkg_name, script_name=fname)
     else:
-        # Importer is defined for path, so add it to
+        # Finder is defined for path, so add it to
         # the start of sys.path
         sys.path.insert(0, path_name)
         try:
index d8769e3..89680a2 100644 (file)
@@ -408,7 +408,11 @@ if hasattr(select, 'epoll'):
                 epoll_events |= select.EPOLLIN
             if events & EVENT_WRITE:
                 epoll_events |= select.EPOLLOUT
-            self._epoll.register(key.fd, epoll_events)
+            try:
+                self._epoll.register(key.fd, epoll_events)
+            except BaseException:
+                super().unregister(fileobj)
+                raise
             return key
 
         def unregister(self, fileobj):
@@ -530,14 +534,18 @@ if hasattr(select, 'kqueue'):
 
         def register(self, fileobj, events, data=None):
             key = super().register(fileobj, events, data)
-            if events & EVENT_READ:
-                kev = select.kevent(key.fd, select.KQ_FILTER_READ,
-                                    select.KQ_EV_ADD)
-                self._kqueue.control([kev], 0, 0)
-            if events & EVENT_WRITE:
-                kev = select.kevent(key.fd, select.KQ_FILTER_WRITE,
-                                    select.KQ_EV_ADD)
-                self._kqueue.control([kev], 0, 0)
+            try:
+                if events & EVENT_READ:
+                    kev = select.kevent(key.fd, select.KQ_FILTER_READ,
+                                        select.KQ_EV_ADD)
+                    self._kqueue.control([kev], 0, 0)
+                if events & EVENT_WRITE:
+                    kev = select.kevent(key.fd, select.KQ_FILTER_WRITE,
+                                        select.KQ_EV_ADD)
+                    self._kqueue.control([kev], 0, 0)
+            except BaseException:
+                super().unregister(fileobj)
+                raise
             return key
 
         def unregister(self, fileobj):
index f083918..ecd2efd 100644 (file)
@@ -224,7 +224,7 @@ class shlex:
                     if self.debug >= 2:
                         print("shlex: I see punctuation in word state")
                     self.state = ' '
-                    if self.token:
+                    if self.token or (self.posix and quoted):
                         break   # emit current token
                     else:
                         continue
index 37124a0..16ca80b 100644 (file)
@@ -10,7 +10,13 @@ import stat
 import fnmatch
 import collections
 import errno
-import tarfile
+
+try:
+    import zlib
+    del zlib
+    _ZLIB_SUPPORTED = True
+except ImportError:
+    _ZLIB_SUPPORTED = False
 
 try:
     import bz2
@@ -64,7 +70,7 @@ class ReadError(OSError):
 
 class RegistryError(Exception):
     """Raised when a registry operation with the archiving
-    and unpacking registeries fails"""
+    and unpacking registries fails"""
 
 
 def copyfileobj(fsrc, fdst, length=16*1024):
@@ -602,23 +608,22 @@ def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
 
     Returns the output filename.
     """
-    tar_compression = {'gzip': 'gz', None: ''}
-    compress_ext = {'gzip': '.gz'}
-
-    if _BZ2_SUPPORTED:
-        tar_compression['bzip2'] = 'bz2'
-        compress_ext['bzip2'] = '.bz2'
-
-    if _LZMA_SUPPORTED:
-        tar_compression['xz'] = 'xz'
-        compress_ext['xz'] = '.xz'
-
-    # flags for compression program, each element of list will be an argument
-    if compress is not None and compress not in compress_ext:
+    if compress is None:
+        tar_compression = ''
+    elif _ZLIB_SUPPORTED and compress == 'gzip':
+        tar_compression = 'gz'
+    elif _BZ2_SUPPORTED and compress == 'bzip2':
+        tar_compression = 'bz2'
+    elif _LZMA_SUPPORTED and compress == 'xz':
+        tar_compression = 'xz'
+    else:
         raise ValueError("bad value for 'compress', or compression format not "
                          "supported : {0}".format(compress))
 
-    archive_name = base_name + '.tar' + compress_ext.get(compress, '')
+    import tarfile  # late import for breaking circular dependency
+
+    compress_ext = '.' + tar_compression if compress else ''
+    archive_name = base_name + '.tar' + compress_ext
     archive_dir = os.path.dirname(archive_name)
 
     if archive_dir and not os.path.exists(archive_dir):
@@ -644,7 +649,7 @@ def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
         return tarinfo
 
     if not dry_run:
-        tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
+        tar = tarfile.open(archive_name, 'w|%s' % tar_compression)
         try:
             tar.add(base_dir, filter=_set_uid_gid)
         finally:
@@ -655,13 +660,10 @@ def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
 def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
     """Create a zip file from all the files under 'base_dir'.
 
-    The output zip file will be named 'base_name' + ".zip".  Uses either the
-    "zipfile" Python module (if available) or the InfoZIP "zip" utility
-    (if installed and found on the default search path).  If neither tool is
-    available, raises ExecError.  Returns the name of the output zip
-    file.
+    The output zip file will be named 'base_name' + ".zip".  Returns the
+    name of the output zip file.
     """
-    import zipfile
+    import zipfile  # late import for breaking circular dependency
 
     zip_filename = base_name + ".zip"
     archive_dir = os.path.dirname(base_name)
@@ -680,9 +682,10 @@ def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
         with zipfile.ZipFile(zip_filename, "w",
                              compression=zipfile.ZIP_DEFLATED) as zf:
             path = os.path.normpath(base_dir)
-            zf.write(path, path)
-            if logger is not None:
-                logger.info("adding '%s'", path)
+            if path != os.curdir:
+                zf.write(path, path)
+                if logger is not None:
+                    logger.info("adding '%s'", path)
             for dirpath, dirnames, filenames in os.walk(base_dir):
                 for name in sorted(dirnames):
                     path = os.path.normpath(os.path.join(dirpath, name))
@@ -699,10 +702,13 @@ def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
     return zip_filename
 
 _ARCHIVE_FORMATS = {
-    'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
     'tar':   (_make_tarball, [('compress', None)], "uncompressed tar file"),
-    'zip':   (_make_zipfile, [], "ZIP file")
-    }
+}
+
+if _ZLIB_SUPPORTED:
+    _ARCHIVE_FORMATS['gztar'] = (_make_tarball, [('compress', 'gzip')],
+                                "gzip'ed tar-file")
+    _ARCHIVE_FORMATS['zip'] = (_make_zipfile, [], "ZIP file")
 
 if _BZ2_SUPPORTED:
     _ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')],
@@ -751,8 +757,8 @@ def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
     """Create an archive file (eg. zip or tar).
 
     'base_name' is the name of the file to create, minus any format-specific
-    extension; 'format' is the archive format: one of "zip", "tar", "bztar"
-    or "gztar".
+    extension; 'format' is the archive format: one of "zip", "tar", "gztar",
+    "bztar", or "xztar".  Or any other registered format.
 
     'root_dir' is a directory that will be the root directory of the
     archive; ie. we typically chdir into 'root_dir' before creating the
@@ -853,7 +859,7 @@ def register_unpack_format(name, extensions, function, extra_args=None,
     _UNPACK_FORMATS[name] = extensions, function, extra_args, description
 
 def unregister_unpack_format(name):
-    """Removes the pack format from the registery."""
+    """Removes the pack format from the registry."""
     del _UNPACK_FORMATS[name]
 
 def _ensure_directory(path):
@@ -865,10 +871,7 @@ def _ensure_directory(path):
 def _unpack_zipfile(filename, extract_dir):
     """Unpack zip `filename` to `extract_dir`
     """
-    try:
-        import zipfile
-    except ImportError:
-        raise ReadError('zlib not supported, cannot unpack this archive.')
+    import zipfile  # late import for breaking circular dependency
 
     if not zipfile.is_zipfile(filename):
         raise ReadError("%s is not a zip file" % filename)
@@ -902,6 +905,7 @@ def _unpack_zipfile(filename, extract_dir):
 def _unpack_tarfile(filename, extract_dir):
     """Unpack tar/tar.gz/tar.bz2/tar.xz `filename` to `extract_dir`
     """
+    import tarfile  # late import for breaking circular dependency
     try:
         tarobj = tarfile.open(filename)
     except tarfile.TarError:
@@ -913,10 +917,13 @@ def _unpack_tarfile(filename, extract_dir):
         tarobj.close()
 
 _UNPACK_FORMATS = {
-    'gztar': (['.tar.gz', '.tgz'], _unpack_tarfile, [], "gzip'ed tar-file"),
     'tar':   (['.tar'], _unpack_tarfile, [], "uncompressed tar file"),
-    'zip':   (['.zip'], _unpack_zipfile, [], "ZIP file")
-    }
+    'zip':   (['.zip'], _unpack_zipfile, [], "ZIP file"),
+}
+
+if _ZLIB_SUPPORTED:
+    _UNPACK_FORMATS['gztar'] = (['.tar.gz', '.tgz'], _unpack_tarfile, [],
+                                "gzip'ed tar-file")
 
 if _BZ2_SUPPORTED:
     _UNPACK_FORMATS['bztar'] = (['.tar.bz2', '.tbz2'], _unpack_tarfile, [],
@@ -941,10 +948,10 @@ def unpack_archive(filename, extract_dir=None, format=None):
     `extract_dir` is the name of the target directory, where the archive
     is unpacked. If not provided, the current working directory is used.
 
-    `format` is the archive format: one of "zip", "tar", or "gztar". Or any
-    other registered format. If not provided, unpack_archive will use the
-    filename extension and see if an unpacker was registered for that
-    extension.
+    `format` is the archive format: one of "zip", "tar", "gztar", "bztar",
+    or "xztar".  Or any other registered format.  If not provided,
+    unpack_archive will use the filename extension and see if an unpacker
+    was registered for that extension.
 
     In case none is found, a ValueError is raised.
     """
index dfbf5f9..5b9e665 100755 (executable)
@@ -900,7 +900,7 @@ class SMTP:
         the recipient addresses contain non-ASCII and the server advertises the
         SMTPUTF8 capability, the policy is cloned with utf8 set to True for the
         serialization, and SMTPUTF8 and BODY=8BITMIME are asserted on the send.
-        If the server does not support SMTPUTF8, an SMPTNotSupported error is
+        If the server does not support SMTPUTF8, an SMTPNotSupported error is
         raised.  Otherwise the generator is called without modifying the
         policy.
 
index ac2e3dd..a9cab32 100644 (file)
@@ -258,7 +258,7 @@ class socket(_socket.socket):
                 raise _GiveupOnSendfile(err)  # not a regular file
             try:
                 fsize = os.fstat(fileno).st_size
-            except OSError:
+            except OSError as err:
                 raise _GiveupOnSendfile(err)  # not a regular file
             if not fsize:
                 return 0  # empty file
@@ -519,6 +519,7 @@ else:
         finally:
             lsock.close()
         return (ssock, csock)
+    __all__.append("socketpair")
 
 socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
 Create a pair of socket objects from the sockets returned by the platform
index 04649fc..7fb8d7e 100644 (file)
@@ -122,11 +122,8 @@ class ConnectionTests(unittest.TestCase):
 
     def CheckFailedOpen(self):
         YOU_CANNOT_OPEN_THIS = "/foo/bar/bla/23534/mydb.db"
-        try:
+        with self.assertRaises(sqlite.OperationalError):
             con = sqlite.connect(YOU_CANNOT_OPEN_THIS)
-        except sqlite.OperationalError:
-            return
-        self.fail("should have raised an OperationalError")
 
     def CheckClose(self):
         self.cx.close()
@@ -180,6 +177,12 @@ class ConnectionTests(unittest.TestCase):
             with self.assertRaises(sqlite.OperationalError):
                 cx.execute('insert into test(id) values(1)')
 
+    @unittest.skipIf(sqlite.sqlite_version_info >= (3, 3, 1),
+                     'needs sqlite versions older than 3.3.1')
+    def CheckSameThreadErrorOnOldVersion(self):
+        with self.assertRaises(sqlite.NotSupportedError) as cm:
+            sqlite.connect(':memory:', check_same_thread=False)
+        self.assertEqual(str(cm.exception), 'shared connections not available')
 
 class CursorTests(unittest.TestCase):
     def setUp(self):
@@ -196,22 +199,12 @@ class CursorTests(unittest.TestCase):
         self.cu.execute("delete from test")
 
     def CheckExecuteIllegalSql(self):
-        try:
+        with self.assertRaises(sqlite.OperationalError):
             self.cu.execute("select asdf")
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError:
-            return
-        except:
-            self.fail("raised wrong exception")
 
     def CheckExecuteTooMuchSql(self):
-        try:
+        with self.assertRaises(sqlite.Warning):
             self.cu.execute("select 5+4; select 4+5")
-            self.fail("should have raised a Warning")
-        except sqlite.Warning:
-            return
-        except:
-            self.fail("raised wrong exception")
 
     def CheckExecuteTooMuchSql2(self):
         self.cu.execute("select 5+4; -- foo bar")
@@ -226,13 +219,8 @@ class CursorTests(unittest.TestCase):
             """)
 
     def CheckExecuteWrongSqlArg(self):
-        try:
+        with self.assertRaises(ValueError):
             self.cu.execute(42)
-            self.fail("should have raised a ValueError")
-        except ValueError:
-            return
-        except:
-            self.fail("raised wrong exception.")
 
     def CheckExecuteArgInt(self):
         self.cu.execute("insert into test(id) values (?)", (42,))
@@ -250,29 +238,25 @@ class CursorTests(unittest.TestCase):
         row = self.cu.fetchone()
         self.assertEqual(row[0], "Hu\x00go")
 
+    def CheckExecuteNonIterable(self):
+        with self.assertRaises(ValueError) as cm:
+            self.cu.execute("insert into test(id) values (?)", 42)
+        self.assertEqual(str(cm.exception), 'parameters are of unsupported type')
+
     def CheckExecuteWrongNoOfArgs1(self):
         # too many parameters
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             self.cu.execute("insert into test(id) values (?)", (17, "Egon"))
-            self.fail("should have raised ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
 
     def CheckExecuteWrongNoOfArgs2(self):
         # too little parameters
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             self.cu.execute("insert into test(id) values (?)")
-            self.fail("should have raised ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
 
     def CheckExecuteWrongNoOfArgs3(self):
         # no parameters, parameters are needed
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             self.cu.execute("insert into test(id) values (?)")
-            self.fail("should have raised ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
 
     def CheckExecuteParamList(self):
         self.cu.execute("insert into test(name) values ('foo')")
@@ -311,27 +295,18 @@ class CursorTests(unittest.TestCase):
 
     def CheckExecuteDictMappingTooLittleArgs(self):
         self.cu.execute("insert into test(name) values ('foo')")
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             self.cu.execute("select name from test where name=:name and id=:id", {"name": "foo"})
-            self.fail("should have raised ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
 
     def CheckExecuteDictMappingNoArgs(self):
         self.cu.execute("insert into test(name) values ('foo')")
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             self.cu.execute("select name from test where name=:name")
-            self.fail("should have raised ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
 
     def CheckExecuteDictMappingUnnamed(self):
         self.cu.execute("insert into test(name) values ('foo')")
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             self.cu.execute("select name from test where name=?", {"name": "foo"})
-            self.fail("should have raised ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
 
     def CheckClose(self):
         self.cu.close()
@@ -360,8 +335,7 @@ class CursorTests(unittest.TestCase):
     def CheckTotalChanges(self):
         self.cu.execute("insert into test(name) values ('foo')")
         self.cu.execute("insert into test(name) values ('foo')")
-        if self.cx.total_changes < 2:
-            self.fail("total changes reported wrong value")
+        self.assertLess(2, self.cx.total_changes, msg='total changes reported wrong value')
 
     # Checks for executemany:
     # Sequences are required by the DB-API, iterators
@@ -392,32 +366,16 @@ class CursorTests(unittest.TestCase):
         self.cu.executemany("insert into test(income) values (?)", mygen())
 
     def CheckExecuteManyWrongSqlArg(self):
-        try:
+        with self.assertRaises(ValueError):
             self.cu.executemany(42, [(3,)])
-            self.fail("should have raised a ValueError")
-        except ValueError:
-            return
-        except:
-            self.fail("raised wrong exception.")
 
     def CheckExecuteManySelect(self):
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             self.cu.executemany("select ?", [(3,)])
-            self.fail("should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            return
-        except:
-            self.fail("raised wrong exception.")
 
     def CheckExecuteManyNotIterable(self):
-        try:
+        with self.assertRaises(TypeError):
             self.cu.executemany("insert into test(income) values (?)", 42)
-            self.fail("should have raised a TypeError")
-        except TypeError:
-            return
-        except Exception as e:
-            print("raised", e.__class__)
-            self.fail("raised wrong exception.")
 
     def CheckFetchIter(self):
         # Optional DB-API extension.
@@ -494,22 +452,15 @@ class CursorTests(unittest.TestCase):
         self.assertEqual(self.cu.connection, self.cx)
 
     def CheckWrongCursorCallable(self):
-        try:
+        with self.assertRaises(TypeError):
             def f(): pass
             cur = self.cx.cursor(f)
-            self.fail("should have raised a TypeError")
-        except TypeError:
-            return
-        self.fail("should have raised a ValueError")
 
     def CheckCursorWrongClass(self):
         class Foo: pass
         foo = Foo()
-        try:
+        with self.assertRaises(TypeError):
             cur = sqlite.Cursor(foo)
-            self.fail("should have raised a ValueError")
-        except TypeError:
-            pass
 
 @unittest.skipUnless(threading, 'This test requires threading.')
 class ThreadTests(unittest.TestCase):
@@ -708,22 +659,21 @@ class ExtensionTests(unittest.TestCase):
     def CheckScriptSyntaxError(self):
         con = sqlite.connect(":memory:")
         cur = con.cursor()
-        raised = False
-        try:
+        with self.assertRaises(sqlite.OperationalError):
             cur.executescript("create table test(x); asdf; create table test2(x)")
-        except sqlite.OperationalError:
-            raised = True
-        self.assertEqual(raised, True, "should have raised an exception")
 
     def CheckScriptErrorNormal(self):
         con = sqlite.connect(":memory:")
         cur = con.cursor()
-        raised = False
-        try:
+        with self.assertRaises(sqlite.OperationalError):
             cur.executescript("create table test(sadfsadfdsa); select foo from hurz;")
-        except sqlite.OperationalError:
-            raised = True
-        self.assertEqual(raised, True, "should have raised an exception")
+
+    def CheckCursorExecutescriptAsBytes(self):
+        con = sqlite.connect(":memory:")
+        cur = con.cursor()
+        with self.assertRaises(ValueError) as cm:
+            cur.executescript(b"create table test(foo); insert into test(foo) values (5);")
+        self.assertEqual(str(cm.exception), 'script argument must be unicode.')
 
     def CheckConnectionExecute(self):
         con = sqlite.connect(":memory:")
@@ -745,68 +695,37 @@ class ExtensionTests(unittest.TestCase):
         self.assertEqual(result, 5, "Basic test of Connection.executescript")
 
 class ClosedConTests(unittest.TestCase):
-    def setUp(self):
-        pass
-
-    def tearDown(self):
-        pass
-
     def CheckClosedConCursor(self):
         con = sqlite.connect(":memory:")
         con.close()
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             cur = con.cursor()
-            self.fail("Should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("Should have raised a ProgrammingError")
 
     def CheckClosedConCommit(self):
         con = sqlite.connect(":memory:")
         con.close()
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             con.commit()
-            self.fail("Should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("Should have raised a ProgrammingError")
 
     def CheckClosedConRollback(self):
         con = sqlite.connect(":memory:")
         con.close()
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             con.rollback()
-            self.fail("Should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("Should have raised a ProgrammingError")
 
     def CheckClosedCurExecute(self):
         con = sqlite.connect(":memory:")
         cur = con.cursor()
         con.close()
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             cur.execute("select 4")
-            self.fail("Should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("Should have raised a ProgrammingError")
 
     def CheckClosedCreateFunction(self):
         con = sqlite.connect(":memory:")
         con.close()
         def f(x): return 17
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             con.create_function("foo", 1, f)
-            self.fail("Should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("Should have raised a ProgrammingError")
 
     def CheckClosedCreateAggregate(self):
         con = sqlite.connect(":memory:")
@@ -818,57 +737,31 @@ class ClosedConTests(unittest.TestCase):
                 pass
             def finalize(self):
                 return 17
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             con.create_aggregate("foo", 1, Agg)
-            self.fail("Should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("Should have raised a ProgrammingError")
 
     def CheckClosedSetAuthorizer(self):
         con = sqlite.connect(":memory:")
         con.close()
         def authorizer(*args):
             return sqlite.DENY
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             con.set_authorizer(authorizer)
-            self.fail("Should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("Should have raised a ProgrammingError")
 
     def CheckClosedSetProgressCallback(self):
         con = sqlite.connect(":memory:")
         con.close()
         def progress(): pass
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             con.set_progress_handler(progress, 100)
-            self.fail("Should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("Should have raised a ProgrammingError")
 
     def CheckClosedCall(self):
         con = sqlite.connect(":memory:")
         con.close()
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             con()
-            self.fail("Should have raised a ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("Should have raised a ProgrammingError")
 
 class ClosedCurTests(unittest.TestCase):
-    def setUp(self):
-        pass
-
-    def tearDown(self):
-        pass
-
     def CheckClosed(self):
         con = sqlite.connect(":memory:")
         cur = con.cursor()
@@ -882,15 +775,103 @@ class ClosedCurTests(unittest.TestCase):
             else:
                 params = []
 
-            try:
+            with self.assertRaises(sqlite.ProgrammingError):
                 method = getattr(cur, method_name)
-
                 method(*params)
-                self.fail("Should have raised a ProgrammingError: method " + method_name)
-            except sqlite.ProgrammingError:
-                pass
-            except:
-                self.fail("Should have raised a ProgrammingError: " + method_name)
+
+
+class SqliteOnConflictTests(unittest.TestCase):
+    """
+    Tests for SQLite's "insert on conflict" feature.
+
+    See https://www.sqlite.org/lang_conflict.html for details.
+    """
+
+    def setUp(self):
+        self.cx = sqlite.connect(":memory:")
+        self.cu = self.cx.cursor()
+        self.cu.execute("""
+          CREATE TABLE test(
+            id INTEGER PRIMARY KEY, name TEXT, unique_name TEXT UNIQUE
+          );
+        """)
+
+    def tearDown(self):
+        self.cu.close()
+        self.cx.close()
+
+    def CheckOnConflictRollbackWithExplicitTransaction(self):
+        self.cx.isolation_level = None  # autocommit mode
+        self.cu = self.cx.cursor()
+        # Start an explicit transaction.
+        self.cu.execute("BEGIN")
+        self.cu.execute("INSERT INTO test(name) VALUES ('abort_test')")
+        self.cu.execute("INSERT OR ROLLBACK INTO test(unique_name) VALUES ('foo')")
+        with self.assertRaises(sqlite.IntegrityError):
+            self.cu.execute("INSERT OR ROLLBACK INTO test(unique_name) VALUES ('foo')")
+        # Use connection to commit.
+        self.cx.commit()
+        self.cu.execute("SELECT name, unique_name from test")
+        # Transaction should have rolled back and nothing should be in table.
+        self.assertEqual(self.cu.fetchall(), [])
+
+    def CheckOnConflictAbortRaisesWithExplicitTransactions(self):
+        # Abort cancels the current sql statement but doesn't change anything
+        # about the current transaction.
+        self.cx.isolation_level = None  # autocommit mode
+        self.cu = self.cx.cursor()
+        # Start an explicit transaction.
+        self.cu.execute("BEGIN")
+        self.cu.execute("INSERT INTO test(name) VALUES ('abort_test')")
+        self.cu.execute("INSERT OR ABORT INTO test(unique_name) VALUES ('foo')")
+        with self.assertRaises(sqlite.IntegrityError):
+            self.cu.execute("INSERT OR ABORT INTO test(unique_name) VALUES ('foo')")
+        self.cx.commit()
+        self.cu.execute("SELECT name, unique_name FROM test")
+        # Expect the first two inserts to work, third to do nothing.
+        self.assertEqual(self.cu.fetchall(), [('abort_test', None), (None, 'foo',)])
+
+    def CheckOnConflictRollbackWithoutTransaction(self):
+        # Start of implicit transaction
+        self.cu.execute("INSERT INTO test(name) VALUES ('abort_test')")
+        self.cu.execute("INSERT OR ROLLBACK INTO test(unique_name) VALUES ('foo')")
+        with self.assertRaises(sqlite.IntegrityError):
+            self.cu.execute("INSERT OR ROLLBACK INTO test(unique_name) VALUES ('foo')")
+        self.cu.execute("SELECT name, unique_name FROM test")
+        # Implicit transaction is rolled back on error.
+        self.assertEqual(self.cu.fetchall(), [])
+
+    def CheckOnConflictAbortRaisesWithoutTransactions(self):
+        # Abort cancels the current sql statement but doesn't change anything
+        # about the current transaction.
+        self.cu.execute("INSERT INTO test(name) VALUES ('abort_test')")
+        self.cu.execute("INSERT OR ABORT INTO test(unique_name) VALUES ('foo')")
+        with self.assertRaises(sqlite.IntegrityError):
+            self.cu.execute("INSERT OR ABORT INTO test(unique_name) VALUES ('foo')")
+        # Make sure all other values were inserted.
+        self.cu.execute("SELECT name, unique_name FROM test")
+        self.assertEqual(self.cu.fetchall(), [('abort_test', None), (None, 'foo',)])
+
+    def CheckOnConflictFail(self):
+        self.cu.execute("INSERT OR FAIL INTO test(unique_name) VALUES ('foo')")
+        with self.assertRaises(sqlite.IntegrityError):
+            self.cu.execute("INSERT OR FAIL INTO test(unique_name) VALUES ('foo')")
+        self.assertEqual(self.cu.fetchall(), [])
+
+    def CheckOnConflictIgnore(self):
+        self.cu.execute("INSERT OR IGNORE INTO test(unique_name) VALUES ('foo')")
+        # Nothing should happen.
+        self.cu.execute("INSERT OR IGNORE INTO test(unique_name) VALUES ('foo')")
+        self.cu.execute("SELECT unique_name FROM test")
+        self.assertEqual(self.cu.fetchall(), [('foo',)])
+
+    def CheckOnConflictReplace(self):
+        self.cu.execute("INSERT OR REPLACE INTO test(name, unique_name) VALUES ('Data!', 'foo')")
+        # There shouldn't be an IntegrityError exception.
+        self.cu.execute("INSERT OR REPLACE INTO test(name, unique_name) VALUES ('Very different data!', 'foo')")
+        self.cu.execute("SELECT name, unique_name FROM test")
+        self.assertEqual(self.cu.fetchall(), [('Very different data!', 'foo')])
+
 
 def suite():
     module_suite = unittest.makeSuite(ModuleTests, "Check")
@@ -901,7 +882,12 @@ def suite():
     ext_suite = unittest.makeSuite(ExtensionTests, "Check")
     closed_con_suite = unittest.makeSuite(ClosedConTests, "Check")
     closed_cur_suite = unittest.makeSuite(ClosedCurTests, "Check")
-    return unittest.TestSuite((module_suite, connection_suite, cursor_suite, thread_suite, constructor_suite, ext_suite, closed_con_suite, closed_cur_suite))
+    on_conflict_suite = unittest.makeSuite(SqliteOnConflictTests, "Check")
+    return unittest.TestSuite((
+        module_suite, connection_suite, cursor_suite, thread_suite,
+        constructor_suite, ext_suite, closed_con_suite, closed_cur_suite,
+        on_conflict_suite,
+    ))
 
 def test():
     runner = unittest.TextTestRunner()
index f587596..ced8445 100644 (file)
@@ -58,9 +58,21 @@ class CursorFactoryTests(unittest.TestCase):
         self.con.close()
 
     def CheckIsInstance(self):
-        cur = self.con.cursor(factory=MyCursor)
+        cur = self.con.cursor()
+        self.assertIsInstance(cur, sqlite.Cursor)
+        cur = self.con.cursor(MyCursor)
+        self.assertIsInstance(cur, MyCursor)
+        cur = self.con.cursor(factory=lambda con: MyCursor(con))
         self.assertIsInstance(cur, MyCursor)
 
+    def CheckInvalidFactory(self):
+        # not a callable at all
+        self.assertRaises(TypeError, self.con.cursor, None)
+        # invalid callable with not exact one argument
+        self.assertRaises(TypeError, self.con.cursor, lambda: None)
+        # invalid callable returning non-cursor
+        self.assertRaises(TypeError, self.con.cursor, lambda con: None)
+
 class RowFactoryTestsBackwardsCompat(unittest.TestCase):
     def setUp(self):
         self.con = sqlite.connect(":memory:")
@@ -183,10 +195,12 @@ class RowFactoryTests(unittest.TestCase):
     def CheckFakeCursorClass(self):
         # Issue #24257: Incorrect use of PyObject_IsInstance() caused
         # segmentation fault.
+        # Issue #27861: Also applies for cursor factory.
         class FakeCursor(str):
             __class__ = sqlite.Cursor
-        cur = self.con.cursor(factory=FakeCursor)
-        self.assertRaises(TypeError, sqlite.Row, cur, ())
+        self.con.row_factory = sqlite.Row
+        self.assertRaises(TypeError, self.con.cursor, FakeCursor)
+        self.assertRaises(TypeError, sqlite.Row, FakeCursor(), ())
 
     def tearDown(self):
         self.con.close()
index ede0bec..f8ef4d8 100644 (file)
@@ -25,27 +25,38 @@ import unittest
 import sqlite3 as sqlite
 
 class CollationTests(unittest.TestCase):
-    def setUp(self):
-        pass
-
-    def tearDown(self):
-        pass
+    def CheckCreateCollationNotString(self):
+        con = sqlite.connect(":memory:")
+        with self.assertRaises(TypeError):
+            con.create_collation(None, lambda x, y: (x > y) - (x < y))
 
     def CheckCreateCollationNotCallable(self):
         con = sqlite.connect(":memory:")
-        try:
+        with self.assertRaises(TypeError) as cm:
             con.create_collation("X", 42)
-            self.fail("should have raised a TypeError")
-        except TypeError as e:
-            self.assertEqual(e.args[0], "parameter must be callable")
+        self.assertEqual(str(cm.exception), 'parameter must be callable')
 
     def CheckCreateCollationNotAscii(self):
         con = sqlite.connect(":memory:")
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             con.create_collation("collä", lambda x, y: (x > y) - (x < y))
-            self.fail("should have raised a ProgrammingError")
-        except sqlite.ProgrammingError as e:
-            pass
+
+    def CheckCreateCollationBadUpper(self):
+        class BadUpperStr(str):
+            def upper(self):
+                return None
+        con = sqlite.connect(":memory:")
+        mycoll = lambda x, y: -((x > y) - (x < y))
+        con.create_collation(BadUpperStr("mycoll"), mycoll)
+        result = con.execute("""
+            select x from (
+            select 'a' as x
+            union
+            select 'b' as x
+            ) order by x collate mycoll
+            """).fetchall()
+        self.assertEqual(result[0][0], 'b')
+        self.assertEqual(result[1][0], 'a')
 
     @unittest.skipIf(sqlite.sqlite_version_info < (3, 2, 1),
                      'old SQLite versions crash on this test')
@@ -66,15 +77,13 @@ class CollationTests(unittest.TestCase):
             ) order by x collate mycoll
             """
         result = con.execute(sql).fetchall()
-        if result[0][0] != "c" or result[1][0] != "b" or result[2][0] != "a":
-            self.fail("the expected order was not returned")
+        self.assertEqual(result, [('c',), ('b',), ('a',)],
+                         msg='the expected order was not returned')
 
         con.create_collation("mycoll", None)
-        try:
+        with self.assertRaises(sqlite.OperationalError) as cm:
             result = con.execute(sql).fetchall()
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError as e:
-            self.assertEqual(e.args[0].lower(), "no such collation sequence: mycoll")
+        self.assertEqual(str(cm.exception), 'no such collation sequence: mycoll')
 
     def CheckCollationReturnsLargeInteger(self):
         def mycoll(x, y):
@@ -106,8 +115,8 @@ class CollationTests(unittest.TestCase):
         result = con.execute("""
             select x from (select 'a' as x union select 'b' as x) order by x collate mycoll
             """).fetchall()
-        if result[0][0] != 'b' or result[1][0] != 'a':
-            self.fail("wrong collation function is used")
+        self.assertEqual(result[0][0], 'b')
+        self.assertEqual(result[1][0], 'a')
 
     def CheckDeregisterCollation(self):
         """
@@ -117,12 +126,9 @@ class CollationTests(unittest.TestCase):
         con = sqlite.connect(":memory:")
         con.create_collation("mycoll", lambda x, y: (x > y) - (x < y))
         con.create_collation("mycoll", None)
-        try:
+        with self.assertRaises(sqlite.OperationalError) as cm:
             con.execute("select 'a' as x union select 'b' as x order by x collate mycoll")
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError as e:
-            if not e.args[0].startswith("no such collation sequence"):
-                self.fail("wrong OperationalError raised")
+        self.assertEqual(str(cm.exception), 'no such collation sequence: mycoll')
 
 class ProgressTests(unittest.TestCase):
     def CheckProgressHandlerUsed(self):
index 11adb30..7dd0050 100644 (file)
@@ -84,9 +84,8 @@ class RegressionTests(unittest.TestCase):
             cur.execute("select 1 x union select " + str(i))
         con.close()
 
+    @unittest.skipIf(sqlite.sqlite_version_info < (3, 2, 2), 'needs sqlite 3.2.2 or newer')
     def CheckOnConflictRollback(self):
-        if sqlite.sqlite_version_info < (3, 2, 2):
-            return
         con = sqlite.connect(":memory:")
         con.execute("create table foo(x, unique(x) on conflict rollback)")
         con.execute("insert into foo(x) values (1)")
@@ -134,17 +133,11 @@ class RegressionTests(unittest.TestCase):
     def CheckErrorMsgDecodeError(self):
         # When porting the module to Python 3.0, the error message about
         # decoding errors disappeared. This verifies they're back again.
-        failure = None
-        try:
+        with self.assertRaises(sqlite.OperationalError) as cm:
             self.con.execute("select 'xxx' || ? || 'yyy' colname",
                              (bytes(bytearray([250])),)).fetchone()
-            failure = "should have raised an OperationalError with detailed description"
-        except sqlite.OperationalError as e:
-            msg = e.args[0]
-            if not msg.startswith("Could not decode to UTF-8 column 'colname' with text 'xxx"):
-                failure = "OperationalError did not have expected description text"
-        if failure:
-            self.fail(failure)
+        msg = "Could not decode to UTF-8 column 'colname' with text 'xxx"
+        self.assertIn(msg, str(cm.exception))
 
     def CheckRegisterAdapter(self):
         """
@@ -153,11 +146,34 @@ class RegressionTests(unittest.TestCase):
         self.assertRaises(TypeError, sqlite.register_adapter, {}, None)
 
     def CheckSetIsolationLevel(self):
-        """
-        See issue 3312.
-        """
+        # See issue 27881.
+        class CustomStr(str):
+            def upper(self):
+                return None
+            def __del__(self):
+                con.isolation_level = ""
+
         con = sqlite.connect(":memory:")
-        setattr(con, "isolation_level", "\xe9")
+        con.isolation_level = None
+        for level in "", "DEFERRED", "IMMEDIATE", "EXCLUSIVE":
+            with self.subTest(level=level):
+                con.isolation_level = level
+                con.isolation_level = level.lower()
+                con.isolation_level = level.capitalize()
+                con.isolation_level = CustomStr(level)
+
+        # setting isolation_level failure should not alter previous state
+        con.isolation_level = None
+        con.isolation_level = "DEFERRED"
+        pairs = [
+            (1, TypeError), (b'', TypeError), ("abc", ValueError),
+            ("IMMEDIATE\0EXCLUSIVE", ValueError), ("\xe9", ValueError),
+        ]
+        for value, exc in pairs:
+            with self.subTest(level=value):
+                with self.assertRaises(exc):
+                    con.isolation_level = value
+                self.assertEqual(con.isolation_level, "DEFERRED")
 
     def CheckCursorConstructorCallCheck(self):
         """
@@ -170,14 +186,8 @@ class RegressionTests(unittest.TestCase):
 
         con = sqlite.connect(":memory:")
         cur = Cursor(con)
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             cur.execute("select 4+5").fetchall()
-            self.fail("should have raised ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("should have raised ProgrammingError")
-
 
     def CheckStrSubclass(self):
         """
@@ -196,13 +206,8 @@ class RegressionTests(unittest.TestCase):
                 pass
 
         con = Connection(":memory:")
-        try:
+        with self.assertRaises(sqlite.ProgrammingError):
             cur = con.cursor()
-            self.fail("should have raised ProgrammingError")
-        except sqlite.ProgrammingError:
-            pass
-        except:
-            self.fail("should have raised ProgrammingError")
 
     def CheckCursorRegistration(self):
         """
@@ -223,13 +228,8 @@ class RegressionTests(unittest.TestCase):
         cur.executemany("insert into foo(x) values (?)", [(3,), (4,), (5,)])
         cur.execute("select x from foo")
         con.rollback()
-        try:
+        with self.assertRaises(sqlite.InterfaceError):
             cur.fetchall()
-            self.fail("should have raised InterfaceError")
-        except sqlite.InterfaceError:
-            pass
-        except:
-            self.fail("should have raised InterfaceError")
 
     def CheckAutoCommit(self):
         """
@@ -345,6 +345,37 @@ class RegressionTests(unittest.TestCase):
         self.assertRaises(ValueError, cur.execute, " \0select 2")
         self.assertRaises(ValueError, cur.execute, "select 2\0")
 
+    def CheckCommitCursorReset(self):
+        """
+        Connection.commit() did reset cursors, which made sqlite3
+        to return rows multiple times when fetched from cursors
+        after commit. See issues 10513 and 23129 for details.
+        """
+        con = sqlite.connect(":memory:")
+        con.executescript("""
+        create table t(c);
+        create table t2(c);
+        insert into t values(0);
+        insert into t values(1);
+        insert into t values(2);
+        """)
+
+        self.assertEqual(con.isolation_level, "")
+
+        counter = 0
+        for i, row in enumerate(con.execute("select c from t")):
+            with self.subTest(i=i, row=row):
+                con.execute("insert into t2(c) values (?)", (i,))
+                con.commit()
+                if counter == 0:
+                    self.assertEqual(row[0], 0)
+                elif counter == 1:
+                    self.assertEqual(row[0], 1)
+                elif counter == 2:
+                    self.assertEqual(row[0], 2)
+                counter += 1
+        self.assertEqual(counter, 3, "should have returned exactly three rows")
+
 
 def suite():
     regression_suite = unittest.makeSuite(RegressionTests, "Check")
index feb4fa1..a25360a 100644 (file)
@@ -111,39 +111,25 @@ class TransactionTests(unittest.TestCase):
         res = self.cur2.fetchall()
         self.assertEqual(len(res), 1)
 
+    @unittest.skipIf(sqlite.sqlite_version_info < (3, 2, 2),
+                     'test hangs on sqlite versions older than 3.2.2')
     def CheckRaiseTimeout(self):
-        if sqlite.sqlite_version_info < (3, 2, 2):
-            # This will fail (hang) on earlier versions of sqlite.
-            # Determine exact version it was fixed. 3.2.1 hangs.
-            return
         self.cur1.execute("create table test(i)")
         self.cur1.execute("insert into test(i) values (5)")
-        try:
+        with self.assertRaises(sqlite.OperationalError):
             self.cur2.execute("insert into test(i) values (5)")
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError:
-            pass
-        except:
-            self.fail("should have raised an OperationalError")
 
+    @unittest.skipIf(sqlite.sqlite_version_info < (3, 2, 2),
+                     'test hangs on sqlite versions older than 3.2.2')
     def CheckLocking(self):
         """
         This tests the improved concurrency with pysqlite 2.3.4. You needed
         to roll back con2 before you could commit con1.
         """
-        if sqlite.sqlite_version_info < (3, 2, 2):
-            # This will fail (hang) on earlier versions of sqlite.
-            # Determine exact version it was fixed. 3.2.1 hangs.
-            return
         self.cur1.execute("create table test(i)")
         self.cur1.execute("insert into test(i) values (5)")
-        try:
+        with self.assertRaises(sqlite.OperationalError):
             self.cur2.execute("insert into test(i) values (5)")
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError:
-            pass
-        except:
-            self.fail("should have raised an OperationalError")
         # NO self.con2.rollback() HERE!!!
         self.con1.commit()
 
@@ -159,13 +145,8 @@ class TransactionTests(unittest.TestCase):
         cur.execute("select 1 union select 2 union select 3")
 
         con.rollback()
-        try:
+        with self.assertRaises(sqlite.InterfaceError):
             cur.fetchall()
-            self.fail("InterfaceError should have been raised")
-        except sqlite.InterfaceError as e:
-            pass
-        except:
-            self.fail("InterfaceError should have been raised")
 
 class SpecialCommandTests(unittest.TestCase):
     def setUp(self):
index adad571..6bc8d71 100644 (file)
@@ -185,24 +185,14 @@ class DeclTypesTests(unittest.TestCase):
     def CheckUnsupportedSeq(self):
         class Bar: pass
         val = Bar()
-        try:
+        with self.assertRaises(sqlite.InterfaceError):
             self.cur.execute("insert into test(f) values (?)", (val,))
-            self.fail("should have raised an InterfaceError")
-        except sqlite.InterfaceError:
-            pass
-        except:
-            self.fail("should have raised an InterfaceError")
 
     def CheckUnsupportedDict(self):
         class Bar: pass
         val = Bar()
-        try:
+        with self.assertRaises(sqlite.InterfaceError):
             self.cur.execute("insert into test(f) values (:val)", {"val": val})
-            self.fail("should have raised an InterfaceError")
-        except sqlite.InterfaceError:
-            pass
-        except:
-            self.fail("should have raised an InterfaceError")
 
     def CheckBlob(self):
         # default
@@ -284,6 +274,45 @@ class ColNamesTests(unittest.TestCase):
         self.cur.execute("select * from test where 0 = 1")
         self.assertEqual(self.cur.description[0][0], "x")
 
+    def CheckCursorDescriptionInsert(self):
+        self.cur.execute("insert into test values (1)")
+        self.assertIsNone(self.cur.description)
+
+
+@unittest.skipIf(sqlite.sqlite_version_info < (3, 8, 3), "CTEs not supported")
+class CommonTableExpressionTests(unittest.TestCase):
+
+    def setUp(self):
+        self.con = sqlite.connect(":memory:")
+        self.cur = self.con.cursor()
+        self.cur.execute("create table test(x foo)")
+
+    def tearDown(self):
+        self.cur.close()
+        self.con.close()
+
+    def CheckCursorDescriptionCTESimple(self):
+        self.cur.execute("with one as (select 1) select * from one")
+        self.assertIsNotNone(self.cur.description)
+        self.assertEqual(self.cur.description[0][0], "1")
+
+    def CheckCursorDescriptionCTESMultipleColumns(self):
+        self.cur.execute("insert into test values(1)")
+        self.cur.execute("insert into test values(2)")
+        self.cur.execute("with testCTE as (select * from test) select * from testCTE")
+        self.assertIsNotNone(self.cur.description)
+        self.assertEqual(self.cur.description[0][0], "x")
+
+    def CheckCursorDescriptionCTE(self):
+        self.cur.execute("insert into test values (1)")
+        self.cur.execute("with bar as (select * from test) select * from test where x = 1")
+        self.assertIsNotNone(self.cur.description)
+        self.assertEqual(self.cur.description[0][0], "x")
+        self.cur.execute("with bar as (select * from test) select * from test where x = 2")
+        self.assertIsNotNone(self.cur.description)
+        self.assertEqual(self.cur.description[0][0], "x")
+
+
 class ObjectAdaptationTests(unittest.TestCase):
     def cast(obj):
         return float(obj)
@@ -350,13 +379,10 @@ class DateTimeTests(unittest.TestCase):
         ts2 = self.cur.fetchone()[0]
         self.assertEqual(ts, ts2)
 
+    @unittest.skipIf(sqlite.sqlite_version_info < (3, 1),
+                     'the date functions are available on 3.1 or later')
     def CheckSqlTimestamp(self):
-        # The date functions are only available in SQLite version 3.1 or later
-        if sqlite.sqlite_version_info < (3, 1):
-            return
-
-        # SQLite's current_timestamp uses UTC time, while datetime.datetime.now() uses local time.
-        now = datetime.datetime.now()
+        now = datetime.datetime.utcnow()
         self.cur.execute("insert into test(ts) values (current_timestamp)")
         self.cur.execute("select ts from test")
         ts = self.cur.fetchone()[0]
@@ -384,7 +410,8 @@ def suite():
     adaptation_suite = unittest.makeSuite(ObjectAdaptationTests, "Check")
     bin_suite = unittest.makeSuite(BinaryConverterTests, "Check")
     date_suite = unittest.makeSuite(DateTimeTests, "Check")
-    return unittest.TestSuite((sqlite_type_suite, decltypes_type_suite, colnames_type_suite, adaptation_suite, bin_suite, date_suite))
+    cte_suite = unittest.makeSuite(CommonTableExpressionTests, "Check")
+    return unittest.TestSuite((sqlite_type_suite, decltypes_type_suite, colnames_type_suite, adaptation_suite, bin_suite, date_suite, cte_suite))
 
 def test():
     runner = unittest.TextTestRunner()
index 8a4bbab..4075045 100644 (file)
@@ -162,11 +162,8 @@ class FunctionTests(unittest.TestCase):
         self.con.close()
 
     def CheckFuncErrorOnCreate(self):
-        try:
+        with self.assertRaises(sqlite.OperationalError):
             self.con.create_function("bla", -100, lambda x: 2*x)
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError:
-            pass
 
     def CheckFuncRefCount(self):
         def getfunc():
@@ -231,12 +228,10 @@ class FunctionTests(unittest.TestCase):
 
     def CheckFuncException(self):
         cur = self.con.cursor()
-        try:
+        with self.assertRaises(sqlite.OperationalError) as cm:
             cur.execute("select raiseexception()")
             cur.fetchone()
-            self.fail("should have raised OperationalError")
-        except sqlite.OperationalError as e:
-            self.assertEqual(e.args[0], 'user-defined function raised exception')
+        self.assertEqual(str(cm.exception), 'user-defined function raised exception')
 
     def CheckParamString(self):
         cur = self.con.cursor()
@@ -312,55 +307,42 @@ class AggregateTests(unittest.TestCase):
         pass
 
     def CheckAggrErrorOnCreate(self):
-        try:
+        with self.assertRaises(sqlite.OperationalError):
             self.con.create_function("bla", -100, AggrSum)
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError:
-            pass
 
     def CheckAggrNoStep(self):
         cur = self.con.cursor()
-        try:
+        with self.assertRaises(AttributeError) as cm:
             cur.execute("select nostep(t) from test")
-            self.fail("should have raised an AttributeError")
-        except AttributeError as e:
-            self.assertEqual(e.args[0], "'AggrNoStep' object has no attribute 'step'")
+        self.assertEqual(str(cm.exception), "'AggrNoStep' object has no attribute 'step'")
 
     def CheckAggrNoFinalize(self):
         cur = self.con.cursor()
-        try:
+        with self.assertRaises(sqlite.OperationalError) as cm:
             cur.execute("select nofinalize(t) from test")
             val = cur.fetchone()[0]
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError as e:
-            self.assertEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error")
+        self.assertEqual(str(cm.exception), "user-defined aggregate's 'finalize' method raised error")
 
     def CheckAggrExceptionInInit(self):
         cur = self.con.cursor()
-        try:
+        with self.assertRaises(sqlite.OperationalError) as cm:
             cur.execute("select excInit(t) from test")
             val = cur.fetchone()[0]
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError as e:
-            self.assertEqual(e.args[0], "user-defined aggregate's '__init__' method raised error")
+        self.assertEqual(str(cm.exception), "user-defined aggregate's '__init__' method raised error")
 
     def CheckAggrExceptionInStep(self):
         cur = self.con.cursor()
-        try:
+        with self.assertRaises(sqlite.OperationalError) as cm:
             cur.execute("select excStep(t) from test")
             val = cur.fetchone()[0]
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError as e:
-            self.assertEqual(e.args[0], "user-defined aggregate's 'step' method raised error")
+        self.assertEqual(str(cm.exception), "user-defined aggregate's 'step' method raised error")
 
     def CheckAggrExceptionInFinalize(self):
         cur = self.con.cursor()
-        try:
+        with self.assertRaises(sqlite.OperationalError) as cm:
             cur.execute("select excFinalize(t) from test")
             val = cur.fetchone()[0]
-            self.fail("should have raised an OperationalError")
-        except sqlite.OperationalError as e:
-            self.assertEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error")
+        self.assertEqual(str(cm.exception), "user-defined aggregate's 'finalize' method raised error")
 
     def CheckAggrCheckParamStr(self):
         cur = self.con.cursor()
@@ -433,22 +415,14 @@ class AuthorizerTests(unittest.TestCase):
         pass
 
     def test_table_access(self):
-        try:
+        with self.assertRaises(sqlite.DatabaseError) as cm:
             self.con.execute("select * from t2")
-        except sqlite.DatabaseError as e:
-            if not e.args[0].endswith("prohibited"):
-                self.fail("wrong exception text: %s" % e.args[0])
-            return
-        self.fail("should have raised an exception due to missing privileges")
+        self.assertIn('prohibited', str(cm.exception))
 
     def test_column_access(self):
-        try:
+        with self.assertRaises(sqlite.DatabaseError) as cm:
             self.con.execute("select c2 from t1")
-        except sqlite.DatabaseError as e:
-            if not e.args[0].endswith("prohibited"):
-                self.fail("wrong exception text: %s" % e.args[0])
-            return
-        self.fail("should have raised an exception due to missing privileges")
+        self.assertIn('prohibited', str(cm.exception))
 
 class AuthorizerRaiseExceptionTests(AuthorizerTests):
     @staticmethod
index 3f5c3c4..e191390 100644 (file)
@@ -51,6 +51,7 @@ The following constants identify various SSL protocol variants:
 PROTOCOL_SSLv2
 PROTOCOL_SSLv3
 PROTOCOL_SSLv23
+PROTOCOL_TLS
 PROTOCOL_TLSv1
 PROTOCOL_TLSv1_1
 PROTOCOL_TLSv1_2
@@ -128,9 +129,10 @@ from _ssl import _OPENSSL_API_VERSION
 
 _IntEnum._convert(
         '_SSLMethod', __name__,
-        lambda name: name.startswith('PROTOCOL_'),
+        lambda name: name.startswith('PROTOCOL_') and name != 'PROTOCOL_SSLv23',
         source=_ssl)
 
+PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS
 _PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()}
 
 try:
@@ -155,36 +157,42 @@ if _ssl.HAS_TLS_UNIQUE:
 else:
     CHANNEL_BINDING_TYPES = []
 
+
 # Disable weak or insecure ciphers by default
 # (OpenSSL's default setting is 'DEFAULT:!aNULL:!eNULL')
 # Enable a better set of ciphers by default
 # This list has been explicitly chosen to:
 #   * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
 #   * Prefer ECDHE over DHE for better performance
-#   * Prefer any AES-GCM over any AES-CBC for better performance and security
+#   * Prefer AEAD over CBC for better performance and security
+#   * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
+#     (ChaCha20 needs OpenSSL 1.1.0 or patched 1.0.2)
+#   * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
+#     performance and security
 #   * Then Use HIGH cipher suites as a fallback
-#   * Then Use 3DES as fallback which is secure but slow
-#   * Disable NULL authentication, NULL encryption, and MD5 MACs for security
-#     reasons
+#   * Disable NULL authentication, NULL encryption, 3DES and MD5 MACs
+#     for security reasons
 _DEFAULT_CIPHERS = (
-    'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
-    'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
-    '!eNULL:!MD5'
-)
+    'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
+    'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
+    '!aNULL:!eNULL:!MD5:!3DES'
+    )
 
 # Restricted and more secure ciphers for the server side
 # This list has been explicitly chosen to:
 #   * Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE)
 #   * Prefer ECDHE over DHE for better performance
-#   * Prefer any AES-GCM over any AES-CBC for better performance and security
+#   * Prefer AEAD over CBC for better performance and security
+#   * Prefer AES-GCM over ChaCha20 because most platforms have AES-NI
+#   * Prefer any AES-GCM and ChaCha20 over any AES-CBC for better
+#     performance and security
 #   * Then Use HIGH cipher suites as a fallback
-#   * Then Use 3DES as fallback which is secure but slow
-#   * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, and RC4 for
-#     security reasons
+#   * Disable NULL authentication, NULL encryption, MD5 MACs, DSS, RC4, and
+#     3DES for security reasons
 _RESTRICTED_SERVER_CIPHERS = (
-    'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:'
-    'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:!aNULL:'
-    '!eNULL:!MD5:!DSS:!RC4'
+    'ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:'
+    'ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:'
+    '!aNULL:!eNULL:!MD5:!DSS:!RC4:!3DES'
 )
 
 
@@ -357,13 +365,13 @@ class SSLContext(_SSLContext):
     __slots__ = ('protocol', '__weakref__')
     _windows_cert_stores = ("CA", "ROOT")
 
-    def __new__(cls, protocol, *args, **kwargs):
+    def __new__(cls, protocol=PROTOCOL_TLS, *args, **kwargs):
         self = _SSLContext.__new__(cls, protocol)
         if protocol != _SSLv2_IF_EXISTS:
             self.set_ciphers(_DEFAULT_CIPHERS)
         return self
 
-    def __init__(self, protocol):
+    def __init__(self, protocol=PROTOCOL_TLS):
         self.protocol = protocol
 
     def wrap_socket(self, sock, server_side=False,
@@ -438,7 +446,7 @@ def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
     if not isinstance(purpose, _ASN1Object):
         raise TypeError(purpose)
 
-    context = SSLContext(PROTOCOL_SSLv23)
+    context = SSLContext(PROTOCOL_TLS)
 
     # SSLv2 considered harmful.
     context.options |= OP_NO_SSLv2
@@ -475,7 +483,7 @@ def create_default_context(purpose=Purpose.SERVER_AUTH, *, cafile=None,
         context.load_default_certs(purpose)
     return context
 
-def _create_unverified_context(protocol=PROTOCOL_SSLv23, *, cert_reqs=None,
+def _create_unverified_context(protocol=PROTOCOL_TLS, *, cert_reqs=None,
                            check_hostname=False, purpose=Purpose.SERVER_AUTH,
                            certfile=None, keyfile=None,
                            cafile=None, capath=None, cadata=None):
@@ -666,7 +674,7 @@ class SSLSocket(socket):
 
     def __init__(self, sock=None, keyfile=None, certfile=None,
                  server_side=False, cert_reqs=CERT_NONE,
-                 ssl_version=PROTOCOL_SSLv23, ca_certs=None,
+                 ssl_version=PROTOCOL_TLS, ca_certs=None,
                  do_handshake_on_connect=True,
                  family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None,
                  suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
@@ -1056,7 +1064,7 @@ class SSLSocket(socket):
 
 def wrap_socket(sock, keyfile=None, certfile=None,
                 server_side=False, cert_reqs=CERT_NONE,
-                ssl_version=PROTOCOL_SSLv23, ca_certs=None,
+                ssl_version=PROTOCOL_TLS, ca_certs=None,
                 do_handshake_on_connect=True,
                 suppress_ragged_eofs=True,
                 ciphers=None):
@@ -1125,7 +1133,7 @@ def PEM_cert_to_DER_cert(pem_cert_string):
     d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)]
     return base64.decodebytes(d.encode('ASCII', 'strict'))
 
-def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None):
+def get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):
     """Retrieve the certificate from the server at the specified address,
     and return it as a PEM-encoded string.
     If 'ca_certs' is specified, validate the server cert against it.
index d8d6ab2..502e26b 100644 (file)
 # Licensed to PSF under a Contributor Agreement.
 # See http://www.python.org/2.4/license for licensing details.
 
-r"""subprocess - Subprocesses with accessible I/O streams
+r"""Subprocesses with accessible I/O streams
 
 This module allows you to spawn processes, connect to their
-input/output/error pipes, and obtain their return codes.  This module
-intends to replace several older modules and functions:
-
-os.system
-os.spawn*
-
-Information about how the subprocess module can be used to replace these
-modules and functions can be found below.
-
-
-
-Using the subprocess module
-===========================
-This module defines one class called Popen:
-
-class Popen(args, bufsize=-1, executable=None,
-            stdin=None, stdout=None, 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=()):
-
-
-Arguments are:
-
-args should be a string, or a sequence of program arguments.  The
-program to execute is normally the first item in the args sequence or
-string, but can be explicitly set by using the executable argument.
-
-On POSIX, with shell=False (default): In this case, the Popen class
-uses os.execvp() to execute the child program.  args should normally
-be a sequence.  A string will be treated as a sequence with the string
-as the only item (the program to execute).
-
-On POSIX, with shell=True: If args is a string, it specifies the
-command string to execute through the shell.  If args is a sequence,
-the first item specifies the command string, and any additional items
-will be treated as additional shell arguments.
-
-On Windows: the Popen class uses CreateProcess() to execute the child
-program, which operates on strings.  If args is a sequence, it will be
-converted to a string using the list2cmdline method.  Please note that
-not all MS Windows applications interpret the command line the same
-way: The list2cmdline is designed for applications using the same
-rules as the MS C runtime.
-
-bufsize will be supplied as the corresponding argument to the io.open()
-function when creating the stdin/stdout/stderr pipe file objects:
-0 means unbuffered (read & write are one system call and can return short),
-1 means line buffered, any other positive value means use a buffer of
-approximately that size.  A negative bufsize, the default, means the system
-default of io.DEFAULT_BUFFER_SIZE will be used.
-
-stdin, stdout and stderr specify the executed programs' standard
-input, standard output and standard error file handles, respectively.
-Valid values are PIPE, an existing file descriptor (a positive
-integer), an existing file object, and None.  PIPE indicates that a
-new pipe to the child should be created.  With None, no redirection
-will occur; the child's file handles will be inherited from the
-parent.  Additionally, stderr can be STDOUT, which indicates that the
-stderr data from the applications should be captured into the same
-file handle as for stdout.
-
-On POSIX, if preexec_fn is set to a callable object, this object will be
-called in the child process just before the child is executed.  The use
-of preexec_fn is not thread safe, using it in the presence of threads
-could lead to a deadlock in the child process before the new executable
-is executed.
-
-If close_fds is true, all file descriptors except 0, 1 and 2 will be
-closed before the child process is executed.  The default for close_fds
-varies by platform:  Always true on POSIX.  True when stdin/stdout/stderr
-are None on Windows, false otherwise.
-
-pass_fds is an optional sequence of file descriptors to keep open between the
-parent and child.  Providing any pass_fds implicitly sets close_fds to true.
-
-if shell is true, the specified command will be executed through the
-shell.
-
-If cwd is not None, the current directory will be changed to cwd
-before the child is executed.
-
-On POSIX, if restore_signals is True all signals that Python sets to
-SIG_IGN are restored to SIG_DFL in the child process before the exec.
-Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals.  This
-parameter does nothing on Windows.
-
-On POSIX, if start_new_session is True, the setsid() system call will be made
-in the child process prior to executing the command.
-
-If env is not None, it defines the environment variables for the new
-process.
-
-If universal_newlines is False, the file objects stdin, stdout and stderr
-are opened as binary files, and no line ending conversion is done.
-
-If universal_newlines is True, the file objects stdout and stderr are
-opened as a text file, but lines may be terminated by any of '\n',
-the Unix end-of-line convention, '\r', the old Macintosh convention or
-'\r\n', the Windows convention.  All of these external representations
-are seen as '\n' by the Python program.  Also, the newlines attribute
-of the file objects stdout, stdin and stderr are not updated by the
-communicate() method.
-
-In either case, the process being communicated with should start up
-expecting to receive bytes on its standard input and decode them with
-the same encoding they are sent in.
-
-The startupinfo and creationflags, if given, will be passed to the
-underlying CreateProcess() function.  They can specify things such as
-appearance of the main window and priority for the new process.
-(Windows only)
-
-
-This module also defines some shortcut functions:
-
-call(*popenargs, **kwargs):
-    Run command with arguments.  Wait for command to complete, then
-    return the returncode attribute.
-
-    The arguments are the same as for the Popen constructor.  Example:
-
-    >>> retcode = subprocess.call(["ls", "-l"])
-
-check_call(*popenargs, **kwargs):
-    Run command with arguments.  Wait for command to complete.  If the
-    exit code was zero then return, otherwise raise
-    CalledProcessError.  The CalledProcessError object will have the
-    return code in the returncode attribute.
-
-    The arguments are the same as for the Popen constructor.  Example:
-
-    >>> subprocess.check_call(["ls", "-l"])
-    0
-
-getstatusoutput(cmd):
-    Return (status, output) of executing cmd in a shell.
-
-    Execute the string 'cmd' in a shell with 'check_output' and
-    return a 2-tuple (status, output). Universal newlines mode is used,
-    meaning that the result with be decoded to a string.
-
-    A trailing newline is stripped from the output.
-    The exit status for the command can be interpreted
-    according to the rules for the function 'wait'.  Example:
-
-    >>> subprocess.getstatusoutput('ls /bin/ls')
-    (0, '/bin/ls')
-    >>> subprocess.getstatusoutput('cat /bin/junk')
-    (256, 'cat: /bin/junk: No such file or directory')
-    >>> subprocess.getstatusoutput('/bin/junk')
-    (256, 'sh: /bin/junk: not found')
-
-getoutput(cmd):
-    Return output (stdout or stderr) of executing cmd in a shell.
-
-    Like getstatusoutput(), except the exit status is ignored and the return
-    value is a string containing the command's output.  Example:
-
-    >>> subprocess.getoutput('ls /bin/ls')
-    '/bin/ls'
-
-check_output(*popenargs, **kwargs):
-    Run command with arguments and return its output.
-
-    If the exit code was non-zero it raises a CalledProcessError.  The
-    CalledProcessError object will have the return code in the returncode
-    attribute and output in the output attribute.
-
-    The arguments are the same as for the Popen constructor.  Example:
-
-    >>> output = subprocess.check_output(["ls", "-l", "/dev/null"])
-
-    There is an additional optional argument, "input", allowing you to
-    pass a string to the subprocess's stdin.  If you use this argument
-    you may not also use the Popen constructor's "stdin" argument.
-
-    If universal_newlines is set to True, the "input" argument must
-    be a string rather than bytes, and the return value will be a string.
-
-Exceptions
-----------
-Exceptions raised in the child process, before the new program has
-started to execute, will be re-raised in the parent.  Additionally,
-the exception object will have one extra attribute called
-'child_traceback', which is a string containing traceback information
-from the child's point of view.
-
-The most common exception raised is OSError.  This occurs, for
-example, when trying to execute a non-existent file.  Applications
-should prepare for OSErrors.
-
-A ValueError will be raised if Popen is called with invalid arguments.
-
-Exceptions defined within this module inherit from SubprocessError.
-check_call() and check_output() will raise CalledProcessError if the
-called process returns a non-zero return code.  TimeoutExpired
-be raised if a timeout was specified and expired.
-
-
-Security
---------
-Unlike some other popen functions, this implementation will never call
-/bin/sh implicitly.  This means that all characters, including shell
-metacharacters, can safely be passed to child processes.
-
-
-Popen objects
-=============
-Instances of the Popen class have the following methods:
-
-poll()
-    Check if child process has terminated.  Returns returncode
-    attribute.
-
-wait()
-    Wait for child process to terminate.  Returns returncode attribute.
-
-communicate(input=None)
-    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. If the Popen instance was constructed with universal_newlines
-    set to True, the input argument should be a string and will be encoded
-    using the preferred system encoding (see locale.getpreferredencoding);
-    if universal_newlines is False, the input argument should be a
-    byte string.
-
-    communicate() returns a tuple (stdout, stderr).
-
-    Note: The data read is buffered in memory, so do not use this
-    method if the data size is large or unlimited.
-
-The following attributes are also available:
-
-stdin
-    If the stdin argument is PIPE, this attribute is a file object
-    that provides input to the child process.  Otherwise, it is None.
-
-stdout
-    If the stdout argument is PIPE, this attribute is a file object
-    that provides output from the child process.  Otherwise, it is
-    None.
-
-stderr
-    If the stderr argument is PIPE, this attribute is file object that
-    provides error output from the child process.  Otherwise, it is
-    None.
-
-pid
-    The process ID of the child process.
-
-returncode
-    The child return code.  A None value indicates that the process
-    hasn't terminated yet.  A negative value -N indicates that the
-    child was terminated by signal N (POSIX only).
-
-
-Replacing older functions with the subprocess module
-====================================================
-In this section, "a ==> b" means that b can be used as a replacement
-for a.
-
-Note: All functions in this section fail (more or less) silently if
-the executed program cannot be found; this module raises an OSError
-exception.
-
-In the following examples, we assume that the subprocess module is
-imported with "from subprocess import *".
-
-
-Replacing /bin/sh shell backquote
----------------------------------
-output=`mycmd myarg`
-==>
-output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
-
-
-Replacing shell pipe line
--------------------------
-output=`dmesg | grep hda`
-==>
-p1 = Popen(["dmesg"], stdout=PIPE)
-p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
-output = p2.communicate()[0]
-
-
-Replacing os.system()
----------------------
-sts = os.system("mycmd" + " myarg")
-==>
-p = Popen("mycmd" + " myarg", shell=True)
-pid, sts = os.waitpid(p.pid, 0)
-
-Note:
-
-* Calling the program through the shell is usually not required.
-
-* It's easier to look at the returncode attribute than the
-  exitstatus.
-
-A more real-world example would look like this:
-
-try:
-    retcode = call("mycmd" + " myarg", shell=True)
-    if retcode < 0:
-        print("Child was terminated by signal", -retcode, file=sys.stderr)
-    else:
-        print("Child returned", retcode, file=sys.stderr)
-except OSError as e:
-    print("Execution failed:", e, file=sys.stderr)
-
-
-Replacing os.spawn*
--------------------
-P_NOWAIT example:
-
-pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
-==>
-pid = Popen(["/bin/mycmd", "myarg"]).pid
-
-
-P_WAIT example:
-
-retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
-==>
-retcode = call(["/bin/mycmd", "myarg"])
-
-
-Vector example:
-
-os.spawnvp(os.P_NOWAIT, path, args)
-==>
-Popen([path] + args[1:])
-
-
-Environment example:
-
-os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
-==>
-Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
+input/output/error pipes, and obtain their return codes.
+
+For a complete description of this module see the Python documentation.
+
+Main API
+========
+run(...): Runs a command, waits for it to complete, then returns a
+          CompletedProcess instance.
+Popen(...): A class for flexibly executing a command in a new process
+
+Constants
+---------
+DEVNULL: Special value that indicates that os.devnull should be used
+PIPE:    Special value that indicates a pipe should be created
+STDOUT:  Special value that indicates that stderr should go to stdout
+
+
+Older API
+=========
+call(...): Runs a command, waits for it to complete, then returns
+    the return code.
+check_call(...): Same as call() but raises CalledProcessError()
+    if return code is not 0
+check_output(...): Same as check_call() but returns the contents of
+    stdout instead of a return code
+getoutput(...): Runs a command in the shell, waits for it to complete,
+    then returns the output
+getstatusoutput(...): Runs a command in the shell, waits for it to complete,
+    then returns a (status, output) tuple
 """
 
 import sys
@@ -372,10 +58,11 @@ class SubprocessError(Exception): pass
 
 
 class CalledProcessError(SubprocessError):
-    """This exception is raised when a process run by check_call() or
-    check_output() returns a non-zero exit status.
-    The exit status will be stored in the returncode attribute;
-    check_output() will also store the output in the output attribute.
+    """Raised when run() is called with check=True and the process
+    returns a non-zero exit status.
+
+    Attributes:
+      cmd, returncode, stdout, stderr, output
     """
     def __init__(self, returncode, cmd, output=None, stderr=None):
         self.returncode = returncode
@@ -401,6 +88,9 @@ class CalledProcessError(SubprocessError):
 class TimeoutExpired(SubprocessError):
     """This exception is raised when the timeout expires while waiting for a
     child process.
+
+    Attributes:
+        cmd, output, stdout, stderr, timeout
     """
     def __init__(self, cmd, timeout, output=None, stderr=None):
         self.cmd = cmd
@@ -828,7 +518,46 @@ _PLATFORM_DEFAULT_CLOSE_FDS = object()
 
 
 class Popen(object):
+    """ Execute a child program in a new process.
+
+    For a complete description of the arguments see the Python documentation.
 
+    Arguments:
+      args: A string, or a sequence of program arguments.
+
+      bufsize: supplied as the buffering argument to the open() function when
+          creating the stdin/stdout/stderr pipe file objects
+
+      executable: A replacement program to execute.
+
+      stdin, stdout and stderr: These specify the executed programs' standard
+          input, standard output and standard error file handles, respectively.
+
+      preexec_fn: (POSIX only) An object to be called in the child process
+          just before the child is executed.
+
+      close_fds: Controls closing or inheriting of file descriptors.
+
+      shell: If true, the command will be executed through the shell.
+
+      cwd: Sets the current directory before the child is executed.
+
+      env: Defines the environment variables for the new process.
+
+      universal_newlines: If true, use universal line endings for file
+          objects stdin, stdout and stderr.
+
+      startupinfo and creationflags (Windows only)
+
+      restore_signals (POSIX only)
+
+      start_new_session (POSIX only)
+
+      pass_fds (POSIX only)
+
+    Attributes:
+        stdin, stdout, stderr, pid, returncode
+    """
     _child_created = False  # Set here since __del__ checks it
 
     def __init__(self, args, bufsize=-1, executable=None,
@@ -1079,6 +808,8 @@ class Popen(object):
 
 
     def poll(self):
+        """Check if child process has terminated. Set and return returncode
+        attribute."""
         return self._internal_poll()
 
 
index 721f9d7..999a99b 100755 (executable)
@@ -1549,7 +1549,9 @@ class TarFile(object):
 
         if mode in ("r", "r:*"):
             # Find out which *open() is appropriate for opening the file.
-            for comptype in cls.OPEN_METH:
+            def not_compressed(comptype):
+                return cls.OPEN_METH[comptype] == 'taropen'
+            for comptype in sorted(cls.OPEN_METH, key=not_compressed):
                 func = getattr(cls, cls.OPEN_METH[comptype])
                 if fileobj is not None:
                     saved_pos = fileobj.tell()
index 11a6310..9b789c2 100644 (file)
@@ -26,7 +26,7 @@ import test.support.script_helper
 _multiprocessing = test.support.import_module('_multiprocessing')
 # Skip tests if sem_open implementation is broken.
 test.support.import_module('multiprocessing.synchronize')
-# import threading after _multiprocessing to raise a more revelant error
+# import threading after _multiprocessing to raise a more relevant error
 # message: "No module named _multiprocessing". _multiprocessing is not compiled
 # without thread support.
 import threading
@@ -3728,6 +3728,19 @@ class TestStartMethod(unittest.TestCase):
             self.assertTrue(methods == ['fork', 'spawn'] or
                             methods == ['fork', 'spawn', 'forkserver'])
 
+    def test_preload_resources(self):
+        if multiprocessing.get_start_method() != 'forkserver':
+            self.skipTest("test only relevant for 'forkserver' method")
+        name = os.path.join(os.path.dirname(__file__), 'mp_preload.py')
+        rc, out, err = test.support.script_helper.assert_python_ok(name)
+        out = out.decode()
+        err = err.decode()
+        if out.rstrip() != 'ok' or err != '':
+            print(out)
+            print(err)
+            self.fail("failed spawning forkserver or grandchild")
+
+
 #
 # Check that killing process does not leak named semaphores
 #
diff --git a/Lib/test/allsans.pem b/Lib/test/allsans.pem
new file mode 100644 (file)
index 0000000..3ee4f59
--- /dev/null
@@ -0,0 +1,37 @@
+-----BEGIN PRIVATE KEY-----
+MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOoy7/QOtTjQ0niE
+6uDcTwtkC0R2Tvy1AjVnXohCntZfdzbTGDoYTgXSOLsP8A697jUiJ8VCePGH50xG
+Z4DKnAF3a9O3a9nr2pLXb0iY3XOMv+YEBii7CfI+3oxFYgCl0sMgHzDD2ZTVYAsm
+DWgLUVsE2gHEccRwrM2tPf2EgR+FAgMBAAECgYEA3qyfyYVSeTrTYxO93x6ZaVMu
+A2IZp9zSxMQL9bKiI2GRj+cV2ebSCGbg2btFnD6qBor7FWsmYz+8g6FNN/9sY4az
+61rMqMtQvLBe+7L8w70FeTze4qQ4Y1oQri0qD6tBWhDVlpnbI5Py9bkZKD67yVUk
+elcEA/5x4PrYXkuqsAECQQD80NjT0mDvaY0JOOaQFSEpMv6QiUA8GGX8Xli7IoKb
+tAolPG8rQBa+qSpcWfDMTrWw/aWHuMEEQoP/bVDH9W4FAkEA7SYQbBAKnojZ5A3G
+kOHdV7aeivRQxQk/JN8Fb8oKB9Csvpv/BsuGxPKXHdhFa6CBTTsNRtHQw/szPo4l
+xMIjgQJAPoMxqibR+0EBM6+TKzteSL6oPXsCnBl4Vk/J5vPgkbmR7KUl4+7j8N8J
+b2554TrxKEN/w7CGYZRE6UrRd7ATNQJAWD7Yz41sli+wfPdPU2xo1BHljyl4wMk/
+EPZYbI/PCbdyAH/F935WyQTIjNeEhZc1Zkq6FwdOWw8ns3hrv3rKgQJAHXv1BqUa
+czGPIFxX2TNoqtcl6/En4vrxVB1wzsfzkkDAg98kBl7qsF+S3qujSzKikjeaVbI2
+/CyWR2P3yLtOmA==
+-----END PRIVATE KEY-----
+-----BEGIN CERTIFICATE-----
+MIIDcjCCAtugAwIBAgIJAN5dc9TOWjB7MA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV
+BAYTAlhZMRcwFQYDVQQHDA5DYXN0bGUgQW50aHJheDEjMCEGA1UECgwaUHl0aG9u
+IFNvZnR3YXJlIEZvdW5kYXRpb24xEDAOBgNVBAMMB2FsbHNhbnMwHhcNMTYwODA1
+MTAyMTExWhcNMjYwODAzMTAyMTExWjBdMQswCQYDVQQGEwJYWTEXMBUGA1UEBwwO
+Q2FzdGxlIEFudGhyYXgxIzAhBgNVBAoMGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0
+aW9uMRAwDgYDVQQDDAdhbGxzYW5zMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
+gQDqMu/0DrU40NJ4hOrg3E8LZAtEdk78tQI1Z16IQp7WX3c20xg6GE4F0ji7D/AO
+ve41IifFQnjxh+dMRmeAypwBd2vTt2vZ69qS129ImN1zjL/mBAYouwnyPt6MRWIA
+pdLDIB8ww9mU1WALJg1oC1FbBNoBxHHEcKzNrT39hIEfhQIDAQABo4IBODCCATQw
+ggEwBgNVHREEggEnMIIBI4IHYWxsc2Fuc6AeBgMqAwSgFwwVc29tZSBvdGhlciBp
+ZGVudGlmaWVyoDUGBisGAQUCAqArMCmgEBsOS0VSQkVST1MuUkVBTE2hFTAToAMC
+AQGhDDAKGwh1c2VybmFtZYEQdXNlckBleGFtcGxlLm9yZ4IPd3d3LmV4YW1wbGUu
+b3JnpGcwZTELMAkGA1UEBhMCWFkxFzAVBgNVBAcMDkNhc3RsZSBBbnRocmF4MSMw
+IQYDVQQKDBpQeXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEYMBYGA1UEAwwPZGly
+bmFtZSBleGFtcGxlhhdodHRwczovL3d3dy5weXRob24ub3JnL4cEfwAAAYcQAAAA
+AAAAAAAAAAAAAAAAAYgEKgMEBTANBgkqhkiG9w0BAQsFAAOBgQAy16h+F+nOmeiT
+VWR0fc8F/j6FcadbLseAUaogcC15OGxCl4UYpLV88HBkABOoGCpP155qwWTwOrdG
+iYPGJSusf1OnJEbvzFejZf6u078bPd9/ZL4VWLjv+FPGkjd+N+/OaqMvgj8Lu99f
+3Y/C4S7YbHxxwff6C6l2Xli+q6gnuQ==
+-----END CERTIFICATE-----
index 1646de8..cfcfef2 100644 (file)
 # Unix users can map to different SMB User names
 ;  username map = /etc/samba/smbusers
 
-# Using the following line enables you to customise your configuration
+# Using the following line enables you to customize your configuration
 # on a per machine basis. The %m gets replaced with the netbios name
 # of the machine that is connecting
 ;   include = /etc/samba/smb.conf.%m
diff --git a/Lib/test/check_soundcard.vbs b/Lib/test/check_soundcard.vbs
deleted file mode 100644 (file)
index 8c21852..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-rem Check for a working sound-card - exit with 0 if OK, 1 otherwise.
-set wmi = GetObject("winmgmts:")
-set scs = wmi.InstancesOf("win32_sounddevice")
-for each sc in scs
-   set status = sc.Properties_("Status")
-   wscript.Echo(sc.Properties_("Name") + "/" + status)
-   if status = "OK" then
-       wscript.Quit 0 rem normal exit
-   end if
-next
-rem No sound card found - exit with status code of 1
-wscript.Quit 1
-
index f5222c7..0860db8 100644 (file)
@@ -3884,7 +3884,7 @@ class Oddballs(unittest.TestCase):
         self.assertRaises(TypeError, lambda: as_date >= as_datetime)
         self.assertRaises(TypeError, lambda: as_datetime >= as_date)
 
-        # Neverthelss, comparison should work with the base-class (date)
+        # Nevertheless, comparison should work with the base-class (date)
         # projection if use of a date method is forced.
         self.assertEqual(as_date.__eq__(as_datetime), True)
         different_day = (as_date.day + 1) % 20 + 1
index 9931a55..e3f1aa5 100644 (file)
@@ -372,7 +372,7 @@ class SignalEINTRTest(EINTRBaseTest):
     @unittest.skipUnless(hasattr(signal, 'sigwaitinfo'),
                          'need signal.sigwaitinfo()')
     def test_sigwaitinfo(self):
-        # Issue #25277, #25868: give a few miliseconds to the parent process
+        # Issue #25277, #25868: give a few milliseconds to the parent process
         # between os.write() and signal.sigwaitinfo() to works around a race
         # condition
         self.sleep_time = 0.100
index f61135d..08a76e6 100644 (file)
@@ -35,5 +35,5 @@ message/external-body; showexternal %s %{access-type} %{name} %{site} \
 text/richtext; shownonascii iso-8859-8 -e richtext -p %s; test=test "`echo \
     %{charset} | tr '[A-Z]' '[a-z]'`"  = iso-8859-8; copiousoutput
 
-video/mpeg; mpeg_play %s
 video/*; animate %s
+video/mpeg; mpeg_play %s
\ No newline at end of file
index 81d04f8..a1f298d 100644 (file)
@@ -20,7 +20,28 @@ req_template = """
     CN                     = {hostname}
 
     [req_x509_extensions]
-    subjectAltName         = DNS:{hostname}
+    subjectAltName         = @san
+
+    [san]
+    DNS.1 = {hostname}
+    {extra_san}
+
+    [dir_sect]
+    C                      = XY
+    L                      = Castle Anthrax
+    O                      = Python Software Foundation
+    CN                     = dirname example
+
+    [princ_name]
+    realm = EXP:0, GeneralString:KERBEROS.REALM
+    principal_name = EXP:1, SEQUENCE:principal_seq
+
+    [principal_seq]
+    name_type = EXP:0, INTEGER:1
+    name_string = EXP:1, SEQUENCE:principals
+
+    [principals]
+    princ1 = GeneralString:username
 
     [ ca ]
     default_ca      = CA_default
@@ -67,7 +88,7 @@ req_template = """
 
 here = os.path.abspath(os.path.dirname(__file__))
 
-def make_cert_key(hostname, sign=False):
+def make_cert_key(hostname, sign=False, extra_san=''):
     print("creating cert for " + hostname)
     tempnames = []
     for i in range(3):
@@ -75,8 +96,9 @@ def make_cert_key(hostname, sign=False):
             tempnames.append(f.name)
     req_file, cert_file, key_file = tempnames
     try:
+        req = req_template.format(hostname=hostname, extra_san=extra_san)
         with open(req_file, 'w') as f:
-            f.write(req_template.format(hostname=hostname))
+            f.write(req)
         args = ['req', '-new', '-days', '3650', '-nodes',
                 '-newkey', 'rsa:1024', '-keyout', key_file,
                 '-config', req_file]
@@ -120,7 +142,7 @@ def make_ca():
         f.write('unique_subject = no')
 
     with tempfile.NamedTemporaryFile("w") as t:
-        t.write(req_template.format(hostname='our-ca-server'))
+        t.write(req_template.format(hostname='our-ca-server', extra_san=''))
         t.flush()
         with tempfile.NamedTemporaryFile() as f:
             args = ['req', '-new', '-days', '3650', '-extensions', 'v3_ca', '-nodes',
@@ -171,6 +193,25 @@ if __name__ == '__main__':
         f.write(key)
         f.write(cert)
 
+    extra_san = [
+        'otherName.1 = 1.2.3.4;UTF8:some other identifier',
+        'otherName.2 = 1.3.6.1.5.2.2;SEQUENCE:princ_name',
+        'email.1 = user@example.org',
+        'DNS.2 = www.example.org',
+        # GEN_X400
+        'dirName.1 = dir_sect',
+        # GEN_EDIPARTY
+        'URI.1 = https://www.python.org/',
+        'IP.1 = 127.0.0.1',
+        'IP.2 = ::1',
+        'RID.1 = 1.2.3.4.5',
+    ]
+
+    cert, key = make_cert_key('allsans', extra_san='\n'.join(extra_san))
+    with open('allsans.pem', 'w') as f:
+        f.write(key)
+        f.write(cert)
+
     unmake_ca()
     print("\n\nPlease change the values in test_ssl.py, test_parse_cert function related to notAfter,notBefore and serialNumber")
     check_call(['openssl','x509','-in','keycert.pem','-dates','-serial','-noout'])
diff --git a/Lib/test/mp_preload.py b/Lib/test/mp_preload.py
new file mode 100644 (file)
index 0000000..5314e8f
--- /dev/null
@@ -0,0 +1,18 @@
+import multiprocessing
+
+multiprocessing.Lock()
+
+
+def f():
+    print("ok")
+
+
+if __name__ == "__main__":
+    ctx = multiprocessing.get_context("forkserver")
+    modname = "test.mp_preload"
+    # Make sure it's importable
+    __import__(modname)
+    ctx.set_forkserver_preload([modname])
+    proc = ctx.Process(target=f)
+    proc.start()
+    proc.join()
index f252a0a..7922b54 100644 (file)
@@ -2629,6 +2629,35 @@ class AbstractPersistentPicklerTests(unittest.TestCase):
             self.assertEqual(self.load_false_count, 1)
 
 
+class AbstractIdentityPersistentPicklerTests(unittest.TestCase):
+
+    def persistent_id(self, obj):
+        return obj
+
+    def persistent_load(self, pid):
+        return pid
+
+    def _check_return_correct_type(self, obj, proto):
+        unpickled = self.loads(self.dumps(obj, proto))
+        self.assertIsInstance(unpickled, type(obj))
+        self.assertEqual(unpickled, obj)
+
+    def test_return_correct_type(self):
+        for proto in protocols:
+            # Protocol 0 supports only ASCII strings.
+            if proto == 0:
+                self._check_return_correct_type("abc", 0)
+            else:
+                for obj in [b"abc\n", "abc\n", -1, -1.1 * 0.1, str]:
+                    self._check_return_correct_type(obj, proto)
+
+    def test_protocol0_is_ascii_only(self):
+        non_ascii_str = "\N{EMPTY SET}"
+        self.assertRaises(pickle.PicklingError, self.dumps, non_ascii_str, 0)
+        pickled = pickle.PERSID + non_ascii_str.encode('utf-8') + b'\n.'
+        self.assertRaises(pickle.UnpicklingError, self.loads, pickled)
+
+
 class AbstractPicklerUnpicklerObjectTests(unittest.TestCase):
 
     pickler_class = None
index fecfd09..c1d85f6 100755 (executable)
@@ -325,9 +325,6 @@ def _create_parser():
     group.add_argument('-P', '--pgo', dest='pgo', action='store_true',
                        help='enable Profile Guided Optimization training')
 
-    parser.add_argument('args', nargs=argparse.REMAINDER,
-                        help=argparse.SUPPRESS)
-
     return parser
 
 def relative_filename(string):
@@ -373,15 +370,21 @@ def _parse_args(args, **kwargs):
         ns.use_resources = []
 
     parser = _create_parser()
-    parser.parse_args(args=args, namespace=ns)
+    # Issue #14191: argparse doesn't support "intermixed" positional and
+    # optional arguments. Use parse_known_args() as workaround.
+    ns.args = parser.parse_known_args(args=args, namespace=ns)[1]
+    for arg in ns.args:
+        if arg.startswith('-'):
+            parser.error("unrecognized arguments: %s" % arg)
+            sys.exit(1)
 
     if ns.single and ns.fromfile:
         parser.error("-s and -f don't go together!")
-    if ns.use_mp and ns.trace:
+    if ns.use_mp is not None and ns.trace:
         parser.error("-T and -j don't go together!")
-    if ns.use_mp and ns.findleaks:
+    if ns.use_mp is not None and ns.findleaks:
         parser.error("-l and -j don't go together!")
-    if ns.use_mp and ns.memlimit:
+    if ns.use_mp is not None and ns.memlimit:
         parser.error("-M and -j don't go together!")
     if ns.failfast and not (ns.verbose or ns.verbose3):
         parser.error("-G/--failfast needs either -v or -W")
@@ -989,7 +992,7 @@ def runtest(test, verbose, quiet,
                 sys.stderr = stream
                 result = runtest_inner(test, verbose, quiet, huntrleaks,
                                        display_failure=False, pgo=pgo)
-                if result[0] == FAILED and not pgo:
+                if result[0] != PASSED and not pgo:
                     output = stream.getvalue()
                     orig_stderr.write(output)
                     orig_stderr.flush()
@@ -1049,7 +1052,7 @@ class saved_test_environment:
 
     resources = ('sys.argv', 'cwd', 'sys.stdin', 'sys.stdout', 'sys.stderr',
                  'os.environ', 'sys.path', 'sys.path_hooks', '__import__',
-                 'warnings.filters', 'asyncore.socket_map',
+                 'asyncore.socket_map',
                  'logging._handlers', 'logging._handlerList', 'sys.gettrace',
                  'sys.warnoptions',
                  # multiprocessing.process._cleanup() may release ref
@@ -1115,12 +1118,6 @@ class saved_test_environment:
     def restore___import__(self, import_):
         builtins.__import__ = import_
 
-    def get_warnings_filters(self):
-        return id(warnings.filters), warnings.filters, warnings.filters[:]
-    def restore_warnings_filters(self, saved_filters):
-        warnings.filters = saved_filters[1]
-        warnings.filters[:] = saved_filters[2]
-
     def get_asyncore_socket_map(self):
         asyncore = sys.modules.get('asyncore')
         # XXX Making a copy keeps objects alive until __exit__ gets called.
@@ -1258,6 +1255,7 @@ class saved_test_environment:
     def __exit__(self, exc_type, exc_val, exc_tb):
         saved_values = self.saved_values
         del self.saved_values
+        support.gc_collect()  # Some resources use weak references
         for name, get, restore in self.resource_info():
             current = get()
             original = saved_values.pop(name)
@@ -1288,6 +1286,7 @@ def runtest_inner(test, verbose, quiet,
         else:
             # Always import it from the test package
             abstest = 'test.' + test
+        clear_caches()
         with saved_test_environment(test, verbose, quiet, pgo=pgo) as environment:
             start_time = time.time()
             the_module = importlib.import_module(abstest)
@@ -1460,17 +1459,9 @@ def dash_R(the_module, test, indirect_test, huntrleaks):
 
 def dash_R_cleanup(fs, ps, pic, zdc, abcs):
     import gc, copyreg
-    import _strptime, linecache
-    import urllib.parse, urllib.request, mimetypes, doctest
-    import struct, filecmp, collections.abc
-    from distutils.dir_util import _path_created
+    import collections.abc
     from weakref import WeakSet
 
-    # Clear the warnings registry, so they can be displayed again
-    for mod in sys.modules.values():
-        if hasattr(mod, '__warningregistry__'):
-            del mod.__warningregistry__
-
     # Restore some original values.
     warnings.filters[:] = fs
     copyreg.dispatch_table.clear()
@@ -1497,6 +1488,22 @@ def dash_R_cleanup(fs, ps, pic, zdc, abcs):
             obj._abc_cache.clear()
             obj._abc_negative_cache.clear()
 
+    clear_caches()
+
+    # Collect cyclic trash and read memory statistics immediately after.
+    func1 = sys.getallocatedblocks
+    func2 = sys.gettotalrefcount
+    gc.collect()
+    return func1(), func2()
+
+def clear_caches():
+    import gc
+
+    # Clear the warnings registry, so they can be displayed again
+    for mod in sys.modules.values():
+        if hasattr(mod, '__warningregistry__'):
+            del mod.__warningregistry__
+
     # Flush standard output, so that buffered data is sent to the OS and
     # associated Python objects are reclaimed.
     for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
@@ -1504,29 +1511,88 @@ def dash_R_cleanup(fs, ps, pic, zdc, abcs):
             stream.flush()
 
     # Clear assorted module caches.
-    _path_created.clear()
+    # Don't worry about resetting the cache if the module is not loaded
+    try:
+        distutils_dir_util = sys.modules['distutils.dir_util']
+    except KeyError:
+        pass
+    else:
+        distutils_dir_util._path_created.clear()
+
     re.purge()
-    _strptime._regex_cache.clear()
-    urllib.parse.clear_cache()
-    urllib.request.urlcleanup()
-    linecache.clearcache()
-    mimetypes._default_mime_types()
-    filecmp._cache.clear()
-    struct._clearcache()
-    doctest.master = None
+
     try:
-        import ctypes
-    except ImportError:
-        # Don't worry about resetting the cache if ctypes is not supported
+        _strptime = sys.modules['_strptime']
+    except KeyError:
+        pass
+    else:
+        _strptime._regex_cache.clear()
+
+    try:
+        urllib_parse = sys.modules['urllib.parse']
+    except KeyError:
+        pass
+    else:
+        urllib_parse.clear_cache()
+
+    try:
+        urllib_request = sys.modules['urllib.request']
+    except KeyError:
+        pass
+    else:
+        urllib_request.urlcleanup()
+
+    try:
+        linecache = sys.modules['linecache']
+    except KeyError:
+        pass
+    else:
+        linecache.clearcache()
+
+    try:
+        mimetypes = sys.modules['mimetypes']
+    except KeyError:
+        pass
+    else:
+        mimetypes._default_mime_types()
+
+    try:
+        filecmp = sys.modules['filecmp']
+    except KeyError:
+        pass
+    else:
+        filecmp._cache.clear()
+
+    try:
+        struct = sys.modules['struct']
+    except KeyError:
+        pass
+    else:
+        struct._clearcache()
+
+    try:
+        doctest = sys.modules['doctest']
+    except KeyError:
+        pass
+    else:
+        doctest.master = None
+
+    try:
+        ctypes = sys.modules['ctypes']
+    except KeyError:
         pass
     else:
         ctypes._reset_cache()
 
-    # Collect cyclic trash and read memory statistics immediately after.
-    func1 = sys.getallocatedblocks
-    func2 = sys.gettotalrefcount
+    try:
+        typing = sys.modules['typing']
+    except KeyError:
+        pass
+    else:
+        for f in typing._cleanups:
+            f()
+
     gc.collect()
-    return func1(), func2()
 
 def warm_caches():
     # char cache
index f9d30cf..b99ea45 100644 (file)
@@ -16,7 +16,7 @@ here = os.path.dirname(__file__)
 HOST = support.HOST
 CERTFILE = os.path.join(here, 'keycert.pem')
 
-# This one's based on HTTPServer, which is based on SocketServer
+# This one's based on HTTPServer, which is based on socketserver
 
 class HTTPSServer(_HTTPServer):
 
index 9b0ed22..5073ae1 100644 (file)
@@ -1,17 +1,32 @@
-# Convenience test module to run all of the SSL-related tests in the
+# Convenience test module to run all of the OpenSSL-related tests in the
 # standard library.
 
+import ssl
 import sys
 import subprocess
 
-TESTS = ['test_asyncio', 'test_ftplib', 'test_hashlib', 'test_httplib',
-         'test_imaplib', 'test_nntplib', 'test_poplib', 'test_smtplib',
-         'test_smtpnet', 'test_urllib2_localnet', 'test_venv']
+TESTS = [
+    'test_asyncio', 'test_ensurepip.py', 'test_ftplib', 'test_hashlib',
+    'test_hmac', 'test_httplib', 'test_imaplib', 'test_nntplib',
+    'test_poplib', 'test_ssl', 'test_smtplib', 'test_smtpnet',
+    'test_urllib2_localnet', 'test_venv', 'test_xmlrpc'
+]
 
 def run_regrtests(*extra_args):
-    args = [sys.executable, "-m", "test"]
+    print(ssl.OPENSSL_VERSION)
+    args = [
+        sys.executable,
+        '-Werror', '-bb',  # turn warnings into exceptions
+        '-m', 'test',
+    ]
     if not extra_args:
-        args.append("-unetwork")
+        args.extend([
+            '-r',  # randomize
+            '-w',  # re-run failed tests with -v
+            '-u', 'network',  # use network
+            '-u', 'urlfetch',  # download test vectors
+            '-j', '0'  # use multiple CPUs
+        ])
     else:
         args.extend(extra_args)
     args.extend(TESTS)
index e124fab..d0d126a 100644 (file)
@@ -89,6 +89,7 @@ __all__ = [
     "bigmemtest", "bigaddrspacetest", "cpython_only", "get_attribute",
     "requires_IEEE_754", "skip_unless_xattr", "requires_zlib",
     "anticipate_failure", "load_package_tests", "detect_api_mismatch",
+     "requires_multiprocessing_queue",
     # sys
     "is_jython", "check_impl_detail",
     # network
@@ -296,6 +297,16 @@ def unload(name):
     except KeyError:
         pass
 
+def _force_run(path, func, *args):
+    try:
+        return func(*args)
+    except OSError as err:
+        if verbose >= 2:
+            print('%s: %s' % (err.__class__.__name__, err))
+            print('re-run %s%r' % (func.__name__, args))
+        os.chmod(path, stat.S_IRWXU)
+        return func(*args)
+
 if sys.platform.startswith("win"):
     def _waitfor(func, pathname, waitall=False):
         # Perform the operation
@@ -338,7 +349,7 @@ if sys.platform.startswith("win"):
 
     def _rmtree(path):
         def _rmtree_inner(path):
-            for name in os.listdir(path):
+            for name in _force_run(path, os.listdir, path):
                 fullname = os.path.join(path, name)
                 try:
                     mode = os.lstat(fullname).st_mode
@@ -348,15 +359,36 @@ if sys.platform.startswith("win"):
                     mode = 0
                 if stat.S_ISDIR(mode):
                     _waitfor(_rmtree_inner, fullname, waitall=True)
-                    os.rmdir(fullname)
+                    _force_run(fullname, os.rmdir, fullname)
                 else:
-                    os.unlink(fullname)
+                    _force_run(fullname, os.unlink, fullname)
         _waitfor(_rmtree_inner, path, waitall=True)
-        _waitfor(os.rmdir, path)
+        _waitfor(lambda p: _force_run(p, os.rmdir, p), path)
 else:
     _unlink = os.unlink
     _rmdir = os.rmdir
-    _rmtree = shutil.rmtree
+
+    def _rmtree(path):
+        try:
+            shutil.rmtree(path)
+            return
+        except OSError:
+            pass
+
+        def _rmtree_inner(path):
+            for name in _force_run(path, os.listdir, path):
+                fullname = os.path.join(path, name)
+                try:
+                    mode = os.lstat(fullname).st_mode
+                except OSError:
+                    mode = 0
+                if stat.S_ISDIR(mode):
+                    _rmtree_inner(fullname)
+                    _force_run(path, os.rmdir, fullname)
+                else:
+                    _force_run(path, os.unlink, fullname)
+        _rmtree_inner(path)
+        os.rmdir(path)
 
 def unlink(filename):
     try:
@@ -464,6 +496,7 @@ def _is_gui_available():
         try:
             from tkinter import Tk
             root = Tk()
+            root.withdraw()
             root.update()
             root.destroy()
         except Exception as e:
@@ -488,12 +521,12 @@ def is_resource_enabled(resource):
 
 def requires(resource, msg=None):
     """Raise ResourceDenied if the specified resource is not available."""
-    if resource == 'gui' and not _is_gui_available():
-        raise ResourceDenied(_is_gui_available.reason)
     if not is_resource_enabled(resource):
         if msg is None:
             msg = "Use of the %r resource not enabled" % resource
         raise ResourceDenied(msg)
+    if resource == 'gui' and not _is_gui_available():
+        raise ResourceDenied(_is_gui_available.reason)
 
 def _requires_unix_version(sysname, min_version):
     """Decorator raising SkipTest if the OS is `sysname` and the version is less
@@ -900,7 +933,7 @@ def temp_dir(path=None, quiet=False):
         yield path
     finally:
         if dir_created:
-            shutil.rmtree(path)
+            rmtree(path)
 
 @contextlib.contextmanager
 def change_cwd(path, quiet=False):
@@ -1008,9 +1041,16 @@ def make_bad_fd():
         file.close()
         unlink(TESTFN)
 
-def check_syntax_error(testcase, statement):
-    testcase.assertRaises(SyntaxError, compile, statement,
-                          '<test string>', 'exec')
+def check_syntax_error(testcase, statement, *, lineno=None, offset=None):
+    with testcase.assertRaises(SyntaxError) as cm:
+        compile(statement, '<test string>', 'exec')
+    err = cm.exception
+    testcase.assertIsNotNone(err.lineno)
+    if lineno is not None:
+        testcase.assertEqual(err.lineno, lineno)
+    testcase.assertIsNotNone(err.offset)
+    if offset is not None:
+        testcase.assertEqual(err.offset, offset)
 
 def open_urlresource(url, *args, **kw):
     import urllib.request, urllib.parse
@@ -1349,7 +1389,8 @@ def transient_internet(resource_name, *, timeout=30.0, errnos=()):
              500 <= err.code <= 599) or
             (isinstance(err, urllib.error.URLError) and
                  (("ConnectionRefusedError" in err.reason) or
-                  ("TimeoutError" in err.reason))) or
+                  ("TimeoutError" in err.reason) or
+                  ("EOFError" in err.reason))) or
             n in captured_errnos):
             if not verbose:
                 sys.stderr.write(denied.args[0] + "\n")
@@ -1729,6 +1770,22 @@ def impl_detail(msg=None, **guards):
         msg = msg.format(' or '.join(guardnames))
     return unittest.skip(msg)
 
+_have_mp_queue = None
+def requires_multiprocessing_queue(test):
+    """Skip decorator for tests that use multiprocessing.Queue."""
+    global _have_mp_queue
+    if _have_mp_queue is None:
+        import multiprocessing
+        # Without a functioning shared semaphore implementation attempts to
+        # instantiate a Queue will result in an ImportError (issue #3770).
+        try:
+            multiprocessing.Queue()
+            _have_mp_queue = True
+        except ImportError:
+            _have_mp_queue = False
+    msg = "requires a functioning shared semaphore implementation"
+    return test if _have_mp_queue else unittest.skip(msg)(test)
+
 def _parse_guards(guards):
     # Returns a tuple ({platform_name: run_me}, default_value)
     if not guards:
@@ -2068,6 +2125,9 @@ def strip_python_stderr(stderr):
     stderr = re.sub(br"\[\d+ refs, \d+ blocks\]\r?\n?", b"", stderr).strip()
     return stderr
 
+requires_type_collecting = unittest.skipIf(hasattr(sys, 'getcounts'),
+                        'types are immortal if COUNT_ALLOCS is defined')
+
 def args_from_interpreter_flags():
     """Return a list of command-line arguments reproducing the current
     settings in sys.flags and sys.warnoptions."""
index 9c2e9eb..80889b1 100644 (file)
@@ -73,22 +73,26 @@ def run_python_until_end(*args, **env_vars):
     # Need to preserve the original environment, for in-place testing of
     # shared library builds.
     env = os.environ.copy()
+    # set TERM='' unless the TERM environment variable is passed explicitly
+    # see issues #11390 and #18300
+    if 'TERM' not in env_vars:
+        env['TERM'] = ''
     # But a special flag that can be set to override -- in this case, the
     # caller is responsible to pass the full environment.
     if env_vars.pop('__cleanenv', None):
         env = {}
     env.update(env_vars)
     cmd_line.extend(args)
-    p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
+    proc = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                          env=env)
-    try:
-        out, err = p.communicate()
-    finally:
-        subprocess._cleanup()
-        p.stdout.close()
-        p.stderr.close()
-    rc = p.returncode
+    with proc:
+        try:
+            out, err = proc.communicate()
+        finally:
+            proc.kill()
+            subprocess._cleanup()
+    rc = proc.returncode
     err = strip_python_stderr(err)
     return _PythonRunResult(rc, out, err), cmd_line
 
index f9ee398..4779a13 100644 (file)
@@ -4550,7 +4550,7 @@ class TestNamespace(TestCase):
         self.assertTrue(ns2 != ns3)
         self.assertTrue(ns2 != ns4)
 
-    def test_equality_returns_notimplemeted(self):
+    def test_equality_returns_notimplemented(self):
         # See issue 21481
         ns = argparse.Namespace(a=1, b=2)
         self.assertIs(ns.__eq__(None), NotImplemented)
index 482526e..2a21e74 100644 (file)
@@ -38,14 +38,24 @@ typecodes = "ubBhHiIlLfd"
 if have_long_long:
     typecodes += 'qQ'
 
-class BadConstructorTest(unittest.TestCase):
+class MiscTest(unittest.TestCase):
 
-    def test_constructor(self):
+    def test_bad_constructor(self):
         self.assertRaises(TypeError, array.array)
         self.assertRaises(TypeError, array.array, spam=42)
         self.assertRaises(TypeError, array.array, 'xx')
         self.assertRaises(ValueError, array.array, 'x')
 
+    def test_empty(self):
+        # Exercise code for handling zero-length arrays
+        a = array.array('B')
+        a[:] = a
+        self.assertEqual(len(a), 0)
+        self.assertEqual(len(a + a), 0)
+        self.assertEqual(len(a * 3), 0)
+        a += a
+        self.assertEqual(len(a), 0)
+
 
 # Machine format codes.
 #
index 0807dfb..3f1ec65 100644 (file)
@@ -116,6 +116,13 @@ class BaseEventTests(test_utils.TestCase):
         self.assertIsNone(
             base_events._ipaddr_info('::3%lo0', 1, INET6, STREAM, TCP))
 
+        if hasattr(socket, 'SOCK_NONBLOCK'):
+            self.assertEqual(
+                None,
+                base_events._ipaddr_info(
+                    '1.2.3.4', 1, INET, STREAM | socket.SOCK_NONBLOCK, TCP))
+
+
     def test_port_parameter_types(self):
         # Test obscure kinds of arguments for "port".
         INET = socket.AF_INET
@@ -142,26 +149,6 @@ class BaseEventTests(test_utils.TestCase):
             (INET, STREAM, TCP, '', ('1.2.3.4', 1)),
             base_events._ipaddr_info('1.2.3.4', b'1', INET, STREAM, TCP))
 
-    def test_getaddrinfo_servname(self):
-        INET = socket.AF_INET
-        STREAM = socket.SOCK_STREAM
-        TCP = socket.IPPROTO_TCP
-
-        self.assertEqual(
-            (INET, STREAM, TCP, '', ('1.2.3.4', 80)),
-            base_events._ipaddr_info('1.2.3.4', 'http', INET, STREAM, TCP))
-
-        self.assertEqual(
-            (INET, STREAM, TCP, '', ('1.2.3.4', 80)),
-            base_events._ipaddr_info('1.2.3.4', b'http', INET, STREAM, TCP))
-
-        # Raises "service/proto not found".
-        with self.assertRaises(OSError):
-            base_events._ipaddr_info('1.2.3.4', 'nonsense', INET, STREAM, TCP)
-
-        with self.assertRaises(OSError):
-            base_events._ipaddr_info('1.2.3.4', 'nonsense', INET, STREAM, TCP)
-
     @patch_socket
     def test_ipaddr_info_no_inet_pton(self, m_socket):
         del m_socket.inet_pton
@@ -174,6 +161,7 @@ class BaseEventTests(test_utils.TestCase):
 class BaseEventLoopTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = base_events.BaseEventLoop()
         self.loop._selector = mock.Mock()
         self.loop._selector.select.return_value = ()
@@ -255,6 +243,11 @@ class BaseEventLoopTests(test_utils.TestCase):
         self.assertIsInstance(h, asyncio.Handle)
         self.assertIn(h, self.loop._ready)
 
+    def test_call_soon_non_callable(self):
+        self.loop.set_debug(True)
+        with self.assertRaisesRegex(TypeError, 'a callable object'):
+            self.loop.call_soon(1)
+
     def test_call_later(self):
         def cb():
             pass
@@ -361,44 +354,21 @@ class BaseEventLoopTests(test_utils.TestCase):
         # check disabled if debug mode is disabled
         test_thread(self.loop, False, create_loop=True)
 
-    def test_run_once_in_executor_handle(self):
-        def cb():
-            pass
-
-        self.assertRaises(
-            AssertionError, self.loop.run_in_executor,
-            None, asyncio.Handle(cb, (), self.loop), ('',))
-        self.assertRaises(
-            AssertionError, self.loop.run_in_executor,
-            None, asyncio.TimerHandle(10, cb, (), self.loop))
-
-    def test_run_once_in_executor_cancelled(self):
-        def cb():
-            pass
-        h = asyncio.Handle(cb, (), self.loop)
-        h.cancel()
-
-        f = self.loop.run_in_executor(None, h)
-        self.assertIsInstance(f, asyncio.Future)
-        self.assertTrue(f.done())
-        self.assertIsNone(f.result())
-
     def test_run_once_in_executor_plain(self):
         def cb():
             pass
-        h = asyncio.Handle(cb, (), self.loop)
         f = asyncio.Future(loop=self.loop)
         executor = mock.Mock()
         executor.submit.return_value = f
 
         self.loop.set_default_executor(executor)
 
-        res = self.loop.run_in_executor(None, h)
+        res = self.loop.run_in_executor(None, cb)
         self.assertIs(f, res)
 
         executor = mock.Mock()
         executor.submit.return_value = f
-        res = self.loop.run_in_executor(executor, h)
+        res = self.loop.run_in_executor(executor, cb)
         self.assertIs(f, res)
         self.assertTrue(executor.submit.called)
 
@@ -1014,6 +984,7 @@ class MyDatagramProto(asyncio.DatagramProtocol):
 class BaseEventLoopWithSelectorTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = asyncio.new_event_loop()
         self.set_event_loop(self.loop)
 
@@ -1076,6 +1047,41 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
             MyProto, 'example.com', 80, sock=object())
         self.assertRaises(ValueError, self.loop.run_until_complete, coro)
 
+    def test_create_connection_wrong_sock(self):
+        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+        with sock:
+            coro = self.loop.create_connection(MyProto, sock=sock)
+            with self.assertRaisesRegex(ValueError,
+                                        'A Stream Socket was expected'):
+                self.loop.run_until_complete(coro)
+
+    def test_create_server_wrong_sock(self):
+        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+        with sock:
+            coro = self.loop.create_server(MyProto, sock=sock)
+            with self.assertRaisesRegex(ValueError,
+                                        'A Stream Socket was expected'):
+                self.loop.run_until_complete(coro)
+
+    @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
+                         'no socket.SOCK_NONBLOCK (linux only)')
+    def test_create_server_stream_bittype(self):
+        sock = socket.socket(
+            socket.AF_INET, socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
+        with sock:
+            coro = self.loop.create_server(lambda: None, sock=sock)
+            srv = self.loop.run_until_complete(coro)
+            srv.close()
+            self.loop.run_until_complete(srv.wait_closed())
+
+    def test_create_datagram_endpoint_wrong_sock(self):
+        sock = socket.socket(socket.AF_INET)
+        with sock:
+            coro = self.loop.create_datagram_endpoint(MyProto, sock=sock)
+            with self.assertRaisesRegex(ValueError,
+                                        'A UDP Socket was expected'):
+                self.loop.run_until_complete(coro)
+
     def test_create_connection_no_host_port_sock(self):
         coro = self.loop.create_connection(MyProto)
         self.assertRaises(ValueError, self.loop.run_until_complete, coro)
@@ -1168,10 +1174,10 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
         m_socket.getaddrinfo = socket.getaddrinfo
         sock = m_socket.socket.return_value
 
-        self.loop.add_reader = mock.Mock()
-        self.loop.add_reader._is_coroutine = False
-        self.loop.add_writer = mock.Mock()
-        self.loop.add_writer._is_coroutine = False
+        self.loop._add_reader = mock.Mock()
+        self.loop._add_reader._is_coroutine = False
+        self.loop._add_writer = mock.Mock()
+        self.loop._add_writer._is_coroutine = False
 
         coro = self.loop.create_connection(asyncio.Protocol, '1.2.3.4', 80)
         t, p = self.loop.run_until_complete(coro)
@@ -1185,14 +1191,14 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
             test_utils.run_briefly(self.loop)  # allow transport to close
 
         sock.family = socket.AF_INET6
-        coro = self.loop.create_connection(asyncio.Protocol, '::2', 80)
+        coro = self.loop.create_connection(asyncio.Protocol, '::1', 80)
         t, p = self.loop.run_until_complete(coro)
         try:
-            # Without inet_pton we use getaddrinfo, which transforms ('::2', 80)
-            # to ('::0.0.0.2', 80, 0, 0). The last 0s are flow info, scope id.
+            # Without inet_pton we use getaddrinfo, which transforms ('::1', 80)
+            # to ('::1', 80, 0, 0). The last 0s are flow info, scope id.
             [address] = sock.connect.call_args[0]
             host, port = address[:2]
-            self.assertRegex(host, r'::(0\.)*2')
+            self.assertRegex(host, r'::(0\.)*1')
             self.assertEqual(port, 80)
             _, kwargs = m_socket.socket.call_args
             self.assertEqual(kwargs['family'], m_socket.AF_INET6)
@@ -1209,6 +1215,37 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
     def test_create_connection_no_inet_pton(self, m_socket):
         self._test_create_connection_ip_addr(m_socket, False)
 
+    @patch_socket
+    def test_create_connection_service_name(self, m_socket):
+        m_socket.getaddrinfo = socket.getaddrinfo
+        sock = m_socket.socket.return_value
+
+        self.loop._add_reader = mock.Mock()
+        self.loop._add_reader._is_coroutine = False
+        self.loop._add_writer = mock.Mock()
+        self.loop._add_writer._is_coroutine = False
+
+        for service, port in ('http', 80), (b'http', 80):
+            coro = self.loop.create_connection(asyncio.Protocol,
+                                               '127.0.0.1', service)
+
+            t, p = self.loop.run_until_complete(coro)
+            try:
+                sock.connect.assert_called_with(('127.0.0.1', port))
+                _, kwargs = m_socket.socket.call_args
+                self.assertEqual(kwargs['family'], m_socket.AF_INET)
+                self.assertEqual(kwargs['type'], m_socket.SOCK_STREAM)
+            finally:
+                t.close()
+                test_utils.run_briefly(self.loop)  # allow transport to close
+
+        for service in 'nonsense', b'nonsense':
+            coro = self.loop.create_connection(asyncio.Protocol,
+                                               '127.0.0.1', service)
+
+            with self.assertRaises(OSError):
+                self.loop.run_until_complete(coro)
+
     def test_create_connection_no_local_addr(self):
         @asyncio.coroutine
         def getaddrinfo(host, *args, **kw):
@@ -1371,6 +1408,17 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
         self.assertRaises(ValueError, self.loop.run_until_complete, f)
 
     @patch_socket
+    def test_create_server_soreuseport_only_defined(self, m_socket):
+        m_socket.getaddrinfo = socket.getaddrinfo
+        m_socket.socket.return_value = mock.Mock()
+        m_socket.SO_REUSEPORT = -1
+
+        f = self.loop.create_server(
+            MyProto, '0.0.0.0', 0, reuse_port=True)
+
+        self.assertRaises(ValueError, self.loop.run_until_complete, f)
+
+    @patch_socket
     def test_create_server_cant_bind(self, m_socket):
 
         class Err(OSError):
@@ -1481,36 +1529,39 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
         self.assertEqual('CLOSED', protocol.state)
 
     def test_create_datagram_endpoint_sock_sockopts(self):
+        class FakeSock:
+            type = socket.SOCK_DGRAM
+
         fut = self.loop.create_datagram_endpoint(
-            MyDatagramProto, local_addr=('127.0.0.1', 0), sock=object())
+            MyDatagramProto, local_addr=('127.0.0.1', 0), sock=FakeSock())
         self.assertRaises(ValueError, self.loop.run_until_complete, fut)
 
         fut = self.loop.create_datagram_endpoint(
-            MyDatagramProto, remote_addr=('127.0.0.1', 0), sock=object())
+            MyDatagramProto, remote_addr=('127.0.0.1', 0), sock=FakeSock())
         self.assertRaises(ValueError, self.loop.run_until_complete, fut)
 
         fut = self.loop.create_datagram_endpoint(
-            MyDatagramProto, family=1, sock=object())
+            MyDatagramProto, family=1, sock=FakeSock())
         self.assertRaises(ValueError, self.loop.run_until_complete, fut)
 
         fut = self.loop.create_datagram_endpoint(
-            MyDatagramProto, proto=1, sock=object())
+            MyDatagramProto, proto=1, sock=FakeSock())
         self.assertRaises(ValueError, self.loop.run_until_complete, fut)
 
         fut = self.loop.create_datagram_endpoint(
-            MyDatagramProto, flags=1, sock=object())
+            MyDatagramProto, flags=1, sock=FakeSock())
         self.assertRaises(ValueError, self.loop.run_until_complete, fut)
 
         fut = self.loop.create_datagram_endpoint(
-            MyDatagramProto, reuse_address=True, sock=object())
+            MyDatagramProto, reuse_address=True, sock=FakeSock())
         self.assertRaises(ValueError, self.loop.run_until_complete, fut)
 
         fut = self.loop.create_datagram_endpoint(
-            MyDatagramProto, reuse_port=True, sock=object())
+            MyDatagramProto, reuse_port=True, sock=FakeSock())
         self.assertRaises(ValueError, self.loop.run_until_complete, fut)
 
         fut = self.loop.create_datagram_endpoint(
-            MyDatagramProto, allow_broadcast=True, sock=object())
+            MyDatagramProto, allow_broadcast=True, sock=FakeSock())
         self.assertRaises(ValueError, self.loop.run_until_complete, fut)
 
     def test_create_datagram_endpoint_sockopts(self):
@@ -1592,8 +1643,8 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
 
         m_socket.getaddrinfo = getaddrinfo
         m_socket.socket.return_value.bind = bind = mock.Mock()
-        self.loop.add_reader = mock.Mock()
-        self.loop.add_reader._is_coroutine = False
+        self.loop._add_reader = mock.Mock()
+        self.loop._add_reader._is_coroutine = False
 
         reuseport_supported = hasattr(socket, 'SO_REUSEPORT')
         coro = self.loop.create_datagram_endpoint(
@@ -1624,23 +1675,24 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
         sock = mock.Mock()
         sock.fileno.return_value = 10
         sock.accept.side_effect = OSError(errno.EMFILE, 'Too many open files')
-        self.loop.remove_reader = mock.Mock()
+        self.loop._remove_reader = mock.Mock()
         self.loop.call_later = mock.Mock()
 
         self.loop._accept_connection(MyProto, sock)
         self.assertTrue(m_log.error.called)
         self.assertFalse(sock.close.called)
-        self.loop.remove_reader.assert_called_with(10)
+        self.loop._remove_reader.assert_called_with(10)
         self.loop.call_later.assert_called_with(constants.ACCEPT_RETRY_DELAY,
                                                 # self.loop._start_serving
                                                 mock.ANY,
-                                                MyProto, sock, None, None)
+                                                MyProto, sock, None, None, mock.ANY)
 
     def test_call_coroutine(self):
         @asyncio.coroutine
         def simple_coroutine():
             pass
 
+        self.loop.set_debug(True)
         coro_func = simple_coroutine
         coro_obj = coro_func()
         self.addCleanup(coro_obj.close)
@@ -1687,5 +1739,23 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
                          "took .* seconds$")
 
 
+class RunningLoopTests(unittest.TestCase):
+
+    def test_running_loop_within_a_loop(self):
+        @asyncio.coroutine
+        def runner(loop):
+            loop.run_forever()
+
+        loop = asyncio.new_event_loop()
+        outer_loop = asyncio.new_event_loop()
+        try:
+            with self.assertRaisesRegex(RuntimeError,
+                                        'while another loop is running'):
+                outer_loop.run_until_complete(runner(loop))
+        finally:
+            loop.close()
+            outer_loop.close()
+
+
 if __name__ == '__main__':
     unittest.main()
index d077775..28d92a9 100644 (file)
@@ -1,5 +1,6 @@
 """Tests for events.py."""
 
+import collections.abc
 import functools
 import gc
 import io
@@ -21,8 +22,11 @@ import unittest
 from unittest import mock
 import weakref
 
+if sys.platform != 'win32':
+    import tty
 
 import asyncio
+from asyncio import coroutines
 from asyncio import proactor_events
 from asyncio import selector_events
 from asyncio import sslproto
@@ -744,6 +748,85 @@ class EventLoopTestsMixin:
             self.assertEqual(cm.exception.errno, errno.EADDRINUSE)
             self.assertIn(str(httpd.address), cm.exception.strerror)
 
+    def test_connect_accepted_socket(self, server_ssl=None, client_ssl=None):
+        loop = self.loop
+
+        class MyProto(MyBaseProto):
+
+            def connection_lost(self, exc):
+                super().connection_lost(exc)
+                loop.call_soon(loop.stop)
+
+            def data_received(self, data):
+                super().data_received(data)
+                self.transport.write(expected_response)
+
+        lsock = socket.socket()
+        lsock.bind(('127.0.0.1', 0))
+        lsock.listen(1)
+        addr = lsock.getsockname()
+
+        message = b'test data'
+        response = None
+        expected_response = b'roger'
+
+        def client():
+            nonlocal response
+            try:
+                csock = socket.socket()
+                if client_ssl is not None:
+                    csock = client_ssl.wrap_socket(csock)
+                csock.connect(addr)
+                csock.sendall(message)
+                response = csock.recv(99)
+                csock.close()
+            except Exception as exc:
+                print(
+                    "Failure in client thread in test_connect_accepted_socket",
+                    exc)
+
+        thread = threading.Thread(target=client, daemon=True)
+        thread.start()
+
+        conn, _ = lsock.accept()
+        proto = MyProto(loop=loop)
+        proto.loop = loop
+        loop.run_until_complete(
+            loop.connect_accepted_socket(
+                (lambda: proto), conn, ssl=server_ssl))
+        loop.run_forever()
+        proto.transport.close()
+        lsock.close()
+
+        thread.join(1)
+        self.assertFalse(thread.is_alive())
+        self.assertEqual(proto.state, 'CLOSED')
+        self.assertEqual(proto.nbytes, len(message))
+        self.assertEqual(response, expected_response)
+
+    @unittest.skipIf(ssl is None, 'No ssl module')
+    def test_ssl_connect_accepted_socket(self):
+        if (sys.platform == 'win32' and
+            sys.version_info < (3, 5) and
+            isinstance(self.loop, proactor_events.BaseProactorEventLoop)
+            ):
+            raise unittest.SkipTest(
+                'SSL not supported with proactor event loops before Python 3.5'
+                )
+
+        server_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+        server_context.load_cert_chain(ONLYCERT, ONLYKEY)
+        if hasattr(server_context, 'check_hostname'):
+            server_context.check_hostname = False
+        server_context.verify_mode = ssl.CERT_NONE
+
+        client_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+        if hasattr(server_context, 'check_hostname'):
+            client_context.check_hostname = False
+        client_context.verify_mode = ssl.CERT_NONE
+
+        self.test_connect_accepted_socket(server_context, client_context)
+
     @mock.patch('asyncio.base_events.socket')
     def create_server_multiple_hosts(self, family, hosts, mock_sock):
         @asyncio.coroutine
@@ -1294,6 +1377,11 @@ class EventLoopTestsMixin:
         server.transport.close()
 
     def test_create_datagram_endpoint_sock(self):
+        if (sys.platform == 'win32' and
+                isinstance(self.loop, proactor_events.BaseProactorEventLoop)):
+            raise unittest.SkipTest(
+                'UDP is not supported with proactor event loops')
+
         sock = None
         local_address = ('127.0.0.1', 0)
         infos = self.loop.run_until_complete(
@@ -1311,7 +1399,7 @@ class EventLoopTestsMixin:
         else:
             assert False, 'Can not create socket.'
 
-        f = self.loop.create_connection(
+        f = self.loop.create_datagram_endpoint(
             lambda: MyDatagramProto(loop=self.loop), sock=sock)
         tr, pr = self.loop.run_until_complete(f)
         self.assertIsInstance(tr, asyncio.Transport)
@@ -1547,6 +1635,79 @@ class EventLoopTestsMixin:
         self.loop.run_until_complete(proto.done)
         self.assertEqual('CLOSED', proto.state)
 
+    @unittest.skipUnless(sys.platform != 'win32',
+                         "Don't support pipes for Windows")
+    # select, poll and kqueue don't support character devices (PTY) on Mac OS X
+    # older than 10.6 (Snow Leopard)
+    @support.requires_mac_ver(10, 6)
+    def test_bidirectional_pty(self):
+        master, read_slave = os.openpty()
+        write_slave = os.dup(read_slave)
+        tty.setraw(read_slave)
+
+        slave_read_obj = io.open(read_slave, 'rb', 0)
+        read_proto = MyReadPipeProto(loop=self.loop)
+        read_connect = self.loop.connect_read_pipe(lambda: read_proto,
+                                                   slave_read_obj)
+        read_transport, p = self.loop.run_until_complete(read_connect)
+        self.assertIs(p, read_proto)
+        self.assertIs(read_transport, read_proto.transport)
+        self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state)
+        self.assertEqual(0, read_proto.nbytes)
+
+
+        slave_write_obj = io.open(write_slave, 'wb', 0)
+        write_proto = MyWritePipeProto(loop=self.loop)
+        write_connect = self.loop.connect_write_pipe(lambda: write_proto,
+                                                     slave_write_obj)
+        write_transport, p = self.loop.run_until_complete(write_connect)
+        self.assertIs(p, write_proto)
+        self.assertIs(write_transport, write_proto.transport)
+        self.assertEqual('CONNECTED', write_proto.state)
+
+        data = bytearray()
+        def reader(data):
+            chunk = os.read(master, 1024)
+            data += chunk
+            return len(data)
+
+        write_transport.write(b'1')
+        test_utils.run_until(self.loop, lambda: reader(data) >= 1, timeout=10)
+        self.assertEqual(b'1', data)
+        self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state)
+        self.assertEqual('CONNECTED', write_proto.state)
+
+        os.write(master, b'a')
+        test_utils.run_until(self.loop, lambda: read_proto.nbytes >= 1,
+                             timeout=10)
+        self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state)
+        self.assertEqual(1, read_proto.nbytes)
+        self.assertEqual('CONNECTED', write_proto.state)
+
+        write_transport.write(b'2345')
+        test_utils.run_until(self.loop, lambda: reader(data) >= 5, timeout=10)
+        self.assertEqual(b'12345', data)
+        self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state)
+        self.assertEqual('CONNECTED', write_proto.state)
+
+        os.write(master, b'bcde')
+        test_utils.run_until(self.loop, lambda: read_proto.nbytes >= 5,
+                             timeout=10)
+        self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state)
+        self.assertEqual(5, read_proto.nbytes)
+        self.assertEqual('CONNECTED', write_proto.state)
+
+        os.close(master)
+
+        read_transport.close()
+        self.loop.run_until_complete(read_proto.done)
+        self.assertEqual(
+            ['INITIAL', 'CONNECTED', 'EOF', 'CLOSED'], read_proto.state)
+
+        write_transport.close()
+        self.loop.run_until_complete(write_proto.done)
+        self.assertEqual('CLOSED', write_proto.state)
+
     def test_prompt_cancellation(self):
         r, w = test_utils.socketpair()
         r.setblocking(False)
@@ -2070,13 +2231,14 @@ else:
             return asyncio.SelectorEventLoop(selectors.SelectSelector())
 
 
-def noop(*args):
+def noop(*args, **kwargs):
     pass
 
 
 class HandleTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = mock.Mock()
         self.loop.get_debug.return_value = True
 
@@ -2093,13 +2255,6 @@ class HandleTests(test_utils.TestCase):
         h.cancel()
         self.assertTrue(h._cancelled)
 
-    def test_handle_from_handle(self):
-        def callback(*args):
-            return args
-        h1 = asyncio.Handle(callback, (), loop=self.loop)
-        self.assertRaises(
-            AssertionError, asyncio.Handle, h1, (), self.loop)
-
     def test_callback_with_exception(self):
         def callback():
             raise ValueError()
@@ -2151,6 +2306,13 @@ class HandleTests(test_utils.TestCase):
                  % (re.escape(filename), lineno))
         self.assertRegex(repr(h), regex)
 
+        # partial function with keyword args
+        cb = functools.partial(noop, x=1)
+        h = asyncio.Handle(cb, (2, 3), self.loop)
+        regex = (r'^<Handle noop\(x=1\)\(2, 3\) at %s:%s>$'
+                 % (re.escape(filename), lineno))
+        self.assertRegex(repr(h), regex)
+
         # partial method
         if sys.version_info >= (3, 4):
             method = HandleTests.test_handle_repr
@@ -2219,10 +2381,47 @@ class HandleTests(test_utils.TestCase):
         h = loop.call_later(0, noop)
         check_source_traceback(h)
 
+    @unittest.skipUnless(hasattr(collections.abc, 'Coroutine'),
+                         'No collections.abc.Coroutine')
+    def test_coroutine_like_object_debug_formatting(self):
+        # Test that asyncio can format coroutines that are instances of
+        # collections.abc.Coroutine, but lack cr_core or gi_code attributes
+        # (such as ones compiled with Cython).
+
+        class Coro:
+            def send(self, v):
+                pass
+
+            def throw(self, *exc):
+                pass
+
+            def close(self):
+                pass
+
+            def __await__(self):
+                pass
+
+        coro = Coro()
+        coro.__name__ = 'AAA'
+        self.assertTrue(asyncio.iscoroutine(coro))
+        self.assertEqual(coroutines._format_coroutine(coro), 'AAA()')
+
+        coro.__qualname__ = 'BBB'
+        self.assertEqual(coroutines._format_coroutine(coro), 'BBB()')
+
+        coro.cr_running = True
+        self.assertEqual(coroutines._format_coroutine(coro), 'BBB() running')
+
+        coro = Coro()
+        # Some coroutines might not have '__name__', such as
+        # built-in async_gen.asend().
+        self.assertEqual(coroutines._format_coroutine(coro), 'Coro()')
+
 
 class TimerTests(unittest.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = mock.Mock()
 
     def test_hash(self):
@@ -2531,6 +2730,31 @@ class PolicyTests(unittest.TestCase):
         self.assertIs(policy, asyncio.get_event_loop_policy())
         self.assertIsNot(policy, old_policy)
 
+    def test_get_event_loop_returns_running_loop(self):
+        class Policy(asyncio.DefaultEventLoopPolicy):
+            def get_event_loop(self):
+                raise NotImplementedError
+
+        loop = None
+
+        old_policy = asyncio.get_event_loop_policy()
+        try:
+            asyncio.set_event_loop_policy(Policy())
+            loop = asyncio.new_event_loop()
+            self.assertIs(asyncio._get_running_loop(), None)
+
+            async def func():
+                self.assertIs(asyncio.get_event_loop(), loop)
+                self.assertIs(asyncio._get_running_loop(), loop)
+
+            loop.run_until_complete(func())
+        finally:
+            asyncio.set_event_loop_policy(old_policy)
+            if loop is not None:
+                loop.close()
+
+        self.assertIs(asyncio._get_running_loop(), None)
+
 
 if __name__ == '__main__':
     unittest.main()
index c38c1f2..c306b77 100644 (file)
@@ -25,12 +25,105 @@ def last_cb():
     pass
 
 
+class DuckFuture:
+    # Class that does not inherit from Future but aims to be duck-type
+    # compatible with it.
+
+    _asyncio_future_blocking = False
+    __cancelled = False
+    __result = None
+    __exception = None
+
+    def cancel(self):
+        if self.done():
+            return False
+        self.__cancelled = True
+        return True
+
+    def cancelled(self):
+        return self.__cancelled
+
+    def done(self):
+        return (self.__cancelled
+                or self.__result is not None
+                or self.__exception is not None)
+
+    def result(self):
+        assert not self.cancelled()
+        if self.__exception is not None:
+            raise self.__exception
+        return self.__result
+
+    def exception(self):
+        assert not self.cancelled()
+        return self.__exception
+
+    def set_result(self, result):
+        assert not self.done()
+        assert result is not None
+        self.__result = result
+
+    def set_exception(self, exception):
+        assert not self.done()
+        assert exception is not None
+        self.__exception = exception
+
+    def __iter__(self):
+        if not self.done():
+            self._asyncio_future_blocking = True
+            yield self
+        assert self.done()
+        return self.result()
+
+
+class DuckTests(test_utils.TestCase):
+
+    def setUp(self):
+        super().setUp()
+        self.loop = self.new_test_loop()
+        self.addCleanup(self.loop.close)
+
+    def test_wrap_future(self):
+        f = DuckFuture()
+        g = asyncio.wrap_future(f)
+        assert g is f
+
+    def test_ensure_future(self):
+        f = DuckFuture()
+        g = asyncio.ensure_future(f)
+        assert g is f
+
+
 class FutureTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.addCleanup(self.loop.close)
 
+    def test_isfuture(self):
+        class MyFuture:
+            _asyncio_future_blocking = None
+
+            def __init__(self):
+                self._asyncio_future_blocking = False
+
+        self.assertFalse(asyncio.isfuture(MyFuture))
+        self.assertTrue(asyncio.isfuture(MyFuture()))
+
+        self.assertFalse(asyncio.isfuture(1))
+        self.assertFalse(asyncio.isfuture(asyncio.Future))
+
+        # As `isinstance(Mock(), Future)` returns `False`
+        self.assertFalse(asyncio.isfuture(mock.Mock()))
+
+        # As `isinstance(Mock(Future), Future)` returns `True`
+        self.assertTrue(asyncio.isfuture(mock.Mock(asyncio.Future)))
+
+        f = asyncio.Future(loop=self.loop)
+        self.assertTrue(asyncio.isfuture(f))
+        f.cancel()
+
     def test_initial_state(self):
         f = asyncio.Future(loop=self.loop)
         self.assertFalse(f.cancelled())
@@ -400,6 +493,7 @@ class FutureTests(test_utils.TestCase):
 class FutureDoneCallbackTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
 
     def run_briefly(self):
index d3bdc51..152948c 100644 (file)
@@ -19,6 +19,7 @@ RGX_REPR = re.compile(STR_RGX_REPR)
 class LockTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
 
     def test_ctor_loop(self):
@@ -130,8 +131,8 @@ class LockTests(test_utils.TestCase):
     def test_cancel_race(self):
         # Several tasks:
         # - A acquires the lock
-        # - B is blocked in aqcuire()
-        # - C is blocked in aqcuire()
+        # - B is blocked in acquire()
+        # - C is blocked in acquire()
         #
         # Now, concurrently:
         # - B is cancelled
@@ -235,6 +236,7 @@ class LockTests(test_utils.TestCase):
 class EventTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
 
     def test_ctor_loop(self):
@@ -364,6 +366,7 @@ class EventTests(test_utils.TestCase):
 class ConditionTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
 
     def test_ctor_loop(self):
@@ -699,6 +702,7 @@ class ConditionTests(test_utils.TestCase):
 class SemaphoreTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
 
     def test_ctor_loop(self):
index 29aba81..d5b8522 100644 (file)
@@ -17,6 +17,7 @@ from asyncio import test_utils
 class BaseTest(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = asyncio.BaseEventLoop()
         self.loop._process_events = mock.Mock()
         self.loop._selector = mock.Mock()
index 5a92b1e..4dfc612 100644 (file)
@@ -24,6 +24,7 @@ def close_transport(transport):
 class ProactorSocketTransportTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.addCleanup(self.loop.close)
         self.proactor = mock.Mock()
@@ -436,6 +437,8 @@ class ProactorSocketTransportTests(test_utils.TestCase):
 class BaseProactorEventLoopTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
+
         self.sock = test_utils.mock_nonblocking_socket()
         self.proactor = mock.Mock()
 
index 591a9bb..fe5a6db 100644 (file)
@@ -10,6 +10,7 @@ from asyncio import test_utils
 class _QueueTestBase(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
 
 
index 5dc6ff8..6bf7862 100644 (file)
@@ -51,6 +51,7 @@ def close_transport(transport):
 class BaseSelectorEventLoopTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.selector = mock.Mock()
         self.selector.select.return_value = []
         self.loop = TestBaseSelectorEventLoop(self.selector)
@@ -72,11 +73,11 @@ class BaseSelectorEventLoopTests(test_utils.TestCase):
     @unittest.skipIf(ssl is None, 'No ssl module')
     def test_make_ssl_transport(self):
         m = mock.Mock()
-        self.loop.add_reader = mock.Mock()
-        self.loop.add_reader._is_coroutine = False
-        self.loop.add_writer = mock.Mock()
-        self.loop.remove_reader = mock.Mock()
-        self.loop.remove_writer = mock.Mock()
+        self.loop._add_reader = mock.Mock()
+        self.loop._add_reader._is_coroutine = False
+        self.loop._add_writer = mock.Mock()
+        self.loop._remove_reader = mock.Mock()
+        self.loop._remove_writer = mock.Mock()
         waiter = asyncio.Future(loop=self.loop)
         with test_utils.disable_logger():
             transport = self.loop._make_ssl_transport(
@@ -119,7 +120,7 @@ class BaseSelectorEventLoopTests(test_utils.TestCase):
         ssock.fileno.return_value = 7
         csock = self.loop._csock
         csock.fileno.return_value = 1
-        remove_reader = self.loop.remove_reader = mock.Mock()
+        remove_reader = self.loop._remove_reader = mock.Mock()
 
         self.loop._selector.close()
         self.loop._selector = selector = mock.Mock()
@@ -337,18 +338,6 @@ class BaseSelectorEventLoopTests(test_utils.TestCase):
             (10, self.loop._sock_sendall, f, True, sock, b'data'),
             self.loop.add_writer.call_args[0])
 
-    def test_sock_connect(self):
-        sock = test_utils.mock_nonblocking_socket()
-        self.loop._sock_connect = mock.Mock()
-
-        f = self.loop.sock_connect(sock, ('127.0.0.1', 8080))
-        self.assertIsInstance(f, asyncio.Future)
-        self.loop._run_once()
-        future_in, sock_in, address_in = self.loop._sock_connect.call_args[0]
-        self.assertEqual(future_in, f)
-        self.assertEqual(sock_in, sock)
-        self.assertEqual(address_in, ('127.0.0.1', 8080))
-
     def test_sock_connect_timeout(self):
         # asyncio issue #205: sock_connect() must unregister the socket on
         # timeout error
@@ -360,19 +349,35 @@ class BaseSelectorEventLoopTests(test_utils.TestCase):
         sock.connect.side_effect = BlockingIOError
 
         # first call to sock_connect() registers the socket
-        fut = self.loop.sock_connect(sock, ('127.0.0.1', 80))
+        fut = self.loop.create_task(
+            self.loop.sock_connect(sock, ('127.0.0.1', 80)))
         self.loop._run_once()
         self.assertTrue(sock.connect.called)
         self.assertTrue(self.loop.add_writer.called)
-        self.assertEqual(len(fut._callbacks), 1)
 
         # on timeout, the socket must be unregistered
         sock.connect.reset_mock()
-        fut.set_exception(asyncio.TimeoutError)
-        with self.assertRaises(asyncio.TimeoutError):
+        fut.cancel()
+        with self.assertRaises(asyncio.CancelledError):
             self.loop.run_until_complete(fut)
         self.assertTrue(self.loop.remove_writer.called)
 
+    @mock.patch('socket.getaddrinfo')
+    def test_sock_connect_resolve_using_socket_params(self, m_gai):
+        addr = ('need-resolution.com', 8080)
+        sock = test_utils.mock_nonblocking_socket()
+        m_gai.side_effect = (None, None, None, None, ('127.0.0.1', 0))
+        m_gai._is_coroutine = False
+        con = self.loop.create_task(self.loop.sock_connect(sock, addr))
+        while not m_gai.called:
+            self.loop._run_once()
+        m_gai.assert_called_with(
+            addr[0], addr[1], sock.family, sock.type, sock.proto, 0)
+
+        con.cancel()
+        with self.assertRaises(asyncio.CancelledError):
+            self.loop.run_until_complete(con)
+
     def test__sock_connect(self):
         f = asyncio.Future(loop=self.loop)
 
@@ -647,12 +652,12 @@ class BaseSelectorEventLoopTests(test_utils.TestCase):
         reader = mock.Mock()
         reader.cancelled = True
 
-        self.loop.remove_reader = mock.Mock()
+        self.loop._remove_reader = mock.Mock()
         self.loop._process_events(
             [(selectors.SelectorKey(
                 1, 1, selectors.EVENT_READ, (reader, None)),
              selectors.EVENT_READ)])
-        self.loop.remove_reader.assert_called_with(1)
+        self.loop._remove_reader.assert_called_with(1)
 
     def test_process_events_write(self):
         writer = mock.Mock()
@@ -668,18 +673,33 @@ class BaseSelectorEventLoopTests(test_utils.TestCase):
     def test_process_events_write_cancelled(self):
         writer = mock.Mock()
         writer.cancelled = True
-        self.loop.remove_writer = mock.Mock()
+        self.loop._remove_writer = mock.Mock()
 
         self.loop._process_events(
             [(selectors.SelectorKey(1, 1, selectors.EVENT_WRITE,
                                     (None, writer)),
               selectors.EVENT_WRITE)])
-        self.loop.remove_writer.assert_called_with(1)
+        self.loop._remove_writer.assert_called_with(1)
+
+    def test_accept_connection_multiple(self):
+        sock = mock.Mock()
+        sock.accept.return_value = (mock.Mock(), mock.Mock())
+        backlog = 100
+        # Mock the coroutine generation for a connection to prevent
+        # warnings related to un-awaited coroutines.
+        mock_obj = mock.patch.object
+        with mock_obj(self.loop, '_accept_connection2') as accept2_mock:
+            accept2_mock.return_value = None
+            with mock_obj(self.loop, 'create_task') as task_mock:
+                task_mock.return_value = None
+                self.loop._accept_connection(mock.Mock(), sock, backlog=backlog)
+        self.assertEqual(sock.accept.call_count, backlog)
 
 
 class SelectorTransportTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.protocol = test_utils.make_test_protocol(asyncio.Protocol)
         self.sock = mock.Mock(socket.socket)
@@ -729,8 +749,8 @@ class SelectorTransportTests(test_utils.TestCase):
     def test_force_close(self):
         tr = self.create_transport()
         tr._buffer.extend(b'1')
-        self.loop.add_reader(7, mock.sentinel)
-        self.loop.add_writer(7, mock.sentinel)
+        self.loop._add_reader(7, mock.sentinel)
+        self.loop._add_writer(7, mock.sentinel)
         tr._force_close(None)
 
         self.assertTrue(tr.is_closing())
@@ -775,6 +795,7 @@ class SelectorTransportTests(test_utils.TestCase):
 class SelectorSocketTransportTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.protocol = test_utils.make_test_protocol(asyncio.Protocol)
         self.sock = mock.Mock(socket.socket)
@@ -1019,7 +1040,7 @@ class SelectorSocketTransportTests(test_utils.TestCase):
 
         transport = self.socket_transport()
         transport._buffer.extend(data)
-        self.loop.add_writer(7, transport._write_ready)
+        self.loop._add_writer(7, transport._write_ready)
         transport._write_ready()
         self.assertTrue(self.sock.send.called)
         self.assertFalse(self.loop.writers)
@@ -1031,7 +1052,7 @@ class SelectorSocketTransportTests(test_utils.TestCase):
         transport = self.socket_transport()
         transport._closing = True
         transport._buffer.extend(data)
-        self.loop.add_writer(7, transport._write_ready)
+        self.loop._add_writer(7, transport._write_ready)
         transport._write_ready()
         self.assertTrue(self.sock.send.called)
         self.assertFalse(self.loop.writers)
@@ -1049,7 +1070,7 @@ class SelectorSocketTransportTests(test_utils.TestCase):
 
         transport = self.socket_transport()
         transport._buffer.extend(data)
-        self.loop.add_writer(7, transport._write_ready)
+        self.loop._add_writer(7, transport._write_ready)
         transport._write_ready()
         self.loop.assert_writer(7, transport._write_ready)
         self.assertEqual(list_to_buffer([b'ta']), transport._buffer)
@@ -1060,7 +1081,7 @@ class SelectorSocketTransportTests(test_utils.TestCase):
 
         transport = self.socket_transport()
         transport._buffer.extend(data)
-        self.loop.add_writer(7, transport._write_ready)
+        self.loop._add_writer(7, transport._write_ready)
         transport._write_ready()
         self.loop.assert_writer(7, transport._write_ready)
         self.assertEqual(list_to_buffer([b'data']), transport._buffer)
@@ -1070,7 +1091,7 @@ class SelectorSocketTransportTests(test_utils.TestCase):
 
         transport = self.socket_transport()
         transport._buffer = list_to_buffer([b'data1', b'data2'])
-        self.loop.add_writer(7, transport._write_ready)
+        self.loop._add_writer(7, transport._write_ready)
         transport._write_ready()
 
         self.loop.assert_writer(7, transport._write_ready)
@@ -1112,7 +1133,7 @@ class SelectorSocketTransportTests(test_utils.TestCase):
 
     @mock.patch('asyncio.base_events.logger')
     def test_transport_close_remove_writer(self, m_log):
-        remove_writer = self.loop.remove_writer = mock.Mock()
+        remove_writer = self.loop._remove_writer = mock.Mock()
 
         transport = self.socket_transport()
         transport.close()
@@ -1123,6 +1144,7 @@ class SelectorSocketTransportTests(test_utils.TestCase):
 class SelectorSslTransportTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.protocol = test_utils.make_test_protocol(asyncio.Protocol)
         self.sock = mock.Mock(socket.socket)
@@ -1270,7 +1292,7 @@ class SelectorSslTransportTests(test_utils.TestCase):
         self.assertEqual((b'data',), self.protocol.data_received.call_args[0])
 
     def test_read_ready_write_wants_read(self):
-        self.loop.add_writer = mock.Mock()
+        self.loop._add_writer = mock.Mock()
         self.sslsock.recv.side_effect = BlockingIOError
         transport = self._make_one()
         transport._write_wants_read = True
@@ -1280,7 +1302,7 @@ class SelectorSslTransportTests(test_utils.TestCase):
 
         self.assertFalse(transport._write_wants_read)
         transport._write_ready.assert_called_with()
-        self.loop.add_writer.assert_called_with(
+        self.loop._add_writer.assert_called_with(
             transport._sock_fd, transport._write_ready)
 
     def test_read_ready_recv_eof(self):
@@ -1315,16 +1337,16 @@ class SelectorSslTransportTests(test_utils.TestCase):
         self.assertFalse(self.protocol.data_received.called)
 
     def test_read_ready_recv_write(self):
-        self.loop.remove_reader = mock.Mock()
-        self.loop.add_writer = mock.Mock()
+        self.loop._remove_reader = mock.Mock()
+        self.loop._add_writer = mock.Mock()
         self.sslsock.recv.side_effect = ssl.SSLWantWriteError
         transport = self._make_one()
         transport._read_ready()
         self.assertFalse(self.protocol.data_received.called)
         self.assertTrue(transport._read_wants_write)
 
-        self.loop.remove_reader.assert_called_with(transport._sock_fd)
-        self.loop.add_writer.assert_called_with(
+        self.loop._remove_reader.assert_called_with(transport._sock_fd)
+        self.loop._add_writer.assert_called_with(
             transport._sock_fd, transport._write_ready)
 
     def test_read_ready_recv_exc(self):
@@ -1401,12 +1423,12 @@ class SelectorSslTransportTests(test_utils.TestCase):
         transport = self._make_one()
         transport._buffer = list_to_buffer([b'data'])
 
-        self.loop.remove_writer = mock.Mock()
+        self.loop._remove_writer = mock.Mock()
         self.sslsock.send.side_effect = ssl.SSLWantReadError
         transport._write_ready()
         self.assertFalse(self.protocol.data_received.called)
         self.assertTrue(transport._write_wants_read)
-        self.loop.remove_writer.assert_called_with(transport._sock_fd)
+        self.loop._remove_writer.assert_called_with(transport._sock_fd)
 
     def test_write_ready_send_exc(self):
         err = self.sslsock.send.side_effect = OSError()
@@ -1421,7 +1443,7 @@ class SelectorSslTransportTests(test_utils.TestCase):
         self.assertEqual(list_to_buffer(), transport._buffer)
 
     def test_write_ready_read_wants_write(self):
-        self.loop.add_reader = mock.Mock()
+        self.loop._add_reader = mock.Mock()
         self.sslsock.send.side_effect = BlockingIOError
         transport = self._make_one()
         transport._read_wants_write = True
@@ -1430,7 +1452,7 @@ class SelectorSslTransportTests(test_utils.TestCase):
 
         self.assertFalse(transport._read_wants_write)
         transport._read_ready.assert_called_with()
-        self.loop.add_reader.assert_called_with(
+        self.loop._add_reader.assert_called_with(
             transport._sock_fd, transport._read_ready)
 
     def test_write_eof(self):
@@ -1483,6 +1505,7 @@ class SelectorSslWithoutSslTransportTests(unittest.TestCase):
 class SelectorDatagramTransportTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.protocol = test_utils.make_test_protocol(asyncio.DatagramProtocol)
         self.sock = mock.Mock(spec_set=socket.socket)
@@ -1681,7 +1704,7 @@ class SelectorDatagramTransportTests(test_utils.TestCase):
 
         transport = self.datagram_transport()
         transport._buffer.append((data, ('0.0.0.0', 12345)))
-        self.loop.add_writer(7, transport._sendto_ready)
+        self.loop._add_writer(7, transport._sendto_ready)
         transport._sendto_ready()
         self.assertTrue(self.sock.sendto.called)
         self.assertEqual(
@@ -1695,7 +1718,7 @@ class SelectorDatagramTransportTests(test_utils.TestCase):
         transport = self.datagram_transport()
         transport._closing = True
         transport._buffer.append((data, ()))
-        self.loop.add_writer(7, transport._sendto_ready)
+        self.loop._add_writer(7, transport._sendto_ready)
         transport._sendto_ready()
         self.sock.sendto.assert_called_with(data, ())
         self.assertFalse(self.loop.writers)
@@ -1704,7 +1727,7 @@ class SelectorDatagramTransportTests(test_utils.TestCase):
 
     def test_sendto_ready_no_data(self):
         transport = self.datagram_transport()
-        self.loop.add_writer(7, transport._sendto_ready)
+        self.loop._add_writer(7, transport._sendto_ready)
         transport._sendto_ready()
         self.assertFalse(self.sock.sendto.called)
         self.assertFalse(self.loop.writers)
@@ -1714,7 +1737,7 @@ class SelectorDatagramTransportTests(test_utils.TestCase):
 
         transport = self.datagram_transport()
         transport._buffer.extend([(b'data1', ()), (b'data2', ())])
-        self.loop.add_writer(7, transport._sendto_ready)
+        self.loop._add_writer(7, transport._sendto_ready)
         transport._sendto_ready()
 
         self.loop.assert_writer(7, transport._sendto_ready)
@@ -1766,6 +1789,5 @@ class SelectorDatagramTransportTests(test_utils.TestCase):
                 'Fatal error on transport\nprotocol:.*\ntransport:.*'),
             exc_info=(ConnectionRefusedError, MOCK_ANY, MOCK_ANY))
 
-
 if __name__ == '__main__':
     unittest.main()
index e4121a0..59ff0f6 100644 (file)
@@ -1,5 +1,6 @@
 """Tests for asyncio/sslproto.py."""
 
+import logging
 import unittest
 from unittest import mock
 try:
@@ -8,6 +9,7 @@ except ImportError:
     ssl = None
 
 import asyncio
+from asyncio import log
 from asyncio import sslproto
 from asyncio import test_utils
 
@@ -16,6 +18,7 @@ from asyncio import test_utils
 class SslProtoHandshakeTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = asyncio.new_event_loop()
         self.set_event_loop(self.loop)
 
@@ -23,6 +26,7 @@ class SslProtoHandshakeTests(test_utils.TestCase):
         sslcontext = test_utils.dummy_ssl_context()
         app_proto = asyncio.Protocol()
         proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter)
+        self.assertIs(proto._app_transport.get_protocol(), app_proto)
         self.addCleanup(proto._app_transport.close)
         return proto
 
@@ -66,6 +70,30 @@ class SslProtoHandshakeTests(test_utils.TestCase):
         test_utils.run_briefly(self.loop)
         self.assertIsInstance(waiter.exception(), ConnectionResetError)
 
+    def test_fatal_error_no_name_error(self):
+        # From issue #363.
+        # _fatal_error() generates a NameError if sslproto.py
+        # does not import base_events.
+        waiter = asyncio.Future(loop=self.loop)
+        ssl_proto = self.ssl_protocol(waiter)
+        # Temporarily turn off error logging so as not to spoil test output.
+        log_level = log.logger.getEffectiveLevel()
+        log.logger.setLevel(logging.FATAL)
+        try:
+            ssl_proto._fatal_error(None)
+        finally:
+            # Restore error logging.
+            log.logger.setLevel(log_level)
+
+    def test_connection_lost(self):
+        # From issue #472.
+        # yield from waiter hang if lost_connection was called.
+        waiter = asyncio.Future(loop=self.loop)
+        ssl_proto = self.ssl_protocol(waiter)
+        self.connection_made(ssl_proto)
+        ssl_proto.connection_lost(ConnectionAbortedError)
+        test_utils.run_briefly(self.loop)
+        self.assertIsInstance(waiter.exception(), ConnectionAbortedError)
 
 if __name__ == '__main__':
     unittest.main()
index 1783d5f..b47433a 100644 (file)
@@ -22,6 +22,7 @@ class StreamReaderTests(test_utils.TestCase):
     DATA = b'line1\nline2\nline3\n'
 
     def setUp(self):
+        super().setUp()
         self.loop = asyncio.new_event_loop()
         self.set_event_loop(self.loop)
 
@@ -831,7 +832,7 @@ os.close(fd)
         stream._waiter = asyncio.Future(loop=self.loop)
         self.assertRegex(
             repr(stream),
-            "<StreamReader w=<Future pending[\S ]*>>")
+            r"<StreamReader w=<Future pending[\S ]*>>")
         stream._waiter.set_result(None)
         self.loop.run_until_complete(stream._waiter)
         stream._waiter = None
index 58f7253..bba688b 100644 (file)
@@ -35,6 +35,7 @@ class TestSubprocessTransport(base_subprocess.BaseSubprocessTransport):
 
 class SubprocessTransportTests(test_utils.TestCase):
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.set_event_loop(self.loop)
 
@@ -433,6 +434,13 @@ class SubprocessMixin:
         # the transport was not notified yet
         self.assertFalse(killed)
 
+        # Unlike SafeChildWatcher, FastChildWatcher does not pop the
+        # callbacks if waitpid() is called elsewhere. Let's clear them
+        # manually to avoid a warning when the watcher is detached.
+        if sys.platform != 'win32' and \
+           isinstance(self, SubprocessFastWatcherTests):
+            asyncio.get_child_watcher()._callbacks.clear()
+
     def test_popen_error(self):
         # Issue #24763: check that the subprocess transport is closed
         # when BaseSubprocessTransport fails
@@ -459,6 +467,7 @@ if sys.platform != 'win32':
         Watcher = None
 
         def setUp(self):
+            super().setUp()
             policy = asyncio.get_event_loop_policy()
             self.loop = policy.new_event_loop()
             self.set_event_loop(self.loop)
@@ -483,6 +492,7 @@ else:
     class SubprocessProactorTests(SubprocessMixin, test_utils.TestCase):
 
         def setUp(self):
+            super().setUp()
             self.loop = asyncio.ProactorEventLoop()
             self.set_event_loop(self.loop)
 
index e7fb774..9872926 100644 (file)
@@ -75,6 +75,7 @@ class Dummy:
 class TaskTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
 
     def test_other_loop_future(self):
@@ -92,6 +93,17 @@ class TaskTests(test_utils.TestCase):
         finally:
             other_loop.close()
 
+    def test_task_awaits_on_itself(self):
+        @asyncio.coroutine
+        def test():
+            yield from task
+
+        task = asyncio.ensure_future(test(), loop=self.loop)
+
+        with self.assertRaisesRegex(RuntimeError,
+                                    'Task cannot await on itself'):
+            self.loop.run_until_complete(task)
+
     def test_task_class(self):
         @asyncio.coroutine
         def notmuch():
@@ -1364,6 +1376,8 @@ class TaskTests(test_utils.TestCase):
             yield
         self.assertTrue(asyncio.iscoroutinefunction(fn2))
 
+        self.assertFalse(asyncio.iscoroutinefunction(mock.Mock()))
+
     def test_yield_vs_yield_from(self):
         fut = asyncio.Future(loop=self.loop)
 
@@ -1723,6 +1737,37 @@ class TaskTests(test_utils.TestCase):
         wd['cw'] = cw  # Would fail without __weakref__ slot.
         cw.gen = None  # Suppress warning from __del__.
 
+    def test_corowrapper_throw(self):
+        # Issue 429: CoroWrapper.throw must be compatible with gen.throw
+        def foo():
+            value = None
+            while True:
+                try:
+                    value = yield value
+                except Exception as e:
+                    value = e
+
+        exception = Exception("foo")
+        cw = asyncio.coroutines.CoroWrapper(foo())
+        cw.send(None)
+        self.assertIs(exception, cw.throw(exception))
+
+        cw = asyncio.coroutines.CoroWrapper(foo())
+        cw.send(None)
+        self.assertIs(exception, cw.throw(Exception, exception))
+
+        cw = asyncio.coroutines.CoroWrapper(foo())
+        cw.send(None)
+        exception = cw.throw(Exception, "foo")
+        self.assertIsInstance(exception, Exception)
+        self.assertEqual(exception.args, ("foo", ))
+
+        cw = asyncio.coroutines.CoroWrapper(foo())
+        cw.send(None)
+        exception = cw.throw(Exception, "foo", None)
+        self.assertIsInstance(exception, Exception)
+        self.assertEqual(exception.args, ("foo", ))
+
     @unittest.skipUnless(PY34,
                          'need python 3.4 or later')
     def test_log_destroyed_pending_task(self):
@@ -1857,10 +1902,41 @@ class TaskTests(test_utils.TestCase):
     def test_cancel_wait_for(self):
         self._test_cancel_wait_for(60.0)
 
+    def test_cancel_gather(self):
+        """Ensure that a gathering future refuses to be cancelled once all
+        children are done"""
+        loop = asyncio.new_event_loop()
+        self.addCleanup(loop.close)
+
+        fut = asyncio.Future(loop=loop)
+        # The indirection fut->child_coro is needed since otherwise the
+        # gathering task is done at the same time as the child future
+        def child_coro():
+            return (yield from fut)
+        gather_future = asyncio.gather(child_coro(), loop=loop)
+        gather_task = asyncio.ensure_future(gather_future, loop=loop)
+
+        cancel_result = None
+        def cancelling_callback(_):
+            nonlocal cancel_result
+            cancel_result = gather_task.cancel()
+        fut.add_done_callback(cancelling_callback)
+
+        fut.set_result(42) # calls the cancelling_callback after fut is done()
+
+        # At this point the task should complete.
+        loop.run_until_complete(gather_task)
+
+        # Python issue #26923: asyncio.gather drops cancellation
+        self.assertEqual(cancel_result, False)
+        self.assertFalse(gather_task.cancelled())
+        self.assertEqual(gather_task.result(), [42])
+
 
 class GatherTestsBase:
 
     def setUp(self):
+        super().setUp()
         self.one_loop = self.new_test_loop()
         self.other_loop = self.new_test_loop()
         self.set_event_loop(self.one_loop, cleanup=False)
@@ -2144,6 +2220,7 @@ class RunCoroutineThreadsafeTests(test_utils.TestCase):
     """Test case for asyncio.run_coroutine_threadsafe."""
 
     def setUp(self):
+        super().setUp()
         self.loop = asyncio.new_event_loop()
         self.set_event_loop(self.loop) # Will cleanup properly
 
@@ -2234,12 +2311,14 @@ class RunCoroutineThreadsafeTests(test_utils.TestCase):
 
 class SleepTests(test_utils.TestCase):
     def setUp(self):
+        super().setUp()
         self.loop = asyncio.new_event_loop()
         asyncio.set_event_loop(None)
 
     def tearDown(self):
         self.loop.close()
         self.loop = None
+        super().tearDown()
 
     def test_sleep_zero(self):
         result = 0
index 22dc688..5a49984 100644 (file)
@@ -4,6 +4,7 @@ import collections
 import errno
 import io
 import os
+import pathlib
 import signal
 import socket
 import stat
@@ -11,6 +12,7 @@ import sys
 import tempfile
 import threading
 import unittest
+import warnings
 from unittest import mock
 
 if sys.platform == 'win32':
@@ -39,6 +41,7 @@ def close_pipe_transport(transport):
 class SelectorEventLoopSignalTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = asyncio.SelectorEventLoop()
         self.set_event_loop(self.loop)
 
@@ -233,6 +236,7 @@ class SelectorEventLoopSignalTests(test_utils.TestCase):
 class SelectorEventLoopUnixSocketTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = asyncio.SelectorEventLoop()
         self.set_event_loop(self.loop)
 
@@ -240,11 +244,22 @@ class SelectorEventLoopUnixSocketTests(test_utils.TestCase):
         with test_utils.unix_socket_path() as path:
             sock = socket.socket(socket.AF_UNIX)
             sock.bind(path)
-            with sock:
-                coro = self.loop.create_unix_server(lambda: None, path)
-                with self.assertRaisesRegex(OSError,
-                                            'Address.*is already in use'):
-                    self.loop.run_until_complete(coro)
+            sock.listen(1)
+            sock.close()
+
+            coro = self.loop.create_unix_server(lambda: None, path)
+            srv = self.loop.run_until_complete(coro)
+            srv.close()
+            self.loop.run_until_complete(srv.wait_closed())
+
+    @unittest.skipUnless(hasattr(os, 'fspath'), 'no os.fspath')
+    def test_create_unix_server_pathlib(self):
+        with test_utils.unix_socket_path() as path:
+            path = pathlib.Path(path)
+            srv_coro = self.loop.create_unix_server(lambda: None, path)
+            srv = self.loop.run_until_complete(srv_coro)
+            srv.close()
+            self.loop.run_until_complete(srv.wait_closed())
 
     def test_create_unix_server_existing_path_nonsock(self):
         with tempfile.NamedTemporaryFile() as file:
@@ -272,7 +287,43 @@ class SelectorEventLoopUnixSocketTests(test_utils.TestCase):
             coro = self.loop.create_unix_server(lambda: None, path=None,
                                                 sock=sock)
             with self.assertRaisesRegex(ValueError,
-                                        'A UNIX Domain Socket was expected'):
+                                        'A UNIX Domain Stream.*was expected'):
+                self.loop.run_until_complete(coro)
+
+    def test_create_unix_server_path_dgram(self):
+        sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
+        with sock:
+            coro = self.loop.create_unix_server(lambda: None, path=None,
+                                                sock=sock)
+            with self.assertRaisesRegex(ValueError,
+                                        'A UNIX Domain Stream.*was expected'):
+                self.loop.run_until_complete(coro)
+
+    @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
+                         'no socket.SOCK_NONBLOCK (linux only)')
+    def test_create_unix_server_path_stream_bittype(self):
+        sock = socket.socket(
+            socket.AF_UNIX, socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
+        with tempfile.NamedTemporaryFile() as file:
+            fn = file.name
+        try:
+            with sock:
+                sock.bind(fn)
+                coro = self.loop.create_unix_server(lambda: None, path=None,
+                                                    sock=sock)
+                srv = self.loop.run_until_complete(coro)
+                srv.close()
+                self.loop.run_until_complete(srv.wait_closed())
+        finally:
+            os.unlink(fn)
+
+    def test_create_unix_connection_path_inetsock(self):
+        sock = socket.socket()
+        with sock:
+            coro = self.loop.create_unix_connection(lambda: None, path=None,
+                                                    sock=sock)
+            with self.assertRaisesRegex(ValueError,
+                                        'A UNIX Domain Stream.*was expected'):
                 self.loop.run_until_complete(coro)
 
     @mock.patch('asyncio.unix_events.socket')
@@ -326,6 +377,7 @@ class SelectorEventLoopUnixSocketTests(test_utils.TestCase):
 class UnixReadPipeTransportTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.protocol = test_utils.make_test_protocol(asyncio.Protocol)
         self.pipe = mock.Mock(spec_set=io.RawIOBase)
@@ -475,6 +527,7 @@ class UnixReadPipeTransportTests(test_utils.TestCase):
 class UnixWritePipeTransportTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.protocol = test_utils.make_test_protocol(asyncio.BaseProtocol)
         self.pipe = mock.Mock(spec_set=io.RawIOBase)
@@ -518,7 +571,7 @@ class UnixWritePipeTransportTests(test_utils.TestCase):
         tr.write(b'data')
         m_write.assert_called_with(5, b'data')
         self.assertFalse(self.loop.writers)
-        self.assertEqual([], tr._buffer)
+        self.assertEqual(bytearray(), tr._buffer)
 
     @mock.patch('os.write')
     def test_write_no_data(self, m_write):
@@ -526,35 +579,34 @@ class UnixWritePipeTransportTests(test_utils.TestCase):
         tr.write(b'')
         self.assertFalse(m_write.called)
         self.assertFalse(self.loop.writers)
-        self.assertEqual([], tr._buffer)
+        self.assertEqual(bytearray(b''), tr._buffer)
 
     @mock.patch('os.write')
     def test_write_partial(self, m_write):
         tr = self.write_pipe_transport()
         m_write.return_value = 2
         tr.write(b'data')
-        m_write.assert_called_with(5, b'data')
         self.loop.assert_writer(5, tr._write_ready)
-        self.assertEqual([b'ta'], tr._buffer)
+        self.assertEqual(bytearray(b'ta'), tr._buffer)
 
     @mock.patch('os.write')
     def test_write_buffer(self, m_write):
         tr = self.write_pipe_transport()
         self.loop.add_writer(5, tr._write_ready)
-        tr._buffer = [b'previous']
+        tr._buffer = bytearray(b'previous')
         tr.write(b'data')
         self.assertFalse(m_write.called)
         self.loop.assert_writer(5, tr._write_ready)
-        self.assertEqual([b'previous', b'data'], tr._buffer)
+        self.assertEqual(bytearray(b'previousdata'), tr._buffer)
 
     @mock.patch('os.write')
     def test_write_again(self, m_write):
         tr = self.write_pipe_transport()
         m_write.side_effect = BlockingIOError()
         tr.write(b'data')
-        m_write.assert_called_with(5, b'data')
+        m_write.assert_called_with(5, bytearray(b'data'))
         self.loop.assert_writer(5, tr._write_ready)
-        self.assertEqual([b'data'], tr._buffer)
+        self.assertEqual(bytearray(b'data'), tr._buffer)
 
     @mock.patch('asyncio.unix_events.logger')
     @mock.patch('os.write')
@@ -566,7 +618,7 @@ class UnixWritePipeTransportTests(test_utils.TestCase):
         tr.write(b'data')
         m_write.assert_called_with(5, b'data')
         self.assertFalse(self.loop.writers)
-        self.assertEqual([], tr._buffer)
+        self.assertEqual(bytearray(), tr._buffer)
         tr._fatal_error.assert_called_with(
                             err,
                             'Fatal write error on pipe transport')
@@ -606,58 +658,55 @@ class UnixWritePipeTransportTests(test_utils.TestCase):
     def test__write_ready(self, m_write):
         tr = self.write_pipe_transport()
         self.loop.add_writer(5, tr._write_ready)
-        tr._buffer = [b'da', b'ta']
+        tr._buffer = bytearray(b'data')
         m_write.return_value = 4
         tr._write_ready()
-        m_write.assert_called_with(5, b'data')
         self.assertFalse(self.loop.writers)
-        self.assertEqual([], tr._buffer)
+        self.assertEqual(bytearray(), tr._buffer)
 
     @mock.patch('os.write')
     def test__write_ready_partial(self, m_write):
         tr = self.write_pipe_transport()
         self.loop.add_writer(5, tr._write_ready)
-        tr._buffer = [b'da', b'ta']
+        tr._buffer = bytearray(b'data')
         m_write.return_value = 3
         tr._write_ready()
-        m_write.assert_called_with(5, b'data')
         self.loop.assert_writer(5, tr._write_ready)
-        self.assertEqual([b'a'], tr._buffer)
+        self.assertEqual(bytearray(b'a'), tr._buffer)
 
     @mock.patch('os.write')
     def test__write_ready_again(self, m_write):
         tr = self.write_pipe_transport()
         self.loop.add_writer(5, tr._write_ready)
-        tr._buffer = [b'da', b'ta']
+        tr._buffer = bytearray(b'data')
         m_write.side_effect = BlockingIOError()
         tr._write_ready()
-        m_write.assert_called_with(5, b'data')
+        m_write.assert_called_with(5, bytearray(b'data'))
         self.loop.assert_writer(5, tr._write_ready)
-        self.assertEqual([b'data'], tr._buffer)
+        self.assertEqual(bytearray(b'data'), tr._buffer)
 
     @mock.patch('os.write')
     def test__write_ready_empty(self, m_write):
         tr = self.write_pipe_transport()
         self.loop.add_writer(5, tr._write_ready)
-        tr._buffer = [b'da', b'ta']
+        tr._buffer = bytearray(b'data')
         m_write.return_value = 0
         tr._write_ready()
-        m_write.assert_called_with(5, b'data')
+        m_write.assert_called_with(5, bytearray(b'data'))
         self.loop.assert_writer(5, tr._write_ready)
-        self.assertEqual([b'data'], tr._buffer)
+        self.assertEqual(bytearray(b'data'), tr._buffer)
 
     @mock.patch('asyncio.log.logger.error')
     @mock.patch('os.write')
     def test__write_ready_err(self, m_write, m_logexc):
         tr = self.write_pipe_transport()
         self.loop.add_writer(5, tr._write_ready)
-        tr._buffer = [b'da', b'ta']
+        tr._buffer = bytearray(b'data')
         m_write.side_effect = err = OSError()
         tr._write_ready()
-        m_write.assert_called_with(5, b'data')
         self.assertFalse(self.loop.writers)
         self.assertFalse(self.loop.readers)
-        self.assertEqual([], tr._buffer)
+        self.assertEqual(bytearray(), tr._buffer)
         self.assertTrue(tr.is_closing())
         m_logexc.assert_called_with(
             test_utils.MockPattern(
@@ -673,13 +722,12 @@ class UnixWritePipeTransportTests(test_utils.TestCase):
         tr = self.write_pipe_transport()
         self.loop.add_writer(5, tr._write_ready)
         tr._closing = True
-        tr._buffer = [b'da', b'ta']
+        tr._buffer = bytearray(b'data')
         m_write.return_value = 4
         tr._write_ready()
-        m_write.assert_called_with(5, b'data')
         self.assertFalse(self.loop.writers)
         self.assertFalse(self.loop.readers)
-        self.assertEqual([], tr._buffer)
+        self.assertEqual(bytearray(), tr._buffer)
         self.protocol.connection_lost.assert_called_with(None)
         self.pipe.close.assert_called_with()
 
@@ -798,6 +846,7 @@ class ChildWatcherTestsMixin:
     ignore_warnings = mock.patch.object(log.logger, "warning")
 
     def setUp(self):
+        super().setUp()
         self.loop = self.new_test_loop()
         self.running = False
         self.zombies = {}
@@ -1396,7 +1445,9 @@ class ChildWatcherTestsMixin:
         with mock.patch.object(
                 old_loop, "remove_signal_handler") as m_remove_signal_handler:
 
-            self.watcher.attach_loop(None)
+            with self.assertWarnsRegex(
+                    RuntimeWarning, 'A loop is being detached'):
+                self.watcher.attach_loop(None)
 
             m_remove_signal_handler.assert_called_once_with(
                 signal.SIGCHLD)
@@ -1468,6 +1519,15 @@ class ChildWatcherTestsMixin:
                 if isinstance(self.watcher, asyncio.FastChildWatcher):
                     self.assertFalse(self.watcher._zombies)
 
+    @waitpid_mocks
+    def test_add_child_handler_with_no_loop_attached(self, m):
+        callback = mock.Mock()
+        with self.create_watcher() as watcher:
+            with self.assertRaisesRegex(
+                    RuntimeError,
+                    'the child watcher does not have a loop attached'):
+                watcher.add_child_handler(100, callback)
+
 
 class SafeChildWatcherTests (ChildWatcherTestsMixin, test_utils.TestCase):
     def create_watcher(self):
index 7fcf402..1afcae1 100644 (file)
@@ -31,6 +31,7 @@ class UpperProto(asyncio.Protocol):
 class ProactorTests(test_utils.TestCase):
 
     def setUp(self):
+        super().setUp()
         self.loop = asyncio.ProactorEventLoop()
         self.set_event_loop(self.loop)
 
index 8367afe..034245d 100644 (file)
@@ -178,37 +178,106 @@ class BinASCIITest(unittest.TestCase):
         self.assertEqual(binascii.unhexlify(self.type2test(t)), u)
 
     def test_qp(self):
-        binascii.a2b_qp(data=b"", header=False)  # Keyword arguments allowed
+        type2test = self.type2test
+        a2b_qp = binascii.a2b_qp
+        b2a_qp = binascii.b2a_qp
+
+        a2b_qp(data=b"", header=False)  # Keyword arguments allowed
 
         # A test for SF bug 534347 (segfaults without the proper fix)
         try:
-            binascii.a2b_qp(b"", **{1:1})
+            a2b_qp(b"", **{1:1})
         except TypeError:
             pass
         else:
             self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError")
 
-        self.assertEqual(binascii.a2b_qp(b"= "), b"= ")
-        self.assertEqual(binascii.a2b_qp(b"=="), b"=")
-        self.assertEqual(binascii.a2b_qp(b"=AX"), b"=AX")
-        self.assertRaises(TypeError, binascii.b2a_qp, foo="bar")
-        self.assertEqual(binascii.a2b_qp(b"=00\r\n=00"), b"\x00\r\n\x00")
-        self.assertEqual(
-            binascii.b2a_qp(b"\xff\r\n\xff\n\xff"),
-            b"=FF\r\n=FF\r\n=FF")
-        self.assertEqual(
-            binascii.b2a_qp(b"0"*75+b"\xff\r\n\xff\r\n\xff"),
-            b"0"*75+b"=\r\n=FF\r\n=FF\r\n=FF")
-
-        self.assertEqual(binascii.b2a_qp(b'\0\n'), b'=00\n')
-        self.assertEqual(binascii.b2a_qp(b'\0\n', quotetabs=True), b'=00\n')
-        self.assertEqual(binascii.b2a_qp(b'foo\tbar\t\n'), b'foo\tbar=09\n')
-        self.assertEqual(binascii.b2a_qp(b'foo\tbar\t\n', quotetabs=True),
-                         b'foo=09bar=09\n')
-
-        self.assertEqual(binascii.b2a_qp(b'.'), b'=2E')
-        self.assertEqual(binascii.b2a_qp(b'.\n'), b'=2E\n')
-        self.assertEqual(binascii.b2a_qp(b'a.\n'), b'a.\n')
+        self.assertEqual(a2b_qp(type2test(b"=")), b"")
+        self.assertEqual(a2b_qp(type2test(b"= ")), b"= ")
+        self.assertEqual(a2b_qp(type2test(b"==")), b"=")
+        self.assertEqual(a2b_qp(type2test(b"=\nAB")), b"AB")
+        self.assertEqual(a2b_qp(type2test(b"=\r\nAB")), b"AB")
+        self.assertEqual(a2b_qp(type2test(b"=\rAB")), b"")  # ?
+        self.assertEqual(a2b_qp(type2test(b"=\rAB\nCD")), b"CD")  # ?
+        self.assertEqual(a2b_qp(type2test(b"=AB")), b"\xab")
+        self.assertEqual(a2b_qp(type2test(b"=ab")), b"\xab")
+        self.assertEqual(a2b_qp(type2test(b"=AX")), b"=AX")
+        self.assertEqual(a2b_qp(type2test(b"=XA")), b"=XA")
+        self.assertEqual(a2b_qp(type2test(b"=AB")[:-1]), b"=A")
+
+        self.assertEqual(a2b_qp(type2test(b'_')), b'_')
+        self.assertEqual(a2b_qp(type2test(b'_'), header=True), b' ')
+
+        self.assertRaises(TypeError, b2a_qp, foo="bar")
+        self.assertEqual(a2b_qp(type2test(b"=00\r\n=00")), b"\x00\r\n\x00")
+        self.assertEqual(b2a_qp(type2test(b"\xff\r\n\xff\n\xff")),
+                         b"=FF\r\n=FF\r\n=FF")
+        self.assertEqual(b2a_qp(type2test(b"0"*75+b"\xff\r\n\xff\r\n\xff")),
+                         b"0"*75+b"=\r\n=FF\r\n=FF\r\n=FF")
+
+        self.assertEqual(b2a_qp(type2test(b'\x7f')), b'=7F')
+        self.assertEqual(b2a_qp(type2test(b'=')), b'=3D')
+
+        self.assertEqual(b2a_qp(type2test(b'_')), b'_')
+        self.assertEqual(b2a_qp(type2test(b'_'), header=True), b'=5F')
+        self.assertEqual(b2a_qp(type2test(b'x y'), header=True), b'x_y')
+        self.assertEqual(b2a_qp(type2test(b'x '), header=True), b'x=20')
+        self.assertEqual(b2a_qp(type2test(b'x y'), header=True, quotetabs=True),
+                         b'x=20y')
+        self.assertEqual(b2a_qp(type2test(b'x\ty'), header=True), b'x\ty')
+
+        self.assertEqual(b2a_qp(type2test(b' ')), b'=20')
+        self.assertEqual(b2a_qp(type2test(b'\t')), b'=09')
+        self.assertEqual(b2a_qp(type2test(b' x')), b' x')
+        self.assertEqual(b2a_qp(type2test(b'\tx')), b'\tx')
+        self.assertEqual(b2a_qp(type2test(b' x')[:-1]), b'=20')
+        self.assertEqual(b2a_qp(type2test(b'\tx')[:-1]), b'=09')
+        self.assertEqual(b2a_qp(type2test(b'\0')), b'=00')
+
+        self.assertEqual(b2a_qp(type2test(b'\0\n')), b'=00\n')
+        self.assertEqual(b2a_qp(type2test(b'\0\n'), quotetabs=True), b'=00\n')
+
+        self.assertEqual(b2a_qp(type2test(b'x y\tz')), b'x y\tz')
+        self.assertEqual(b2a_qp(type2test(b'x y\tz'), quotetabs=True),
+                         b'x=20y=09z')
+        self.assertEqual(b2a_qp(type2test(b'x y\tz'), istext=False),
+                         b'x y\tz')
+        self.assertEqual(b2a_qp(type2test(b'x \ny\t\n')),
+                         b'x=20\ny=09\n')
+        self.assertEqual(b2a_qp(type2test(b'x \ny\t\n'), quotetabs=True),
+                         b'x=20\ny=09\n')
+        self.assertEqual(b2a_qp(type2test(b'x \ny\t\n'), istext=False),
+                         b'x =0Ay\t=0A')
+        self.assertEqual(b2a_qp(type2test(b'x \ry\t\r')),
+                         b'x \ry\t\r')
+        self.assertEqual(b2a_qp(type2test(b'x \ry\t\r'), quotetabs=True),
+                         b'x=20\ry=09\r')
+        self.assertEqual(b2a_qp(type2test(b'x \ry\t\r'), istext=False),
+                         b'x =0Dy\t=0D')
+        self.assertEqual(b2a_qp(type2test(b'x \r\ny\t\r\n')),
+                         b'x=20\r\ny=09\r\n')
+        self.assertEqual(b2a_qp(type2test(b'x \r\ny\t\r\n'), quotetabs=True),
+                         b'x=20\r\ny=09\r\n')
+        self.assertEqual(b2a_qp(type2test(b'x \r\ny\t\r\n'), istext=False),
+                         b'x =0D=0Ay\t=0D=0A')
+
+        self.assertEqual(b2a_qp(type2test(b'x \r\n')[:-1]), b'x \r')
+        self.assertEqual(b2a_qp(type2test(b'x\t\r\n')[:-1]), b'x\t\r')
+        self.assertEqual(b2a_qp(type2test(b'x \r\n')[:-1], quotetabs=True),
+                         b'x=20\r')
+        self.assertEqual(b2a_qp(type2test(b'x\t\r\n')[:-1], quotetabs=True),
+                         b'x=09\r')
+        self.assertEqual(b2a_qp(type2test(b'x \r\n')[:-1], istext=False),
+                         b'x =0D')
+        self.assertEqual(b2a_qp(type2test(b'x\t\r\n')[:-1], istext=False),
+                         b'x\t=0D')
+
+        self.assertEqual(b2a_qp(type2test(b'.')), b'=2E')
+        self.assertEqual(b2a_qp(type2test(b'.\n')), b'=2E\n')
+        self.assertEqual(b2a_qp(type2test(b'.\r')), b'=2E\r')
+        self.assertEqual(b2a_qp(type2test(b'.\0')), b'=2E=00')
+        self.assertEqual(b2a_qp(type2test(b'a.\n')), b'a.\n')
+        self.assertEqual(b2a_qp(type2test(b'.a')[:-1]), b'=2E')
 
     def test_empty_string(self):
         # A test for SF bug #1022953.  Make sure SystemError is not raised.
index 8cc1b00..0b03340 100644 (file)
@@ -3,12 +3,15 @@
 import ast
 import builtins
 import collections
+import decimal
+import fractions
 import io
 import locale
 import os
 import pickle
 import platform
 import random
+import re
 import sys
 import traceback
 import types
@@ -1244,6 +1247,15 @@ class BuiltinTest(unittest.TestCase):
         self.assertEqual(round(5e15+2), 5e15+2)
         self.assertEqual(round(5e15+3), 5e15+3)
 
+    def test_bug_27936(self):
+        # Verify that ndigits=None means the same as passing in no argument
+        for x in [1234,
+                  1234.56,
+                  decimal.Decimal('1234.56'),
+                  fractions.Fraction(123456, 100)]:
+            self.assertEqual(round(x, None), round(x))
+            self.assertEqual(type(round(x, None)), type(round(x)))
+
     def test_setattr(self):
         setattr(sys, 'spam', 1)
         self.assertEqual(sys.spam, 1)
@@ -1436,21 +1448,14 @@ class BuiltinTest(unittest.TestCase):
 
         # --------------------------------------------------------------------
         # Issue #7994: object.__format__ with a non-empty format string is
-        #  deprecated
-        def test_deprecated_format_string(obj, fmt_str, should_raise):
-            if should_raise:
-                self.assertRaises(TypeError, format, obj, fmt_str)
-            else:
-                format(obj, fmt_str)
-
-        fmt_strs = ['', 's']
-
+        # disallowed
         class A:
             def __format__(self, fmt_str):
                 return format('', fmt_str)
 
-        for fmt_str in fmt_strs:
-            test_deprecated_format_string(A(), fmt_str, False)
+        self.assertEqual(format(A()), '')
+        self.assertEqual(format(A(), ''), '')
+        self.assertEqual(format(A(), 's'), '')
 
         class B:
             pass
@@ -1459,8 +1464,12 @@ class BuiltinTest(unittest.TestCase):
             pass
 
         for cls in [object, B, C]:
-            for fmt_str in fmt_strs:
-                test_deprecated_format_string(cls(), fmt_str, len(fmt_str) != 0)
+            obj = cls()
+            self.assertEqual(format(obj), str(obj))
+            self.assertEqual(format(obj, ''), str(obj))
+            with self.assertRaisesRegex(TypeError,
+                                        r'\b%s\b' % re.escape(cls.__name__)):
+                format(obj, 's')
         # --------------------------------------------------------------------
 
         # make sure we can take a subclass of str as a format spec
index 65c00d7..3288a5b 100644 (file)
@@ -1233,6 +1233,16 @@ class ByteArrayTest(BaseBytesTest, unittest.TestCase):
 
     test_exhausted_iterator = test.list_tests.CommonTest.test_exhausted_iterator
 
+    def test_iterator_length_hint(self):
+        # Issue 27443: __length_hint__ can return negative integer
+        ba = bytearray(b'ab')
+        it = iter(ba)
+        next(it)
+        ba.clear()
+        # Shouldn't raise an error
+        self.assertEqual(list(it), [])
+
+
 class AssortedBytesTest(unittest.TestCase):
     #
     # Test various combinations of bytes and bytearray
@@ -1249,6 +1259,15 @@ class AssortedBytesTest(unittest.TestCase):
             self.assertEqual(f(b"'"), '''b"'"''') # '''
             self.assertEqual(f(b"'\""), r"""b'\'"'""") # '
 
+    @check_bytes_warnings
+    def test_format(self):
+        for b in b'abc', bytearray(b'abc'):
+            self.assertEqual(format(b), str(b))
+            self.assertEqual(format(b, ''), str(b))
+            with self.assertRaisesRegex(TypeError,
+                                        r'\b%s\b' % re.escape(type(b).__name__)):
+                format(b, 's')
+
     def test_compare_bytes_to_bytearray(self):
         self.assertEqual(b"abc" == bytes(b"abc"), True)
         self.assertEqual(b"ab" != bytes(b"abc"), True)
index a1e4b8d..34f6478 100644 (file)
@@ -7,6 +7,7 @@ import os
 import pickle
 import glob
 import random
+import shutil
 import subprocess
 import sys
 from test.support import unlink
@@ -21,6 +22,16 @@ except ImportError:
 bz2 = support.import_module('bz2')
 from bz2 import BZ2File, BZ2Compressor, BZ2Decompressor
 
+has_cmdline_bunzip2 = None
+
+def ext_decompress(data):
+    global has_cmdline_bunzip2
+    if has_cmdline_bunzip2 is None:
+        has_cmdline_bunzip2 = bool(shutil.which('bunzip2'))
+    if has_cmdline_bunzip2:
+        return subprocess.check_output(['bunzip2'], input=data)
+    else:
+        return bz2.decompress(data)
 
 class BaseTest(unittest.TestCase):
     "Base for other testcases."
@@ -73,24 +84,6 @@ class BaseTest(unittest.TestCase):
         if os.path.isfile(self.filename):
             os.unlink(self.filename)
 
-    if sys.platform == "win32":
-        # bunzip2 isn't available to run on Windows.
-        def decompress(self, data):
-            return bz2.decompress(data)
-    else:
-        def decompress(self, data):
-            pop = subprocess.Popen("bunzip2", shell=True,
-                                   stdin=subprocess.PIPE,
-                                   stdout=subprocess.PIPE,
-                                   stderr=subprocess.STDOUT)
-            pop.stdin.write(data)
-            pop.stdin.close()
-            ret = pop.stdout.read()
-            pop.stdout.close()
-            if pop.wait() != 0:
-                ret = bz2.decompress(data)
-            return ret
-
 
 class BZ2FileTest(BaseTest):
     "Test the BZ2File class."
@@ -251,7 +244,7 @@ class BZ2FileTest(BaseTest):
             self.assertRaises(TypeError, bz2f.write)
             bz2f.write(self.TEXT)
         with open(self.filename, 'rb') as f:
-            self.assertEqual(self.decompress(f.read()), self.TEXT)
+            self.assertEqual(ext_decompress(f.read()), self.TEXT)
 
     def testWriteChunks10(self):
         with BZ2File(self.filename, "w") as bz2f:
@@ -263,7 +256,7 @@ class BZ2FileTest(BaseTest):
                 bz2f.write(str)
                 n += 1
         with open(self.filename, 'rb') as f:
-            self.assertEqual(self.decompress(f.read()), self.TEXT)
+            self.assertEqual(ext_decompress(f.read()), self.TEXT)
 
     def testWriteNonDefaultCompressLevel(self):
         expected = bz2.compress(self.TEXT, compresslevel=5)
@@ -280,7 +273,7 @@ class BZ2FileTest(BaseTest):
         # should raise an exception.
         self.assertRaises(ValueError, bz2f.writelines, ["a"])
         with open(self.filename, 'rb') as f:
-            self.assertEqual(self.decompress(f.read()), self.TEXT)
+            self.assertEqual(ext_decompress(f.read()), self.TEXT)
 
     def testWriteMethodsOnReadOnlyFile(self):
         with BZ2File(self.filename, "w") as bz2f:
@@ -298,7 +291,7 @@ class BZ2FileTest(BaseTest):
             self.assertRaises(TypeError, bz2f.write)
             bz2f.write(self.TEXT)
         with open(self.filename, 'rb') as f:
-            self.assertEqual(self.decompress(f.read()), self.TEXT * 2)
+            self.assertEqual(ext_decompress(f.read()), self.TEXT * 2)
 
     def testSeekForward(self):
         self.createTempFile()
@@ -594,7 +587,7 @@ class BZ2FileTest(BaseTest):
             with BZ2File(bio, "w") as bz2f:
                 self.assertRaises(TypeError, bz2f.write)
                 bz2f.write(self.TEXT)
-            self.assertEqual(self.decompress(bio.getvalue()), self.TEXT)
+            self.assertEqual(ext_decompress(bio.getvalue()), self.TEXT)
             self.assertFalse(bio.closed)
 
     def testSeekForwardBytesIO(self):
@@ -631,7 +624,7 @@ class BZ2CompressorTest(BaseTest):
         self.assertRaises(TypeError, bz2c.compress)
         data = bz2c.compress(self.TEXT)
         data += bz2c.flush()
-        self.assertEqual(self.decompress(data), self.TEXT)
+        self.assertEqual(ext_decompress(data), self.TEXT)
 
     def testCompressEmptyString(self):
         bz2c = BZ2Compressor()
@@ -650,7 +643,7 @@ class BZ2CompressorTest(BaseTest):
             data += bz2c.compress(str)
             n += 1
         data += bz2c.flush()
-        self.assertEqual(self.decompress(data), self.TEXT)
+        self.assertEqual(ext_decompress(data), self.TEXT)
 
     @bigmemtest(size=_4G + 100, memuse=2)
     def testCompress4G(self, size):
@@ -821,10 +814,16 @@ class BZ2DecompressorTest(BaseTest):
         out.append(bzd.decompress(self.DATA[300:]))
         self.assertEqual(b''.join(out), self.TEXT)
 
+    def test_failure(self):
+        bzd = BZ2Decompressor()
+        self.assertRaises(Exception, bzd.decompress, self.BAD_DATA * 30)
+        # Previously, a second call could crash due to internal inconsistency
+        self.assertRaises(Exception, bzd.decompress, self.BAD_DATA * 30)
+
 class CompressDecompressTest(BaseTest):
     def testCompress(self):
         data = bz2.compress(self.TEXT)
-        self.assertEqual(self.decompress(data), self.TEXT)
+        self.assertEqual(ext_decompress(data), self.TEXT)
 
     def testCompressEmptyString(self):
         text = bz2.compress(b'')
@@ -874,14 +873,14 @@ class OpenTest(BaseTest):
             with self.open(self.filename, mode) as f:
                 f.write(self.TEXT)
             with open(self.filename, "rb") as f:
-                file_data = self.decompress(f.read())
+                file_data = ext_decompress(f.read())
                 self.assertEqual(file_data, self.TEXT)
             with self.open(self.filename, "rb") as f:
                 self.assertEqual(f.read(), self.TEXT)
             with self.open(self.filename, "ab") as f:
                 f.write(self.TEXT)
             with open(self.filename, "rb") as f:
-                file_data = self.decompress(f.read())
+                file_data = ext_decompress(f.read())
                 self.assertEqual(file_data, self.TEXT * 2)
 
     def test_implicit_binary_modes(self):
@@ -892,14 +891,14 @@ class OpenTest(BaseTest):
             with self.open(self.filename, mode) as f:
                 f.write(self.TEXT)
             with open(self.filename, "rb") as f:
-                file_data = self.decompress(f.read())
+                file_data = ext_decompress(f.read())
                 self.assertEqual(file_data, self.TEXT)
             with self.open(self.filename, "r") as f:
                 self.assertEqual(f.read(), self.TEXT)
             with self.open(self.filename, "a") as f:
                 f.write(self.TEXT)
             with open(self.filename, "rb") as f:
-                file_data = self.decompress(f.read())
+                file_data = ext_decompress(f.read())
                 self.assertEqual(file_data, self.TEXT * 2)
 
     def test_text_modes(self):
@@ -911,14 +910,14 @@ class OpenTest(BaseTest):
             with self.open(self.filename, mode) as f:
                 f.write(text)
             with open(self.filename, "rb") as f:
-                file_data = self.decompress(f.read()).decode("ascii")
+                file_data = ext_decompress(f.read()).decode("ascii")
                 self.assertEqual(file_data, text_native_eol)
             with self.open(self.filename, "rt") as f:
                 self.assertEqual(f.read(), text)
             with self.open(self.filename, "at") as f:
                 f.write(text)
             with open(self.filename, "rb") as f:
-                file_data = self.decompress(f.read()).decode("ascii")
+                file_data = ext_decompress(f.read()).decode("ascii")
                 self.assertEqual(file_data, text_native_eol * 2)
 
     def test_x_mode(self):
@@ -959,7 +958,7 @@ class OpenTest(BaseTest):
         with self.open(self.filename, "wt", encoding="utf-16-le") as f:
             f.write(text)
         with open(self.filename, "rb") as f:
-            file_data = self.decompress(f.read()).decode("utf-16-le")
+            file_data = ext_decompress(f.read()).decode("utf-16-le")
             self.assertEqual(file_data, text_native_eol)
         with self.open(self.filename, "rt", encoding="utf-16-le") as f:
             self.assertEqual(f.read(), text)
index 80ed632..accf251 100644 (file)
@@ -409,8 +409,7 @@ class OutputTestCase(unittest.TestCase):
     def test_prmonth(self):
         with support.captured_stdout() as out:
             calendar.TextCalendar().prmonth(2004, 1)
-            output = out.getvalue().strip()
-            self.assertEqual(output, result_2004_01_text.strip())
+            self.assertEqual(out.getvalue(), result_2004_01_text)
 
     def test_pryear(self):
         with support.captured_stdout() as out:
@@ -502,6 +501,27 @@ class CalendarTestCase(unittest.TestCase):
         # see #15421
         list(calendar.Calendar().itermonthdates(datetime.MAXYEAR, 12))
 
+    def test_itermonthdays(self):
+        for firstweekday in range(7):
+            cal = calendar.Calendar(firstweekday)
+            # Test the extremes, see #28253 and #26650
+            for y, m in [(1, 1), (9999, 12)]:
+                days = list(cal.itermonthdays(y, m))
+                self.assertIn(len(days), (35, 42))
+        # Test a short month
+        cal = calendar.Calendar(firstweekday=3)
+        days = list(cal.itermonthdays(2001, 2))
+        self.assertEqual(days, list(range(1, 29)))
+
+    def test_itermonthdays2(self):
+        for firstweekday in range(7):
+            cal = calendar.Calendar(firstweekday)
+            # Test the extremes, see #28253 and #26650
+            for y, m in [(1, 1), (9999, 12)]:
+                days = list(cal.itermonthdays2(y, m))
+                self.assertEqual(days[0][1], firstweekday)
+                self.assertEqual(days[-1][1], (firstweekday - 1) % 7)
+
 
 class MonthCalendarTestCase(unittest.TestCase):
     def setUp(self):
index dce418b..3d2f769 100644 (file)
@@ -465,7 +465,7 @@ class CmdLineTest(unittest.TestCase):
         rc, out, err = assert_python_ok('-I', '-c',
             'from sys import flags as f; '
             'print(f.no_user_site, f.ignore_environment, f.isolated)',
-            # dummyvar to prevent extranous -E
+            # dummyvar to prevent extraneous -E
             dummyvar="")
         self.assertEqual(out.strip(), b'1 1 1')
         with test.support.temp_cwd() as tmpdir:
index b2be9b1..919f361 100644 (file)
@@ -10,6 +10,7 @@ import os
 import os.path
 import py_compile
 import subprocess
+import io
 
 import textwrap
 from test import support
@@ -426,8 +427,9 @@ class CmdLineTest(unittest.TestCase):
         # Exercise error reporting for various invalid package executions
         tests = (
             ('builtins', br'No code object available'),
-            ('builtins.x', br'Error while finding spec.*AttributeError'),
-            ('builtins.x.y', br'Error while finding spec.*'
+            ('builtins.x', br'Error while finding module specification.*'
+                br'AttributeError'),
+            ('builtins.x.y', br'Error while finding module specification.*'
                 br'ImportError.*No module named.*not a package'),
             ('os.path', br'loader.*cannot handle'),
             ('importlib', br'No module named.*'
@@ -450,7 +452,8 @@ class CmdLineTest(unittest.TestCase):
             with open('test_pkg/__init__.pyc', 'wb'):
                 pass
             err = self.check_dash_m_failure('test_pkg')
-            self.assertRegex(err, br'Error while finding spec.*'
+            self.assertRegex(err,
+                br'Error while finding module specification.*'
                 br'ImportError.*bad magic number')
             self.assertNotIn(b'is a package', err)
             self.assertNotIn(b'Traceback', err)
@@ -538,6 +541,38 @@ class CmdLineTest(unittest.TestCase):
             text = stderr.decode('ascii')
             self.assertEqual(text, "some text")
 
+    def test_syntaxerror_unindented_caret_position(self):
+        script = "1 + 1 = 2\n"
+        with support.temp_dir() as script_dir:
+            script_name = _make_test_script(script_dir, 'script', script)
+            exitcode, stdout, stderr = assert_python_failure(script_name)
+            text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
+            # Confirm that the caret is located under the first 1 character
+            self.assertIn("\n    1 + 1 = 2\n    ^", text)
+
+    def test_syntaxerror_indented_caret_position(self):
+        script = textwrap.dedent("""\
+            if True:
+                1 + 1 = 2
+            """)
+        with support.temp_dir() as script_dir:
+            script_name = _make_test_script(script_dir, 'script', script)
+            exitcode, stdout, stderr = assert_python_failure(script_name)
+            text = io.TextIOWrapper(io.BytesIO(stderr), 'ascii').read()
+            # Confirm that the caret is located under the first 1 character
+            self.assertIn("\n    1 + 1 = 2\n    ^", text)
+
+            # Try the same with a form feed at the start of the indented line
+            script = (
+                "if True:\n"
+                "\f    1 + 1 = 2\n"
+            )
+            script_name = _make_test_script(script_dir, "script", script)
+            exitcode, stdout, stderr = assert_python_failure(script_name)
+            text = io.TextIOWrapper(io.BytesIO(stderr), "ascii").read()
+            self.assertNotIn("\f", text)
+            self.assertIn("\n    1 + 1 = 2\n    ^", text)
+
 
 def test_main():
     support.run_unittest(CmdLineTest)
index 21b12a5..7975ea0 100644 (file)
@@ -102,6 +102,7 @@ consts: ('None',)
 
 """
 
+import sys
 import unittest
 import weakref
 from test.support import run_doctest, run_unittest, cpython_only
@@ -135,6 +136,57 @@ class CodeTest(unittest.TestCase):
         self.assertEqual(co.co_firstlineno, 15)
 
 
+def isinterned(s):
+    return s is sys.intern(('_' + s + '_')[1:-1])
+
+class CodeConstsTest(unittest.TestCase):
+
+    def find_const(self, consts, value):
+        for v in consts:
+            if v == value:
+                return v
+        self.assertIn(value, consts)  # raises an exception
+        self.fail('Should never be reached')
+
+    def assertIsInterned(self, s):
+        if not isinterned(s):
+            self.fail('String %r is not interned' % (s,))
+
+    def assertIsNotInterned(self, s):
+        if isinterned(s):
+            self.fail('String %r is interned' % (s,))
+
+    @cpython_only
+    def test_interned_string(self):
+        co = compile('res = "str_value"', '?', 'exec')
+        v = self.find_const(co.co_consts, 'str_value')
+        self.assertIsInterned(v)
+
+    @cpython_only
+    def test_interned_string_in_tuple(self):
+        co = compile('res = ("str_value",)', '?', 'exec')
+        v = self.find_const(co.co_consts, ('str_value',))
+        self.assertIsInterned(v[0])
+
+    @cpython_only
+    def test_interned_string_in_frozenset(self):
+        co = compile('res = a in {"str_value"}', '?', 'exec')
+        v = self.find_const(co.co_consts, frozenset(('str_value',)))
+        self.assertIsInterned(tuple(v)[0])
+
+    @cpython_only
+    def test_interned_string_default(self):
+        def f(a='str_value'):
+            return a
+        self.assertIsInterned(f())
+
+    @cpython_only
+    def test_interned_string_with_null(self):
+        co = compile(r'res = "str\0value!"', '?', 'exec')
+        v = self.find_const(co.co_consts, 'str\0value!')
+        self.assertIsNotInterned(v)
+
+
 class CodeWeakRefTest(unittest.TestCase):
 
     def test_basic(self):
@@ -163,7 +215,7 @@ class CodeWeakRefTest(unittest.TestCase):
 def test_main(verbose=None):
     from test import test_code
     run_doctest(test_code, verbose)
-    run_unittest(CodeTest, CodeWeakRefTest)
+    run_unittest(CodeTest, CodeConstsTest, CodeWeakRefTest)
 
 
 if __name__ == "__main__":
index 0479542..013ec64 100644 (file)
@@ -2501,6 +2501,26 @@ class RawUnicodeEscapeTest(unittest.TestCase):
         self.assertEqual(decode(br"\U00110000", "replace"), ("\ufffd", 10))
 
 
+class EscapeEncodeTest(unittest.TestCase):
+
+    def test_escape_encode(self):
+        tests = [
+            (b'', (b'', 0)),
+            (b'foobar', (b'foobar', 6)),
+            (b'spam\0eggs', (b'spam\\x00eggs', 9)),
+            (b'a\'b', (b"a\\'b", 3)),
+            (b'b\\c', (b'b\\\\c', 3)),
+            (b'c\nd', (b'c\\nd', 3)),
+            (b'd\re', (b'd\\re', 3)),
+            (b'f\x7fg', (b'f\\x7fg', 3)),
+        ]
+        for data, output in tests:
+            with self.subTest(data=data):
+                self.assertEqual(codecs.escape_encode(data), output)
+        self.assertRaises(TypeError, codecs.escape_encode, 'spam')
+        self.assertRaises(TypeError, codecs.escape_encode, bytearray(b'spam'))
+
+
 class SurrogateEscapeTest(unittest.TestCase):
 
     def test_utf8(self):
index 4c32e09..5238382 100644 (file)
@@ -114,7 +114,7 @@ class TestChainMap(unittest.TestCase):
         self.assertEqual(f['b'], 5)                                    # find first in chain
         self.assertEqual(f.parents['b'], 2)                            # look beyond maps[0]
 
-    def test_contructor(self):
+    def test_constructor(self):
         self.assertEqual(ChainMap().maps, [{}])                        # no-args --> one new dict
         self.assertEqual(ChainMap({1:2}).maps, [{1:2}])                # 1 arg --> list
 
index e0fdee3..824e843 100644 (file)
@@ -472,6 +472,13 @@ if 1:
         d = {f(): f(), f(): f()}
         self.assertEqual(d, {1: 2, 3: 4})
 
+    def test_compile_filename(self):
+        for filename in ('file.py', b'file.py',
+                         bytearray(b'file.py'), memoryview(b'file.py')):
+            code = compile('pass', filename, 'exec')
+            self.assertEqual(code.co_filename, 'file.py')
+        self.assertRaises(TypeError, compile, 'pass', list(b'file.py'), 'exec')
+
     @support.cpython_only
     def test_same_filename_used(self):
         s = """def f(): pass\ndef g(): pass"""
index 0ef9a7a..403ee3b 100644 (file)
@@ -326,6 +326,14 @@ class ComplexTest(unittest.TestCase):
         self.assertRaises(ValueError, complex, "1e1ej")
         self.assertRaises(ValueError, complex, "1e++1ej")
         self.assertRaises(ValueError, complex, ")1+2j(")
+        self.assertRaisesRegex(
+            TypeError,
+            "first argument must be a string or a number, not 'dict'",
+            complex, {1:2}, 1)
+        self.assertRaisesRegex(
+            TypeError,
+            "second argument must be a number, not 'dict'",
+            complex, 1, {1:2})
         # the following three are accepted by Python 2.6
         self.assertRaises(ValueError, complex, "1..1j")
         self.assertRaises(ValueError, complex, "1.11.1j")
index cdb9308..7513815 100644 (file)
@@ -4,7 +4,7 @@ import test.support
 test.support.import_module('_multiprocessing')
 # Skip tests if sem_open implementation is broken.
 test.support.import_module('multiprocessing.synchronize')
-# import threading after _multiprocessing to raise a more revelant error
+# import threading after _multiprocessing to raise a more relevant error
 # message: "No module named _multiprocessing". _multiprocessing is not compiled
 # without thread support.
 test.support.import_module('threading')
index 71a8f3f..864a1d0 100644 (file)
@@ -9,6 +9,7 @@ import warnings
 
 from test import support
 
+
 class SortedDict(collections.UserDict):
 
     def items(self):
@@ -64,6 +65,7 @@ class CfgParserTestCaseClass:
         cf.read_string(string)
         return cf
 
+
 class BasicTestCase(CfgParserTestCaseClass):
 
     def basic_test(self, cf):
@@ -828,6 +830,21 @@ boolean {0[0]} NO
         self.assertEqual(set(cf['section3'].keys()), set())
         self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
 
+    def test_invalid_multiline_value(self):
+        if self.allow_no_value:
+            self.skipTest('if no_value is allowed, ParsingError is not raised')
+
+        invalid = textwrap.dedent("""\
+            [DEFAULT]
+            test {0} test
+            invalid""".format(self.delimiters[0])
+        )
+        cf = self.newconfig()
+        with self.assertRaises(configparser.ParsingError):
+            cf.read_string(invalid)
+        self.assertEqual(cf.get('DEFAULT', 'test'), 'test')
+        self.assertEqual(cf['DEFAULT']['test'], 'test')
+
 
 class StrictTestCase(BasicTestCase, unittest.TestCase):
     config_class = configparser.RawConfigParser
@@ -981,14 +998,17 @@ class ConfigParserTestCaseLegacyInterpolation(ConfigParserTestCase):
         cf.set("sect", "option2", "foo%%bar")
         self.assertEqual(cf.get("sect", "option2"), "foo%%bar")
 
+
 class ConfigParserTestCaseNonStandardDelimiters(ConfigParserTestCase):
     delimiters = (':=', '$')
     comment_prefixes = ('//', '"')
     inline_comment_prefixes = ('//', '"')
 
+
 class ConfigParserTestCaseNonStandardDefaultSection(ConfigParserTestCase):
     default_section = 'general'
 
+
 class MultilineValuesTestCase(BasicTestCase, unittest.TestCase):
     config_class = configparser.ConfigParser
     wonderful_spam = ("I'm having spam spam spam spam "
@@ -1017,6 +1037,7 @@ class MultilineValuesTestCase(BasicTestCase, unittest.TestCase):
         self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'),
                          self.wonderful_spam.replace('\t\n', '\n'))
 
+
 class RawConfigParserTestCase(BasicTestCase, unittest.TestCase):
     config_class = configparser.RawConfigParser
 
@@ -1059,11 +1080,13 @@ class RawConfigParserTestCase(BasicTestCase, unittest.TestCase):
             cf.set('non-string', 1, 1)
             self.assertEqual(cf.get('non-string', 1), 1)
 
+
 class RawConfigParserTestCaseNonStandardDelimiters(RawConfigParserTestCase):
     delimiters = (':=', '$')
     comment_prefixes = ('//', '"')
     inline_comment_prefixes = ('//', '"')
 
+
 class RawConfigParserTestSambaConf(CfgParserTestCaseClass, unittest.TestCase):
     config_class = configparser.RawConfigParser
     comment_prefixes = ('#', ';', '----')
@@ -1258,6 +1281,7 @@ class ConfigParserTestCaseExtendedInterpolation(BasicTestCase, unittest.TestCase
 class ConfigParserTestCaseNoValue(ConfigParserTestCase):
     allow_no_value = True
 
+
 class ConfigParserTestCaseTrickyFile(CfgParserTestCaseClass, unittest.TestCase):
     config_class = configparser.ConfigParser
     delimiters = {'='}
index 30a6377..516403e 100644 (file)
@@ -762,6 +762,40 @@ class TestExitStack(unittest.TestCase):
         stack.push(cm)
         self.assertIs(stack._exit_callbacks[-1], cm)
 
+    def test_dont_reraise_RuntimeError(self):
+        # https://bugs.python.org/issue27122
+        class UniqueException(Exception): pass
+        class UniqueRuntimeError(RuntimeError): pass
+
+        @contextmanager
+        def second():
+            try:
+                yield 1
+            except Exception as exc:
+                raise UniqueException("new exception") from exc
+
+        @contextmanager
+        def first():
+            try:
+                yield 1
+            except Exception as exc:
+                raise exc
+
+        # The UniqueRuntimeError should be caught by second()'s exception
+        # handler which chain raised a new UniqueException.
+        with self.assertRaises(UniqueException) as err_ctx:
+            with ExitStack() as es_ctx:
+                es_ctx.enter_context(second())
+                es_ctx.enter_context(first())
+                raise UniqueRuntimeError("please no infinite loop.")
+
+        exc = err_ctx.exception
+        self.assertIsInstance(exc, UniqueException)
+        self.assertIsInstance(exc.__context__, UniqueRuntimeError)
+        self.assertIsNone(exc.__context__.__context__)
+        self.assertIsNone(exc.__context__.__cause__)
+        self.assertIs(exc.__cause__, exc.__context__)
+
 
 class TestRedirectStream:
 
index 4f725ae..4a327b5 100644 (file)
@@ -710,6 +710,21 @@ class CoroutineTest(unittest.TestCase):
             coro.close()
             self.assertEqual(CHK, 1)
 
+    def test_coro_wrapper_send_tuple(self):
+        async def foo():
+            return (10,)
+
+        result = run_async__await__(foo())
+        self.assertEqual(result, ([], (10,)))
+
+    def test_coro_wrapper_send_stop_iterator(self):
+        async def foo():
+            return StopIteration(10)
+
+        result = run_async__await__(foo())
+        self.assertIsInstance(result[1], StopIteration)
+        self.assertEqual(result[1].value, 10)
+
     def test_cr_await(self):
         @types.coroutine
         def a():
@@ -1423,7 +1438,7 @@ class CoroutineTest(unittest.TestCase):
 
         with warnings.catch_warnings():
             warnings.simplefilter("error")
-            # Test that __aiter__ that returns an asyncronous iterator
+            # Test that __aiter__ that returns an asynchronous iterator
             # directly does not throw any warnings.
             run_async(main())
         self.assertEqual(I, 111011)
@@ -1537,6 +1552,52 @@ class CoroutineTest(unittest.TestCase):
                 warnings.simplefilter("error")
                 run_async(foo())
 
+    def test_for_tuple(self):
+        class Done(Exception): pass
+
+        class AIter(tuple):
+            i = 0
+            def __aiter__(self):
+                return self
+            async def __anext__(self):
+                if self.i >= len(self):
+                    raise StopAsyncIteration
+                self.i += 1
+                return self[self.i - 1]
+
+        result = []
+        async def foo():
+            async for i in AIter([42]):
+                result.append(i)
+            raise Done
+
+        with self.assertRaises(Done):
+            foo().send(None)
+        self.assertEqual(result, [42])
+
+    def test_for_stop_iteration(self):
+        class Done(Exception): pass
+
+        class AIter(StopIteration):
+            i = 0
+            def __aiter__(self):
+                return self
+            async def __anext__(self):
+                if self.i:
+                    raise StopAsyncIteration
+                self.i += 1
+                return self.value
+
+        result = []
+        async def foo():
+            async for i in AIter(42):
+                result.append(i)
+            raise Done
+
+        with self.assertRaises(Done):
+            foo().send(None)
+        self.assertEqual(result, [42])
+
     def test_copy(self):
         async def func(): pass
         coro = func()
@@ -1565,6 +1626,15 @@ class CoroutineTest(unittest.TestCase):
         finally:
             aw.close()
 
+    def test_fatal_coro_warning(self):
+        # Issue 27811
+        async def func(): pass
+        with warnings.catch_warnings(), support.captured_stderr() as stderr:
+            warnings.filterwarnings("error")
+            func()
+            support.gc_collect()
+        self.assertIn("was never awaited", stderr.getvalue())
+
 
 class CoroAsyncIOCompatTest(unittest.TestCase):
 
index 8411cdb..14ba87f 100644 (file)
@@ -10,6 +10,7 @@
 #
 
 import os
+import string
 import sys
 import tempfile
 import unittest
@@ -26,6 +27,7 @@ requires('curses')
 curses = import_module('curses')
 import_module('curses.panel')
 import_module('curses.ascii')
+import_module('curses.textpad')
 
 def requires_curses_func(name):
     return unittest.skipUnless(hasattr(curses, name),
@@ -187,6 +189,11 @@ class TestCurses(unittest.TestCase):
         if hasattr(curses, 'enclose'):
             stdscr.enclose()
 
+        self.assertRaises(ValueError, stdscr.getstr, -400)
+        self.assertRaises(ValueError, stdscr.getstr, 2, 3, -400)
+        self.assertRaises(ValueError, stdscr.instr, -2)
+        self.assertRaises(ValueError, stdscr.instr, 2, 3, -2)
+
 
     def test_module_funcs(self):
         "Test module-level functions"
@@ -386,9 +393,18 @@ class TestCurses(unittest.TestCase):
         human_readable_signature = stdscr.addch.__doc__.split("\n")[0]
         self.assertIn("[y, x,]", human_readable_signature)
 
+    def test_issue13051(self):
+        stdscr = self.stdscr
+        box = curses.textpad.Textbox(stdscr, insert_mode=True)
+        lines, cols = stdscr.getmaxyx()
+        stdscr.resize(lines-2, cols-2)
+        # this may cause infinite recursion, leading to a RuntimeError
+        box._insert_printable_char('a')
+
 
 class MiscTests(unittest.TestCase):
 
+    @requires_curses_func('update_lines_cols')
     def test_update_lines_cols(self):
         # this doesn't actually test that LINES and COLS are updated,
         # because we can't automate changing them. See Issue #4254 for
@@ -399,6 +415,74 @@ class MiscTests(unittest.TestCase):
 
 class TestAscii(unittest.TestCase):
 
+    def test_controlnames(self):
+        for name in curses.ascii.controlnames:
+            self.assertTrue(hasattr(curses.ascii, name), name)
+
+    def test_ctypes(self):
+        def check(func, expected):
+            with self.subTest(ch=c, func=func):
+                self.assertEqual(func(i), expected)
+                self.assertEqual(func(c), expected)
+
+        for i in range(256):
+            c = chr(i)
+            b = bytes([i])
+            check(curses.ascii.isalnum, b.isalnum())
+            check(curses.ascii.isalpha, b.isalpha())
+            check(curses.ascii.isdigit, b.isdigit())
+            check(curses.ascii.islower, b.islower())
+            check(curses.ascii.isspace, b.isspace())
+            check(curses.ascii.isupper, b.isupper())
+
+            check(curses.ascii.isascii, i < 128)
+            check(curses.ascii.ismeta, i >= 128)
+            check(curses.ascii.isctrl, i < 32)
+            check(curses.ascii.iscntrl, i < 32 or i == 127)
+            check(curses.ascii.isblank, c in ' \t')
+            check(curses.ascii.isgraph, 32 < i <= 126)
+            check(curses.ascii.isprint, 32 <= i <= 126)
+            check(curses.ascii.ispunct, c in string.punctuation)
+            check(curses.ascii.isxdigit, c in string.hexdigits)
+
+        for i in (-2, -1, 256, sys.maxunicode, sys.maxunicode+1):
+            self.assertFalse(curses.ascii.isalnum(i))
+            self.assertFalse(curses.ascii.isalpha(i))
+            self.assertFalse(curses.ascii.isdigit(i))
+            self.assertFalse(curses.ascii.islower(i))
+            self.assertFalse(curses.ascii.isspace(i))
+            self.assertFalse(curses.ascii.isupper(i))
+
+            self.assertFalse(curses.ascii.isascii(i))
+            self.assertFalse(curses.ascii.isctrl(i))
+            self.assertFalse(curses.ascii.iscntrl(i))
+            self.assertFalse(curses.ascii.isblank(i))
+            self.assertFalse(curses.ascii.isgraph(i))
+            self.assertFalse(curses.ascii.isprint(i))
+            self.assertFalse(curses.ascii.ispunct(i))
+            self.assertFalse(curses.ascii.isxdigit(i))
+
+        self.assertFalse(curses.ascii.ismeta(-1))
+
+    def test_ascii(self):
+        ascii = curses.ascii.ascii
+        self.assertEqual(ascii('\xc1'), 'A')
+        self.assertEqual(ascii('A'), 'A')
+        self.assertEqual(ascii(ord('\xc1')), ord('A'))
+
+    def test_ctrl(self):
+        ctrl = curses.ascii.ctrl
+        self.assertEqual(ctrl('J'), '\n')
+        self.assertEqual(ctrl('\n'), '\n')
+        self.assertEqual(ctrl('@'), '\0')
+        self.assertEqual(ctrl(ord('J')), ord('\n'))
+
+    def test_alt(self):
+        alt = curses.ascii.alt
+        self.assertEqual(alt('\n'), '\x8a')
+        self.assertEqual(alt('A'), '\xc1')
+        self.assertEqual(alt(ord('A')), 0xc1)
+
     def test_unctrl(self):
         unctrl = curses.ascii.unctrl
         self.assertEqual(unctrl('a'), 'a')
@@ -408,9 +492,13 @@ class TestAscii(unittest.TestCase):
         self.assertEqual(unctrl('\x7f'), '^?')
         self.assertEqual(unctrl('\n'), '^J')
         self.assertEqual(unctrl('\0'), '^@')
+        self.assertEqual(unctrl(ord('A')), 'A')
+        self.assertEqual(unctrl(ord('\n')), '^J')
         # Meta-bit characters
         self.assertEqual(unctrl('\x8a'), '!^J')
         self.assertEqual(unctrl('\xc1'), '!A')
+        self.assertEqual(unctrl(ord('\x8a')), '!^J')
+        self.assertEqual(unctrl(ord('\xc1')), '!A')
 
 
 if __name__ == '__main__':
index ff63c88..235ab11 100644 (file)
@@ -5,6 +5,7 @@
 import io
 import operator
 import os
+import stat
 import unittest
 import dbm.dumb as dumbdbm
 from test import support
@@ -234,6 +235,21 @@ class DumbDBMTestCase(unittest.TestCase):
                     pass
             self.assertEqual(stdout.getvalue(), '')
 
+    @unittest.skipUnless(hasattr(os, 'chmod'), 'test needs os.chmod()')
+    def test_readonly_files(self):
+        with support.temp_dir() as dir:
+            fname = os.path.join(dir, 'db')
+            with dumbdbm.open(fname, 'n') as f:
+                self.assertEqual(list(f.keys()), [])
+                for key in self._dict:
+                    f[key] = self._dict[key]
+            os.chmod(fname + ".dir", stat.S_IRUSR)
+            os.chmod(fname + ".dat", stat.S_IRUSR)
+            os.chmod(dir, stat.S_IRUSR|stat.S_IXUSR)
+            with dumbdbm.open(fname, 'r') as f:
+                self.assertEqual(sorted(f.keys()), sorted(self._dict))
+                f.close()  # don't write
+
     def tearDown(self):
         _delete_files()
 
index c0d21b1..1aa0bf8 100644 (file)
@@ -2491,7 +2491,8 @@ class PythonAPItests(unittest.TestCase):
         Decimal = self.decimal.Decimal
 
         class MyDecimal(Decimal):
-            pass
+            def __init__(self, _):
+                self.x = 'y'
 
         self.assertTrue(issubclass(MyDecimal, Decimal))
 
@@ -2499,6 +2500,8 @@ class PythonAPItests(unittest.TestCase):
         self.assertEqual(type(r), MyDecimal)
         self.assertEqual(str(r),
                 '0.1000000000000000055511151231257827021181583404541015625')
+        self.assertEqual(r.x, 'y')
+
         bigint = 12345678901234567890123456789
         self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
         self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
@@ -5395,6 +5398,34 @@ class CWhitebox(unittest.TestCase):
             y = Decimal(10**(9*25)).__sizeof__()
             self.assertEqual(y, x+4)
 
+    def test_internal_use_of_overridden_methods(self):
+        Decimal = C.Decimal
+
+        # Unsound subtyping
+        class X(float):
+            def as_integer_ratio(self):
+                return 1
+            def __abs__(self):
+                return self
+
+        class Y(float):
+            def __abs__(self):
+                return [1]*200
+
+        class I(int):
+            def bit_length(self):
+                return [1]*200
+
+        class Z(float):
+            def as_integer_ratio(self):
+                return (I(1), I(1))
+            def __abs__(self):
+                return self
+
+        for cls in X, Y, Z:
+            self.assertEqual(Decimal.from_float(cls(101.1)),
+                             Decimal.from_float(101.1))
+
 @requires_docstrings
 @unittest.skipUnless(C, "test requires C version")
 class SignatureTest(unittest.TestCase):
index a90bc2b..7218349 100644 (file)
@@ -175,7 +175,7 @@ class TestDefaultDict(unittest.TestCase):
     def test_callable_arg(self):
         self.assertRaises(TypeError, defaultdict, {})
 
-    def test_pickleing(self):
+    def test_pickling(self):
         d = defaultdict(int)
         d[1]
         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
index f525429..18e1df0 100644 (file)
@@ -494,7 +494,7 @@ class TestBasic(unittest.TestCase):
         d.clear()
         self.assertEqual(len(d), 0)
         self.assertEqual(list(d), [])
-        d.clear()               # clear an emtpy deque
+        d.clear()               # clear an empty deque
         self.assertEqual(list(d), [])
 
     def test_remove(self):
index a130cec..eda6fc1 100644 (file)
@@ -7,6 +7,7 @@ import pickle
 import sys
 import types
 import unittest
+import warnings
 import weakref
 
 from copy import deepcopy
@@ -876,7 +877,7 @@ class ClassPropertiesAndMethods(unittest.TestCase):
         self.assertEqual(Frag().__int__(), 42)
         self.assertEqual(int(Frag()), 42)
 
-    def test_diamond_inheritence(self):
+    def test_diamond_inheritance(self):
         # Testing multiple inheritance special cases...
         class A(object):
             def spam(self): return "A"
@@ -1661,6 +1662,77 @@ order (MRO) for bases """
         self.assertEqual(b.foo, 3)
         self.assertEqual(b.__class__, D)
 
+    @unittest.expectedFailure
+    def test_bad_new(self):
+        self.assertRaises(TypeError, object.__new__)
+        self.assertRaises(TypeError, object.__new__, '')
+        self.assertRaises(TypeError, list.__new__, object)
+        self.assertRaises(TypeError, object.__new__, list)
+        class C(object):
+            __new__ = list.__new__
+        self.assertRaises(TypeError, C)
+        class C(list):
+            __new__ = object.__new__
+        self.assertRaises(TypeError, C)
+
+    def test_object_new(self):
+        class A(object):
+            pass
+        object.__new__(A)
+        self.assertRaises(TypeError, object.__new__, A, 5)
+        object.__init__(A())
+        self.assertRaises(TypeError, object.__init__, A(), 5)
+
+        class A(object):
+            def __init__(self, foo):
+                self.foo = foo
+        object.__new__(A)
+        object.__new__(A, 5)
+        object.__init__(A(3))
+        self.assertRaises(TypeError, object.__init__, A(3), 5)
+
+        class A(object):
+            def __new__(cls, foo):
+                return object.__new__(cls)
+        object.__new__(A)
+        self.assertRaises(TypeError, object.__new__, A, 5)
+        object.__init__(A(3))
+        object.__init__(A(3), 5)
+
+        class A(object):
+            def __new__(cls, foo):
+                return object.__new__(cls)
+            def __init__(self, foo):
+                self.foo = foo
+        object.__new__(A)
+        self.assertRaises(TypeError, object.__new__, A, 5)
+        object.__init__(A(3))
+        self.assertRaises(TypeError, object.__init__, A(3), 5)
+
+    @unittest.expectedFailure
+    def test_restored_object_new(self):
+        class A(object):
+            def __new__(cls, *args, **kwargs):
+                raise AssertionError
+        self.assertRaises(AssertionError, A)
+        class B(A):
+            __new__ = object.__new__
+            def __init__(self, foo):
+                self.foo = foo
+        with warnings.catch_warnings():
+            warnings.simplefilter('error', DeprecationWarning)
+            b = B(3)
+        self.assertEqual(b.foo, 3)
+        self.assertEqual(b.__class__, B)
+        del B.__new__
+        self.assertRaises(AssertionError, B)
+        del A.__new__
+        with warnings.catch_warnings():
+            warnings.simplefilter('error', DeprecationWarning)
+            b = B(3)
+        self.assertEqual(b.foo, 3)
+        self.assertEqual(b.__class__, B)
+
     def test_altmro(self):
         # Testing mro() and overriding it...
         class A(object):
@@ -3522,6 +3594,24 @@ order (MRO) for bases """
         self.assertIsInstance(d, D)
         self.assertEqual(d.foo, 1)
 
+        class C(object):
+            @staticmethod
+            def __new__(*args):
+                return args
+        self.assertEqual(C(1, 2), (C, 1, 2))
+        class D(C):
+            pass
+        self.assertEqual(D(1, 2), (D, 1, 2))
+
+        class C(object):
+            @classmethod
+            def __new__(*args):
+                return args
+        self.assertEqual(C(1, 2), (C, C, 1, 2))
+        class D(C):
+            pass
+        self.assertEqual(D(1, 2), (D, D, 1, 2))
+
     def test_imul_bug(self):
         # Testing for __imul__ problems...
         # SF bug 544647
index 6d68e76..b85d333 100644 (file)
@@ -836,6 +836,24 @@ class DictTest(unittest.TestCase):
             pass
         self._tracked(MyDict())
 
+    @support.cpython_only
+    def test_splittable_setattr_after_pop(self):
+        """setattr must not convert combined table into split table"""
+        # Issue 28147
+        import _testcapi
+
+        class C:
+            pass
+        a = C()
+        a.a = 2
+        self.assertTrue(_testcapi.dict_hassplittable(a.__dict__))
+        # dict.popitem() convert it to combined table
+        a.__dict__.popitem()
+        self.assertFalse(_testcapi.dict_hassplittable(a.__dict__))
+        # But C should not convert a.__dict__ to split table again.
+        a.a = 3
+        self.assertFalse(_testcapi.dict_hassplittable(a.__dict__))
+
     def test_iterator_pickling(self):
         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
             data = {1:"a", 2:"b", 3:"c"}
index ab23ca1..0c99652 100644 (file)
@@ -209,6 +209,32 @@ class DictSetTest(unittest.TestCase):
         self.assertRaises(TypeError, copy.copy, d.values())
         self.assertRaises(TypeError, copy.copy, d.items())
 
+    def test_compare_error(self):
+        class Exc(Exception):
+            pass
+
+        class BadEq:
+            def __hash__(self):
+                return 7
+            def __eq__(self, other):
+                raise Exc
+
+        k1, k2 = BadEq(), BadEq()
+        v1, v2 = BadEq(), BadEq()
+        d = {k1: v1}
+
+        self.assertIn(k1, d)
+        self.assertIn(k1, d.keys())
+        self.assertIn(v1, d.values())
+        self.assertIn((k1, v1), d.items())
+
+        self.assertRaises(Exc, d.__contains__, k2)
+        self.assertRaises(Exc, d.keys().__contains__, k2)
+        self.assertRaises(Exc, d.items().__contains__, (k2, v1))
+        self.assertRaises(Exc, d.items().__contains__, (k1, v2))
+        with self.assertRaises(Exc):
+            v2 in d.values()
+
     def test_pickle(self):
         d = {1: 10, "a": "ABC"}
         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
index 29426a3..33163b9 100644 (file)
@@ -2719,12 +2719,6 @@ output into something we can doctest against:
     >>> def normalize(s):
     ...     return '\n'.join(s.decode().splitlines())
 
-Note: we also pass TERM='' to all the assert_python calls to avoid a bug
-in the readline library that is triggered in these tests because we are
-running them in a new python process.  See:
-
-  http://lists.gnu.org/archive/html/bug-readline/2013-06/msg00000.html
-
 With those preliminaries out of the way, we'll start with a file with two
 simple tests and no errors.  We'll run both the unadorned doctest command, and
 the verbose version, and then check the output:
@@ -2741,9 +2735,9 @@ the verbose version, and then check the output:
     ...         _ = f.write('\n')
     ...         _ = f.write('And that is it.\n')
     ...     rc1, out1, err1 = script_helper.assert_python_ok(
-    ...             '-m', 'doctest', fn, TERM='')
+    ...             '-m', 'doctest', fn)
     ...     rc2, out2, err2 = script_helper.assert_python_ok(
-    ...             '-m', 'doctest', '-v', fn, TERM='')
+    ...             '-m', 'doctest', '-v', fn)
 
 With no arguments and passing tests, we should get no output:
 
@@ -2806,17 +2800,17 @@ text files).
     ...         _ = f.write('   \"\"\"\n')
     ...     import shutil
     ...     rc1, out1, err1 = script_helper.assert_python_failure(
-    ...             '-m', 'doctest', fn, fn2, TERM='')
+    ...             '-m', 'doctest', fn, fn2)
     ...     rc2, out2, err2 = script_helper.assert_python_ok(
-    ...             '-m', 'doctest', '-o', 'ELLIPSIS', fn, TERM='')
+    ...             '-m', 'doctest', '-o', 'ELLIPSIS', fn)
     ...     rc3, out3, err3 = script_helper.assert_python_ok(
     ...             '-m', 'doctest', '-o', 'ELLIPSIS',
-    ...             '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
+    ...             '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
     ...     rc4, out4, err4 = script_helper.assert_python_failure(
-    ...             '-m', 'doctest', '-f', fn, fn2, TERM='')
+    ...             '-m', 'doctest', '-f', fn, fn2)
     ...     rc5, out5, err5 = script_helper.assert_python_ok(
     ...             '-m', 'doctest', '-v', '-o', 'ELLIPSIS',
-    ...             '-o', 'NORMALIZE_WHITESPACE', fn, fn2, TERM='')
+    ...             '-o', 'NORMALIZE_WHITESPACE', fn, fn2)
 
 Our first test run will show the errors from the first file (doctest stops if a
 file has errors).  Note that doctest test-run error output appears on stdout,
@@ -2922,7 +2916,7 @@ We should also check some typical error cases.
 Invalid file name:
 
     >>> rc, out, err = script_helper.assert_python_failure(
-    ...         '-m', 'doctest', 'nosuchfile', TERM='')
+    ...         '-m', 'doctest', 'nosuchfile')
     >>> rc, out
     (1, b'')
     >>> print(normalize(err))                    # doctest: +ELLIPSIS
@@ -2933,7 +2927,7 @@ Invalid file name:
 Invalid doctest option:
 
     >>> rc, out, err = script_helper.assert_python_failure(
-    ...         '-m', 'doctest', '-o', 'nosuchoption', TERM='')
+    ...         '-m', 'doctest', '-o', 'nosuchoption')
     >>> rc, out
     (2, b'')
     >>> print(normalize(err))                    # doctest: +ELLIPSIS
index e6ca961..0090333 100644 (file)
@@ -3,12 +3,8 @@ import http.client
 import sys
 from test import support
 threading = support.import_module('threading')
-import time
-import socket
 import unittest
 
-PORT = None
-
 def make_request_and_skipIf(condition, reason):
     # If we skip the test, we have to make a request because
     # the server created in setUp blocks expecting one to come in.
@@ -23,13 +19,10 @@ def make_request_and_skipIf(condition, reason):
     return decorator
 
 
-def server(evt, numrequests):
+def make_server():
     serv = DocXMLRPCServer(("localhost", 0), logRequests=False)
 
     try:
-        global PORT
-        PORT = serv.socket.getsockname()[1]
-
         # Add some documentation
         serv.set_server_title("DocXMLRPCServer Test Documentation")
         serv.set_server_name("DocXMLRPCServer Test Docs")
@@ -66,43 +59,31 @@ def server(evt, numrequests):
         serv.register_function(lambda x, y: x-y)
         serv.register_function(annotation)
         serv.register_instance(ClassWithAnnotation())
-
-        while numrequests > 0:
-            serv.handle_request()
-            numrequests -= 1
-    except socket.timeout:
-        pass
-    finally:
+        return serv
+    except:
         serv.server_close()
-        PORT = None
-        evt.set()
+        raise
 
 class DocXMLRPCHTTPGETServer(unittest.TestCase):
     def setUp(self):
-        self._threads = support.threading_setup()
         # Enable server feedback
         DocXMLRPCServer._send_traceback_header = True
 
-        self.evt = threading.Event()
-        threading.Thread(target=server, args=(self.evt, 1)).start()
-
-        # wait for port to be assigned
-        deadline = time.monotonic() + 10.0
-        while PORT is None:
-            time.sleep(0.010)
-            if time.monotonic() > deadline:
-                break
+        self.serv = make_server()
+        self.thread = threading.Thread(target=self.serv.serve_forever)
+        self.thread.start()
 
+        PORT = self.serv.server_address[1]
         self.client = http.client.HTTPConnection("localhost:%d" % PORT)
 
     def tearDown(self):
         self.client.close()
 
-        self.evt.wait()
-
         # Disable server feedback
         DocXMLRPCServer._send_traceback_header = False
-        support.threading_cleanup(*self._threads)
+        self.serv.shutdown()
+        self.thread.join()
+        self.serv.server_close()
 
     def test_valid_get_response(self):
         self.client.request("GET", "/")
@@ -164,7 +145,7 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase):
     @make_request_and_skipIf(sys.flags.optimize >= 2,
                      "Docstrings are omitted with -O2 and above")
     def test_system_methods(self):
-        """Test the precense of three consecutive system.* methods.
+        """Test the presence of three consecutive system.* methods.
 
         This also tests their use of parameter type recognition and the
         systems related to that process.
index a6a2856..bb4bfe7 100644 (file)
@@ -1,19 +1,13 @@
-"""Generic thread tests.
-
-Meant to be used by dummy_thread and thread.  To allow for different modules
-to be used, test_main() can be called with the module to use as the thread
-implementation as its sole argument.
-
-"""
 import _dummy_thread as _thread
 import time
 import queue
 import random
 import unittest
 from test import support
+from unittest import mock
+
+DELAY = 0
 
-DELAY = 0 # Set > 0 when testing a module other than _dummy_thread, such as
-          # the '_thread' module.
 
 class LockTests(unittest.TestCase):
     """Test lock objects."""
@@ -34,6 +28,12 @@ class LockTests(unittest.TestCase):
         self.assertFalse(self.lock.locked(),
                         "Lock object did not release properly.")
 
+    def test_LockType_context_manager(self):
+        with _thread.LockType():
+            pass
+        self.assertFalse(self.lock.locked(),
+                         "Acquired Lock was not released")
+
     def test_improper_release(self):
         #Make sure release of an unlocked thread raises RuntimeError
         self.assertRaises(RuntimeError, self.lock.release)
@@ -83,39 +83,72 @@ class LockTests(unittest.TestCase):
         self.assertGreaterEqual(end_time - start_time, DELAY,
                         "Blocking by unconditional acquiring failed.")
 
+    @mock.patch('time.sleep')
+    def test_acquire_timeout(self, mock_sleep):
+        """Test invoking acquire() with a positive timeout when the lock is
+        already acquired. Ensure that time.sleep() is invoked with the given
+        timeout and that False is returned."""
+
+        self.lock.acquire()
+        retval = self.lock.acquire(waitflag=0, timeout=1)
+        self.assertTrue(mock_sleep.called)
+        mock_sleep.assert_called_once_with(1)
+        self.assertEqual(retval, False)
+
+    def test_lock_representation(self):
+        self.lock.acquire()
+        self.assertIn("locked", repr(self.lock))
+        self.lock.release()
+        self.assertIn("unlocked", repr(self.lock))
+
+
 class MiscTests(unittest.TestCase):
     """Miscellaneous tests."""
 
     def test_exit(self):
-        #Make sure _thread.exit() raises SystemExit
         self.assertRaises(SystemExit, _thread.exit)
 
     def test_ident(self):
-        #Test sanity of _thread.get_ident()
         self.assertIsInstance(_thread.get_ident(), int,
                               "_thread.get_ident() returned a non-integer")
         self.assertNotEqual(_thread.get_ident(), 0,
                         "_thread.get_ident() returned 0")
 
     def test_LockType(self):
-        #Make sure _thread.LockType is the same type as _thread.allocate_locke()
         self.assertIsInstance(_thread.allocate_lock(), _thread.LockType,
                               "_thread.LockType is not an instance of what "
                               "is returned by _thread.allocate_lock()")
 
+    def test_set_sentinel(self):
+        self.assertIsInstance(_thread._set_sentinel(), _thread.LockType,
+                              "_thread._set_sentinel() did not return a "
+                              "LockType instance.")
+
     def test_interrupt_main(self):
         #Calling start_new_thread with a function that executes interrupt_main
         # should raise KeyboardInterrupt upon completion.
         def call_interrupt():
             _thread.interrupt_main()
-        self.assertRaises(KeyboardInterrupt, _thread.start_new_thread,
-                              call_interrupt, tuple())
+
+        self.assertRaises(KeyboardInterrupt,
+                          _thread.start_new_thread,
+                          call_interrupt,
+                          tuple())
 
     def test_interrupt_in_main(self):
-        # Make sure that if interrupt_main is called in main threat that
-        # KeyboardInterrupt is raised instantly.
         self.assertRaises(KeyboardInterrupt, _thread.interrupt_main)
 
+    def test_stack_size_None(self):
+        retval = _thread.stack_size(None)
+        self.assertEqual(retval, 0)
+
+    def test_stack_size_not_None(self):
+        with self.assertRaises(_thread.error) as cm:
+            _thread.stack_size("")
+        self.assertEqual(cm.exception.args[0],
+                         "setting thread stack size not supported")
+
+
 class ThreadTests(unittest.TestCase):
     """Test thread creation."""
 
@@ -129,31 +162,43 @@ class ThreadTests(unittest.TestCase):
         _thread.start_new_thread(arg_tester, (testing_queue, True, True))
         result = testing_queue.get()
         self.assertTrue(result[0] and result[1],
-                        "Argument passing for thread creation using tuple failed")
-        _thread.start_new_thread(arg_tester, tuple(), {'queue':testing_queue,
-                                                       'arg1':True, 'arg2':True})
+                        "Argument passing for thread creation "
+                        "using tuple failed")
+
+        _thread.start_new_thread(
+                arg_tester,
+                tuple(),
+                {'queue':testing_queue, 'arg1':True, 'arg2':True})
+
         result = testing_queue.get()
         self.assertTrue(result[0] and result[1],
-                        "Argument passing for thread creation using kwargs failed")
-        _thread.start_new_thread(arg_tester, (testing_queue, True), {'arg2':True})
+                        "Argument passing for thread creation "
+                        "using kwargs failed")
+
+        _thread.start_new_thread(
+                arg_tester,
+                (testing_queue, True),
+                {'arg2':True})
+
         result = testing_queue.get()
         self.assertTrue(result[0] and result[1],
                         "Argument passing for thread creation using both tuple"
                         " and kwargs failed")
 
-    def test_multi_creation(self):
-        #Make sure multiple threads can be created.
+    def test_multi_thread_creation(self):
         def queue_mark(queue, delay):
-            """Wait for ``delay`` seconds and then put something into ``queue``"""
             time.sleep(delay)
             queue.put(_thread.get_ident())
 
         thread_count = 5
         testing_queue = queue.Queue(thread_count)
+
         if support.verbose:
             print()
-            print("*** Testing multiple thread creation "\
-            "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count))
+            print("*** Testing multiple thread creation "
+                  "(will take approx. %s to %s sec.) ***" % (
+                    DELAY, thread_count))
+
         for count in range(thread_count):
             if DELAY:
                 local_delay = round(random.random(), 1)
@@ -165,18 +210,47 @@ class ThreadTests(unittest.TestCase):
         if support.verbose:
             print('done')
         self.assertEqual(testing_queue.qsize(), thread_count,
-                        "Not all %s threads executed properly after %s sec." %
-                        (thread_count, DELAY))
-
-def test_main(imported_module=None):
-    global _thread, DELAY
-    if imported_module:
-        _thread = imported_module
-        DELAY = 2
-    if support.verbose:
-        print()
-        print("*** Using %s as _thread module ***" % _thread)
-    support.run_unittest(LockTests, MiscTests, ThreadTests)
-
-if __name__ == '__main__':
-    test_main()
+                         "Not all %s threads executed properly "
+                         "after %s sec." % (thread_count, DELAY))
+
+    def test_args_not_tuple(self):
+        """
+        Test invoking start_new_thread() with a non-tuple value for "args".
+        Expect TypeError with a meaningful error message to be raised.
+        """
+        with self.assertRaises(TypeError) as cm:
+            _thread.start_new_thread(mock.Mock(), [])
+        self.assertEqual(cm.exception.args[0], "2nd arg must be a tuple")
+
+    def test_kwargs_not_dict(self):
+        """
+        Test invoking start_new_thread() with a non-dict value for "kwargs".
+        Expect TypeError with a meaningful error message to be raised.
+        """
+        with self.assertRaises(TypeError) as cm:
+            _thread.start_new_thread(mock.Mock(), tuple(), kwargs=[])
+        self.assertEqual(cm.exception.args[0], "3rd arg must be a dict")
+
+    def test_SystemExit(self):
+        """
+        Test invoking start_new_thread() with a function that raises
+        SystemExit.
+        The exception should be discarded.
+        """
+        func = mock.Mock(side_effect=SystemExit())
+        try:
+            _thread.start_new_thread(func, tuple())
+        except SystemExit:
+            self.fail("start_new_thread raised SystemExit.")
+
+    @mock.patch('traceback.print_exc')
+    def test_RaiseException(self, mock_print_exc):
+        """
+        Test invoking start_new_thread() with a function that raises exception.
+
+        The exception should be discarded and the traceback should be printed
+        via traceback.print_exc()
+        """
+        func = mock.Mock(side_effect=Exception)
+        _thread.start_new_thread(func, tuple())
+        self.assertTrue(mock_print_exc.called)
index d2f7d31..d4a03ee 100644 (file)
@@ -121,6 +121,10 @@ def parameterize(cls):
     Note: if and only if the generated test name is a valid identifier can it
     be used to select the test individually from the unittest command line.
 
+    The values in the params dict can be a single value, a tuple, or a
+    dict.  If a single value of a tuple, it is passed to the test function
+    as positional arguments.  If a dict, it is a passed via **kw.
+
     """
     paramdicts = {}
     testers = collections.defaultdict(list)
@@ -149,8 +153,12 @@ def parameterize(cls):
             if name.startswith(paramsname):
                 testnameroot = 'test_' + name[len(paramsname):]
                 for paramname, params in paramsdict.items():
-                    test = (lambda self, name=name, params=params:
-                                    getattr(self, name)(*params))
+                    if hasattr(params, 'keys'):
+                        test = (lambda self, name=name, params=params:
+                                    getattr(self, name)(**params))
+                    else:
+                        test = (lambda self, name=name, params=params:
+                                        getattr(self, name)(*params))
                     testname = testnameroot + '_' + paramname
                     test.__name__ = testname
                     testfuncs[testname] = test
index 894b800..9b86a2a 100644 (file)
@@ -11,6 +11,7 @@ import textwrap
 from io import StringIO, BytesIO
 from itertools import chain
 from random import choice
+from socket import getfqdn
 try:
     from threading import Thread
 except ImportError:
@@ -723,12 +724,12 @@ class TestMessageAPI(TestEmailBase):
 
     # Issue 5871: reject an attempt to embed a header inside a header value
     # (header injection attack).
-    def test_embeded_header_via_Header_rejected(self):
+    def test_embedded_header_via_Header_rejected(self):
         msg = Message()
         msg['Dummy'] = Header('dummy\nX-Injected-Header: test')
         self.assertRaises(errors.HeaderParseError, msg.as_string)
 
-    def test_embeded_header_via_string_rejected(self):
+    def test_embedded_header_via_string_rejected(self):
         msg = Message()
         msg['Dummy'] = 'dummy\nX-Injected-Header: test'
         self.assertRaises(errors.HeaderParseError, msg.as_string)
@@ -1598,6 +1599,18 @@ class TestMIMEApplication(unittest.TestCase):
         self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata))
         self.assertEqual(msg2.get_payload(decode=True), bytesdata)
 
+    def test_binary_body_with_unicode_linend_encode_noop(self):
+        # Issue 19003: This is a variation on #16564.
+        bytesdata = b'\x0b\xfa\xfb\xfc\xfd\xfe\xff'
+        msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop)
+        self.assertEqual(msg.get_payload(decode=True), bytesdata)
+        s = BytesIO()
+        g = BytesGenerator(s)
+        g.flatten(msg)
+        wireform = s.getvalue()
+        msg2 = email.message_from_bytes(wireform)
+        self.assertEqual(msg2.get_payload(decode=True), bytesdata)
+
     def test_binary_body_with_encode_quopri(self):
         # Issue 14360.
         bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff '
@@ -1652,9 +1665,12 @@ class TestMIMEText(unittest.TestCase):
         eq(msg.get_charset().input_charset, 'us-ascii')
         eq(msg['content-type'], 'text/plain; charset="us-ascii"')
         # Also accept a Charset instance
-        msg = MIMEText('hello there', _charset=Charset('utf-8'))
+        charset = Charset('utf-8')
+        charset.body_encoding = None
+        msg = MIMEText('hello there', _charset=charset)
         eq(msg.get_charset().input_charset, 'utf-8')
         eq(msg['content-type'], 'text/plain; charset="utf-8"')
+        eq(msg.get_payload(), 'hello there')
 
     def test_7bit_input(self):
         eq = self.assertEqual
@@ -2302,9 +2318,9 @@ Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar =?mac-iceland?q?r=8Aksm?=
 
     def test_rfc2047_Q_invalid_digits(self):
         # issue 10004.
-        s = '=?iso-8659-1?Q?andr=e9=zz?='
+        s = '=?iso-8859-1?Q?andr=e9=zz?='
         self.assertEqual(decode_header(s),
-                        [(b'andr\xe9=zz', 'iso-8659-1')])
+                        [(b'andr\xe9=zz', 'iso-8859-1')])
 
     def test_rfc2047_rfc2047_1(self):
         # 1st testcase at end of rfc2047
@@ -3279,6 +3295,17 @@ multipart/report
             email.utils.make_msgid(domain='testdomain-string')[-19:],
             '@testdomain-string>')
 
+    def test_make_msgid_idstring(self):
+        self.assertEqual(
+            email.utils.make_msgid(idstring='test-idstring',
+                domain='testdomain-string')[-33:],
+            '.test-idstring@testdomain-string>')
+
+    def test_make_msgid_default_domain(self):
+        self.assertTrue(
+            email.utils.make_msgid().endswith(
+                '@' + getfqdn() + '>'))
+
     def test_Generator_linend(self):
         # Issue 14645.
         with openfile('msg_26.txt', newline='\n') as f:
@@ -3444,10 +3471,12 @@ class TestFeedParsers(TestEmailBase):
         self.assertEqual(m.keys(), ['a', 'b'])
         m = self.parse(['a:\r', '\nb:\n'])
         self.assertEqual(m.keys(), ['a', 'b'])
+
+        # Only CR and LF should break header fields
         m = self.parse(['a:\x85b:\u2028c:\n'])
-        self.assertEqual(m.items(), [('a', '\x85'), ('b', '\u2028'), ('c', '')])
+        self.assertEqual(m.items(), [('a', '\x85b:\u2028c:')])
         m = self.parse(['a:\r', 'b:\x85', 'c:\n'])
-        self.assertEqual(m.items(), [('a', ''), ('b', '\x85'), ('c', '')])
+        self.assertEqual(m.items(), [('a', ''), ('b', '\x85c:')])
 
     def test_long_lines(self):
         # Expected peak memory use on 32-bit platform: 6*N*M bytes.
index f36e33d..8e8d676 100644 (file)
@@ -7,6 +7,7 @@ producing RFC valid messages.
 import io
 import unittest
 from email import policy, message_from_bytes
+from email.message import EmailMessage
 from email.generator import BytesGenerator
 from test.test_email import TestEmailBase, parameterize
 
@@ -23,7 +24,10 @@ def dedent(bstr):
 
 
 @parameterize
-class TestInversion(TestEmailBase, unittest.TestCase):
+class TestInversion(TestEmailBase):
+
+    policy = policy.default
+    message = EmailMessage
 
     def msg_as_input(self, msg):
         m = message_from_bytes(msg, policy=policy.SMTP)
@@ -44,6 +48,23 @@ class TestInversion(TestEmailBase, unittest.TestCase):
 
             }
 
+    payload_params = {
+        'plain_text': dict(payload='This is a test\n'*20),
+        'base64_text': dict(payload=(('xy a'*40+'\n')*5), cte='base64'),
+        'qp_text': dict(payload=(('xy a'*40+'\n')*5), cte='quoted-printable'),
+        }
+
+    def payload_as_body(self, payload, **kw):
+        msg = self._make_message()
+        msg['From'] = 'foo'
+        msg['To'] = 'bar'
+        msg['Subject'] = 'payload round trip test'
+        msg.set_content(payload, **kw)
+        b = bytes(msg)
+        msg2 = message_from_bytes(b, policy=self.policy)
+        self.assertEqual(bytes(msg2), b)
+        self.assertEqual(msg2.get_content(), payload)
+
 
 if __name__ == '__main__':
     unittest.main()
index d78049e..4345162 100644 (file)
@@ -732,6 +732,16 @@ class TestEmailMessageBase:
         m.set_param('filename', 'abc.png', 'Content-Disposition')
         self.assertTrue(m.is_attachment())
 
+    def test_iter_attachments_mutation(self):
+        # We had a bug where iter_attachments was mutating the list.
+        m = self._make_message()
+        m.set_content('arbitrary text as main part')
+        m.add_related('more text as a related part')
+        m.add_related('yet more text as a second "attachment"')
+        orig = m.get_payload().copy()
+        self.assertEqual(len(list(m.iter_attachments())), 2)
+        self.assertEqual(m.get_payload(), orig)
+
 
 class TestEmailMessage(TestEmailMessageBase, TestEmailBase):
     message = EmailMessage
index b54fdd7..8ddc176 100644 (file)
@@ -2,6 +2,7 @@ import io
 import email
 import unittest
 from email.message import Message
+from email.policy import default
 from test.test_email import TestEmailBase
 
 
@@ -32,5 +33,45 @@ class TestCustomMessage(TestEmailBase):
     # XXX add tests for other functions that take Message arg.
 
 
+class TestParserBase:
+
+    def test_only_split_on_cr_lf(self):
+        # The unicode line splitter splits on unicode linebreaks, which are
+        # more numerous than allowed by the email RFCs; make sure we are only
+        # splitting on those two.
+        msg = self.parser(
+            "Next-Line: not\x85broken\r\n"
+            "Null: not\x00broken\r\n"
+            "Vertical-Tab: not\vbroken\r\n"
+            "Form-Feed: not\fbroken\r\n"
+            "File-Separator: not\x1Cbroken\r\n"
+            "Group-Separator: not\x1Dbroken\r\n"
+            "Record-Separator: not\x1Ebroken\r\n"
+            "Line-Separator: not\u2028broken\r\n"
+            "Paragraph-Separator: not\u2029broken\r\n"
+            "\r\n",
+            policy=default,
+        )
+        self.assertEqual(msg.items(), [
+            ("Next-Line", "not\x85broken"),
+            ("Null", "not\x00broken"),
+            ("Vertical-Tab", "not\vbroken"),
+            ("Form-Feed", "not\fbroken"),
+            ("File-Separator", "not\x1Cbroken"),
+            ("Group-Separator", "not\x1Dbroken"),
+            ("Record-Separator", "not\x1Ebroken"),
+            ("Line-Separator", "not\u2028broken"),
+            ("Paragraph-Separator", "not\u2029broken"),
+        ])
+        self.assertEqual(msg.get_payload(), "")
+
+class TestParser(TestParserBase, TestEmailBase):
+    parser = staticmethod(email.message_from_string)
+
+class TestBytesParser(TestParserBase, TestEmailBase):
+    def parser(self, s, *args, **kw):
+        return email.message_from_bytes(s.encode(), *args, **kw)
+
+
 if __name__ == '__main__':
     unittest.main()
index e970a26..630b155 100644 (file)
@@ -654,7 +654,7 @@ class TestEnum(unittest.TestCase):
                  self.Season.SPRING]
                 )
 
-    def test_programatic_function_string(self):
+    def test_programmatic_function_string(self):
         SummerMonth = Enum('SummerMonth', 'june july august')
         lst = list(SummerMonth)
         self.assertEqual(len(lst), len(SummerMonth))
@@ -671,7 +671,7 @@ class TestEnum(unittest.TestCase):
             self.assertIn(e, SummerMonth)
             self.assertIs(type(e), SummerMonth)
 
-    def test_programatic_function_string_with_start(self):
+    def test_programmatic_function_string_with_start(self):
         SummerMonth = Enum('SummerMonth', 'june july august', start=10)
         lst = list(SummerMonth)
         self.assertEqual(len(lst), len(SummerMonth))
@@ -688,7 +688,7 @@ class TestEnum(unittest.TestCase):
             self.assertIn(e, SummerMonth)
             self.assertIs(type(e), SummerMonth)
 
-    def test_programatic_function_string_list(self):
+    def test_programmatic_function_string_list(self):
         SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'])
         lst = list(SummerMonth)
         self.assertEqual(len(lst), len(SummerMonth))
@@ -705,7 +705,7 @@ class TestEnum(unittest.TestCase):
             self.assertIn(e, SummerMonth)
             self.assertIs(type(e), SummerMonth)
 
-    def test_programatic_function_string_list_with_start(self):
+    def test_programmatic_function_string_list_with_start(self):
         SummerMonth = Enum('SummerMonth', ['june', 'july', 'august'], start=20)
         lst = list(SummerMonth)
         self.assertEqual(len(lst), len(SummerMonth))
@@ -722,7 +722,7 @@ class TestEnum(unittest.TestCase):
             self.assertIn(e, SummerMonth)
             self.assertIs(type(e), SummerMonth)
 
-    def test_programatic_function_iterable(self):
+    def test_programmatic_function_iterable(self):
         SummerMonth = Enum(
                 'SummerMonth',
                 (('june', 1), ('july', 2), ('august', 3))
@@ -742,7 +742,7 @@ class TestEnum(unittest.TestCase):
             self.assertIn(e, SummerMonth)
             self.assertIs(type(e), SummerMonth)
 
-    def test_programatic_function_from_dict(self):
+    def test_programmatic_function_from_dict(self):
         SummerMonth = Enum(
                 'SummerMonth',
                 OrderedDict((('june', 1), ('july', 2), ('august', 3)))
@@ -762,7 +762,7 @@ class TestEnum(unittest.TestCase):
             self.assertIn(e, SummerMonth)
             self.assertIs(type(e), SummerMonth)
 
-    def test_programatic_function_type(self):
+    def test_programmatic_function_type(self):
         SummerMonth = Enum('SummerMonth', 'june july august', type=int)
         lst = list(SummerMonth)
         self.assertEqual(len(lst), len(SummerMonth))
@@ -778,7 +778,7 @@ class TestEnum(unittest.TestCase):
             self.assertIn(e, SummerMonth)
             self.assertIs(type(e), SummerMonth)
 
-    def test_programatic_function_type_with_start(self):
+    def test_programmatic_function_type_with_start(self):
         SummerMonth = Enum('SummerMonth', 'june july august', type=int, start=30)
         lst = list(SummerMonth)
         self.assertEqual(len(lst), len(SummerMonth))
@@ -794,7 +794,7 @@ class TestEnum(unittest.TestCase):
             self.assertIn(e, SummerMonth)
             self.assertIs(type(e), SummerMonth)
 
-    def test_programatic_function_type_from_subclass(self):
+    def test_programmatic_function_type_from_subclass(self):
         SummerMonth = IntEnum('SummerMonth', 'june july august')
         lst = list(SummerMonth)
         self.assertEqual(len(lst), len(SummerMonth))
@@ -810,7 +810,7 @@ class TestEnum(unittest.TestCase):
             self.assertIn(e, SummerMonth)
             self.assertIs(type(e), SummerMonth)
 
-    def test_programatic_function_type_from_subclass_with_start(self):
+    def test_programmatic_function_type_from_subclass_with_start(self):
         SummerMonth = IntEnum('SummerMonth', 'june july august', start=40)
         lst = list(SummerMonth)
         self.assertEqual(len(lst), len(SummerMonth))
index 458ddc1..96c3a48 100644 (file)
@@ -1096,6 +1096,23 @@ class ImportErrorTests(unittest.TestCase):
         self.assertEqual(exc.name, 'somename')
         self.assertEqual(exc.path, 'somepath')
 
+        msg = "'invalid' is an invalid keyword argument for this function"
+        with self.assertRaisesRegex(TypeError, msg):
+            ImportError('test', invalid='keyword')
+
+        with self.assertRaisesRegex(TypeError, msg):
+            ImportError('test', name='name', invalid='keyword')
+
+        with self.assertRaisesRegex(TypeError, msg):
+            ImportError('test', path='path', invalid='keyword')
+
+        with self.assertRaisesRegex(TypeError, msg):
+            ImportError(invalid='keyword')
+
+        msg = "'invalid|another' is an invalid keyword argument for this function"
+        with self.assertRaisesRegex(TypeError, msg):
+            ImportError('test', invalid='keyword', another=True)
+
     def test_non_str_argument(self):
         # Issue #15778
         with check_warnings(('', BytesWarning), quiet=True):
index d526b5f..9cb0d38 100644 (file)
@@ -57,6 +57,10 @@ Here we add keyword arguments
     Traceback (most recent call last):
         ...
     TypeError: f() got multiple values for keyword argument 'a'
+    >>> f(1, 2, a=3, **{'a': 4}, **{'a': 5})
+    Traceback (most recent call last):
+        ...
+    TypeError: f() got multiple values for keyword argument 'a'
     >>> f(1, 2, 3, *[4, 5], **{'a':6, 'b':7})
     (1, 2, 3, 4, 5) {'a': 6, 'b': 7}
     >>> f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b': 9})
@@ -229,6 +233,11 @@ What about willful misconduct?
       ...
     TypeError: h() argument after * must be an iterable, not function
 
+    >>> h(1, *h)
+    Traceback (most recent call last):
+      ...
+    TypeError: h() argument after * must be an iterable, not function
+
     >>> dir(*h)
     Traceback (most recent call last):
       ...
@@ -245,6 +254,31 @@ not function
       ...
     TypeError: h() argument after ** must be a mapping, not function
 
+    >>> h(**[])
+    Traceback (most recent call last):
+      ...
+    TypeError: h() argument after ** must be a mapping, not list
+
+    >>> h(a=1, **h)
+    Traceback (most recent call last):
+      ...
+    TypeError: h() argument after ** must be a mapping, not function
+
+    >>> h(a=1, **[])
+    Traceback (most recent call last):
+      ...
+    TypeError: h() argument after ** must be a mapping, not list
+
+    >>> h(**{'a': 1}, **h)
+    Traceback (most recent call last):
+      ...
+    TypeError: h() argument after ** must be a mapping, not function
+
+    >>> h(**{'a': 1}, **[])
+    Traceback (most recent call last):
+      ...
+    TypeError: h() argument after ** must be a mapping, not list
+
     >>> dir(**h)
     Traceback (most recent call last):
       ...
index 59cc38f..12f2f11 100644 (file)
@@ -377,7 +377,7 @@ class OtherFileTests:
                     self.assertEqual(f.writable(), True)
                     if sys.platform != "darwin" and \
                        'bsd' not in sys.platform and \
-                       not sys.platform.startswith('sunos'):
+                       not sys.platform.startswith(('sunos', 'aix')):
                         # Somehow /dev/tty appears seekable on some BSDs
                         self.assertEqual(f.seekable(), False)
                     self.assertEqual(f.isatty(), True)
index 9b13632..565bb79 100644 (file)
@@ -114,6 +114,7 @@ class FormatTest(unittest.TestCase):
         testcommon("%o", 100000000000, "1351035564000")
         testcommon("%d", 10, "10")
         testcommon("%d", 100000000000, "100000000000")
+
         big = 123456789012345678901234567890
         testcommon("%d", big, "123456789012345678901234567890")
         testcommon("%d", -big, "-123456789012345678901234567890")
@@ -133,6 +134,7 @@ class FormatTest(unittest.TestCase):
         testcommon("%.31d", big, "0123456789012345678901234567890")
         testcommon("%32.31d", big, " 0123456789012345678901234567890")
         testcommon("%d", float(big), "123456________________________", 6)
+
         big = 0x1234567890abcdef12345  # 21 hex digits
         testcommon("%x", big, "1234567890abcdef12345")
         testcommon("%x", -big, "-1234567890abcdef12345")
@@ -156,19 +158,26 @@ class FormatTest(unittest.TestCase):
         testcommon("%#X", big, "0X1234567890ABCDEF12345")
         testcommon("%#x", big, "0x1234567890abcdef12345")
         testcommon("%#x", -big, "-0x1234567890abcdef12345")
+        testcommon("%#27x", big, "    0x1234567890abcdef12345")
+        testcommon("%#-27x", big, "0x1234567890abcdef12345    ")
+        testcommon("%#027x", big, "0x00001234567890abcdef12345")
+        testcommon("%#.23x", big, "0x001234567890abcdef12345")
         testcommon("%#.23x", -big, "-0x001234567890abcdef12345")
+        testcommon("%#27.23x", big, "  0x001234567890abcdef12345")
+        testcommon("%#-27.23x", big, "0x001234567890abcdef12345  ")
+        testcommon("%#027.23x", big, "0x00001234567890abcdef12345")
         testcommon("%#+.23x", big, "+0x001234567890abcdef12345")
         testcommon("%# .23x", big, " 0x001234567890abcdef12345")
         testcommon("%#+.23X", big, "+0X001234567890ABCDEF12345")
-        testcommon("%#-+.23X", big, "+0X001234567890ABCDEF12345")
-        testcommon("%#-+26.23X", big, "+0X001234567890ABCDEF12345")
-        testcommon("%#-+27.23X", big, "+0X001234567890ABCDEF12345 ")
-        testcommon("%#+27.23X", big, " +0X001234567890ABCDEF12345")
         # next one gets two leading zeroes from precision, and another from the
         # 0 flag and the width
         testcommon("%#+027.23X", big, "+0X0001234567890ABCDEF12345")
+        testcommon("%# 027.23X", big, " 0X0001234567890ABCDEF12345")
         # same, except no 0 flag
         testcommon("%#+27.23X", big, " +0X001234567890ABCDEF12345")
+        testcommon("%#-+27.23x", big, "+0x001234567890abcdef12345 ")
+        testcommon("%#- 27.23x", big, " 0x001234567890abcdef12345 ")
+
         big = 0o12345670123456701234567012345670  # 32 octal digits
         testcommon("%o", big, "12345670123456701234567012345670")
         testcommon("%o", -big, "-12345670123456701234567012345670")
@@ -191,51 +200,46 @@ class FormatTest(unittest.TestCase):
         testcommon("%o", big, "12345670123456701234567012345670")
         testcommon("%#o", big, "0o12345670123456701234567012345670")
         testcommon("%#o", -big, "-0o12345670123456701234567012345670")
+        testcommon("%#38o", big, "    0o12345670123456701234567012345670")
+        testcommon("%#-38o", big, "0o12345670123456701234567012345670    ")
+        testcommon("%#038o", big, "0o000012345670123456701234567012345670")
+        testcommon("%#.34o", big, "0o0012345670123456701234567012345670")
         testcommon("%#.34o", -big, "-0o0012345670123456701234567012345670")
+        testcommon("%#38.34o", big, "  0o0012345670123456701234567012345670")
+        testcommon("%#-38.34o", big, "0o0012345670123456701234567012345670  ")
+        testcommon("%#038.34o", big, "0o000012345670123456701234567012345670")
         testcommon("%#+.34o", big, "+0o0012345670123456701234567012345670")
         testcommon("%# .34o", big, " 0o0012345670123456701234567012345670")
-        testcommon("%#+.34o", big, "+0o0012345670123456701234567012345670")
-        testcommon("%#-+.34o", big, "+0o0012345670123456701234567012345670")
-        testcommon("%#-+37.34o", big, "+0o0012345670123456701234567012345670")
-        testcommon("%#+37.34o", big, "+0o0012345670123456701234567012345670")
+        testcommon("%#+38.34o", big, " +0o0012345670123456701234567012345670")
+        testcommon("%#-+38.34o", big, "+0o0012345670123456701234567012345670 ")
+        testcommon("%#- 38.34o", big, " 0o0012345670123456701234567012345670 ")
+        testcommon("%#+038.34o", big, "+0o00012345670123456701234567012345670")
+        testcommon("%# 038.34o", big, " 0o00012345670123456701234567012345670")
         # next one gets one leading zero from precision
         testcommon("%.33o", big, "012345670123456701234567012345670")
-        # base marker shouldn't change that, since "0" is redundant
+        # base marker added in spite of leading zero (different to Python 2)
         testcommon("%#.33o", big, "0o012345670123456701234567012345670")
-        # but reduce precision, and base marker should add a zero
+        # reduce precision, and base marker is always added
         testcommon("%#.32o", big, "0o12345670123456701234567012345670")
-        # one leading zero from precision, and another from "0" flag & width
-        testcommon("%034.33o", big, "0012345670123456701234567012345670")
-        # base marker shouldn't change that
-        testcommon("%0#34.33o", big, "0o012345670123456701234567012345670")
+        # one leading zero from precision, plus two from "0" flag & width
+        testcommon("%035.33o", big, "00012345670123456701234567012345670")
+        # base marker shouldn't change the size
+        testcommon("%0#35.33o", big, "0o012345670123456701234567012345670")
+
         # Some small ints, in both Python int and flavors).
         testcommon("%d", 42, "42")
         testcommon("%d", -42, "-42")
-        testcommon("%d", 42, "42")
-        testcommon("%d", -42, "-42")
         testcommon("%d", 42.0, "42")
         testcommon("%#x", 1, "0x1")
-        testcommon("%#x", 1, "0x1")
         testcommon("%#X", 1, "0X1")
-        testcommon("%#X", 1, "0X1")
-        testcommon("%#o", 1, "0o1")
         testcommon("%#o", 1, "0o1")
         testcommon("%#o", 0, "0o0")
-        testcommon("%#o", 0, "0o0")
-        testcommon("%o", 0, "0")
         testcommon("%o", 0, "0")
         testcommon("%d", 0, "0")
-        testcommon("%d", 0, "0")
         testcommon("%#x", 0, "0x0")
-        testcommon("%#x", 0, "0x0")
-        testcommon("%#X", 0, "0X0")
         testcommon("%#X", 0, "0X0")
         testcommon("%x", 0x42, "42")
         testcommon("%x", -0x42, "-42")
-        testcommon("%x", 0x42, "42")
-        testcommon("%x", -0x42, "-42")
-        testcommon("%o", 0o42, "42")
-        testcommon("%o", -0o42, "-42")
         testcommon("%o", 0o42, "42")
         testcommon("%o", -0o42, "-42")
         # alternate float formatting
@@ -384,6 +388,13 @@ class FormatTest(unittest.TestCase):
             else:
                 raise TestFailed('"%*d"%(maxsize, -127) should fail')
 
+    def test_nul(self):
+        # test the null character
+        testcommon("a\0b", (), 'a\0b')
+        testcommon("a%cb", (0,), 'a\0b')
+        testformat("a%sb", ('c\0d',), 'ac\0db')
+        testcommon(b"a%sb", (b'c\0d',), b'ac\0db')
+
     def test_non_ascii(self):
         testformat("\u20ac=%f", (1.0,), "\u20ac=1.000000")
 
index 1699852..9df4a54 100644 (file)
@@ -356,6 +356,19 @@ class FractionTest(unittest.TestCase):
         z = pow(F(-1), F(1, 2))
         self.assertAlmostEqual(z.real, 0)
         self.assertEqual(z.imag, 1)
+        # Regression test for #27539.
+        p = F(-1, 2) ** 0
+        self.assertEqual(p, F(1, 1))
+        self.assertEqual(p.numerator, 1)
+        self.assertEqual(p.denominator, 1)
+        p = F(-1, 2) ** -1
+        self.assertEqual(p, F(-2, 1))
+        self.assertEqual(p.numerator, -2)
+        self.assertEqual(p.denominator, 1)
+        p = F(-1, 2) ** -2
+        self.assertEqual(p, F(4, 1))
+        self.assertEqual(p.numerator, 4)
+        self.assertEqual(p.denominator, 1)
 
     def testMixedArithmetic(self):
         self.assertTypedEquals(F(11, 10), F(1, 10) + 1)
index 9abe984..b431e05 100644 (file)
@@ -1,4 +1,5 @@
 import abc
+import builtins
 import collections
 import copy
 from itertools import permutations
@@ -217,6 +218,33 @@ class TestPartialC(TestPartial, unittest.TestCase):
                       ['{}({!r}, {}, {})'.format(name, capture, args_repr, kwargs_repr)
                        for kwargs_repr in kwargs_reprs])
 
+    def test_recursive_repr(self):
+        if self.partial is c_functools.partial:
+            name = 'functools.partial'
+        else:
+            name = self.partial.__name__
+
+        f = self.partial(capture)
+        f.__setstate__((f, (), {}, {}))
+        try:
+            self.assertEqual(repr(f), '%s(%s(...))' % (name, name))
+        finally:
+            f.__setstate__((capture, (), {}, {}))
+
+        f = self.partial(capture)
+        f.__setstate__((capture, (f,), {}, {}))
+        try:
+            self.assertEqual(repr(f), '%s(%r, %s(...))' % (name, capture, name))
+        finally:
+            f.__setstate__((capture, (), {}, {}))
+
+        f = self.partial(capture)
+        f.__setstate__((capture, (), {'a': f}, {}))
+        try:
+            self.assertEqual(repr(f), '%s(%r, a=%s(...))' % (name, capture, name))
+        finally:
+            f.__setstate__((capture, (), {}, {}))
+
     def test_pickle(self):
         f = self.partial(signature, ['asdf'], bar=[True])
         f.attr = []
@@ -297,6 +325,40 @@ class TestPartialC(TestPartial, unittest.TestCase):
         self.assertEqual(r, ((1, 2), {}))
         self.assertIs(type(r[0]), tuple)
 
+    def test_recursive_pickle(self):
+        f = self.partial(capture)
+        f.__setstate__((f, (), {}, {}))
+        try:
+            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+                with self.assertRaises(RecursionError):
+                    pickle.dumps(f, proto)
+        finally:
+            f.__setstate__((capture, (), {}, {}))
+
+        f = self.partial(capture)
+        f.__setstate__((capture, (f,), {}, {}))
+        try:
+            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+                f_copy = pickle.loads(pickle.dumps(f, proto))
+                try:
+                    self.assertIs(f_copy.args[0], f_copy)
+                finally:
+                    f_copy.__setstate__((capture, (), {}, {}))
+        finally:
+            f.__setstate__((capture, (), {}, {}))
+
+        f = self.partial(capture)
+        f.__setstate__((capture, (), {'a': f}, {}))
+        try:
+            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+                f_copy = pickle.loads(pickle.dumps(f, proto))
+                try:
+                    self.assertIs(f_copy.keywords['a'], f_copy)
+                finally:
+                    f_copy.__setstate__((capture, (), {}, {}))
+        finally:
+            f.__setstate__((capture, (), {}, {}))
+
     # Issue 6083: Reference counting bug
     def test_setstate_refcount(self):
         class BadSequence:
@@ -993,7 +1055,7 @@ class TestTotalOrdering(unittest.TestCase):
                 a <= b
 
     def test_pickle(self):
-        for proto in range(4, pickle.HIGHEST_PROTOCOL + 1):
+        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
             for name in '__lt__', '__gt__', '__le__', '__ge__':
                 with self.subTest(method=name, proto=proto):
                     method = getattr(Orderable_LT, name)
@@ -1101,6 +1163,37 @@ class TestLRU:
         self.assertEqual(misses, 4)
         self.assertEqual(currsize, 2)
 
+    def test_lru_reentrancy_with_len(self):
+        # Test to make sure the LRU cache code isn't thrown-off by
+        # caching the built-in len() function.  Since len() can be
+        # cached, we shouldn't use it inside the lru code itself.
+        old_len = builtins.len
+        try:
+            builtins.len = self.module.lru_cache(4)(len)
+            for i in [0, 0, 1, 2, 3, 3, 4, 5, 6, 1, 7, 2, 1]:
+                self.assertEqual(len('abcdefghijklmn'[:i]), i)
+        finally:
+            builtins.len = old_len
+
+    def test_lru_type_error(self):
+        # Regression test for issue #28653.
+        # lru_cache was leaking when one of the arguments
+        # wasn't cacheable.
+
+        @functools.lru_cache(maxsize=None)
+        def infinite_cache(o):
+            pass
+
+        @functools.lru_cache(maxsize=10)
+        def limited_cache(o):
+            pass
+
+        with self.assertRaises(TypeError):
+            infinite_cache([])
+
+        with self.assertRaises(TypeError):
+            limited_cache([])
+
     def test_lru_with_maxsize_none(self):
         @self.module.lru_cache(maxsize=None)
         def fib(n):
index beac993..7b072ad 100644 (file)
@@ -2,6 +2,7 @@
 
 import unittest
 from test import support
+import os
 import re
 
 rx = re.compile('\((\S+).py, line (\d+)')
@@ -12,6 +13,12 @@ def get_error_location(msg):
 
 class FutureTest(unittest.TestCase):
 
+    def check_syntax_error(self, err, basename, lineno, offset=0):
+        self.assertIn('%s.py, line %d' % (basename, lineno), str(err))
+        self.assertEqual(os.path.basename(err.filename), basename + '.py')
+        self.assertEqual(err.lineno, lineno)
+        self.assertEqual(err.offset, offset)
+
     def test_future1(self):
         with support.CleanImport('future_test1'):
             from test import future_test1
@@ -27,68 +34,44 @@ class FutureTest(unittest.TestCase):
             from test import test_future3
 
     def test_badfuture3(self):
-        try:
+        with self.assertRaises(SyntaxError) as cm:
             from test import badsyntax_future3
-        except SyntaxError as msg:
-            self.assertEqual(get_error_location(msg), ("badsyntax_future3", '3'))
-        else:
-            self.fail("expected exception didn't occur")
+        self.check_syntax_error(cm.exception, "badsyntax_future3", 3)
 
     def test_badfuture4(self):
-        try:
+        with self.assertRaises(SyntaxError) as cm:
             from test import badsyntax_future4
-        except SyntaxError as msg:
-            self.assertEqual(get_error_location(msg), ("badsyntax_future4", '3'))
-        else:
-            self.fail("expected exception didn't occur")
+        self.check_syntax_error(cm.exception, "badsyntax_future4", 3)
 
     def test_badfuture5(self):
-        try:
+        with self.assertRaises(SyntaxError) as cm:
             from test import badsyntax_future5
-        except SyntaxError as msg:
-            self.assertEqual(get_error_location(msg), ("badsyntax_future5", '4'))
-        else:
-            self.fail("expected exception didn't occur")
+        self.check_syntax_error(cm.exception, "badsyntax_future5", 4)
 
     def test_badfuture6(self):
-        try:
+        with self.assertRaises(SyntaxError) as cm:
             from test import badsyntax_future6
-        except SyntaxError as msg:
-            self.assertEqual(get_error_location(msg), ("badsyntax_future6", '3'))
-        else:
-            self.fail("expected exception didn't occur")
+        self.check_syntax_error(cm.exception, "badsyntax_future6", 3)
 
     def test_badfuture7(self):
-        try:
+        with self.assertRaises(SyntaxError) as cm:
             from test import badsyntax_future7
-        except SyntaxError as msg:
-            self.assertEqual(get_error_location(msg), ("badsyntax_future7", '3'))
-        else:
-            self.fail("expected exception didn't occur")
+        self.check_syntax_error(cm.exception, "badsyntax_future7", 3, 53)
 
     def test_badfuture8(self):
-        try:
+        with self.assertRaises(SyntaxError) as cm:
             from test import badsyntax_future8
-        except SyntaxError as msg:
-            self.assertEqual(get_error_location(msg), ("badsyntax_future8", '3'))
-        else:
-            self.fail("expected exception didn't occur")
+        self.check_syntax_error(cm.exception, "badsyntax_future8", 3)
 
     def test_badfuture9(self):
-        try:
+        with self.assertRaises(SyntaxError) as cm:
             from test import badsyntax_future9
-        except SyntaxError as msg:
-            self.assertEqual(get_error_location(msg), ("badsyntax_future9", '3'))
-        else:
-            self.fail("expected exception didn't occur")
+        self.check_syntax_error(cm.exception, "badsyntax_future9", 3, 0)
 
     def test_badfuture10(self):
-        try:
+        with self.assertRaises(SyntaxError) as cm:
             from test import badsyntax_future10
-        except SyntaxError as msg:
-            self.assertEqual(get_error_location(msg), ("badsyntax_future10", '3'))
-        else:
-            self.fail("expected exception didn't occur")
+        self.check_syntax_error(cm.exception, "badsyntax_future10", 3, 0)
 
     def test_parserhack(self):
         # test that the parser.c::future_hack function works as expected
index 1f0867d..a4d684b 100644 (file)
@@ -1,7 +1,7 @@
 import unittest
 from test.support import (verbose, refcount_test, run_unittest,
-                            strip_python_stderr, cpython_only, start_threads,
-                            temp_dir)
+                          strip_python_stderr, cpython_only, start_threads,
+                          temp_dir, requires_type_collecting)
 from test.support.script_helper import assert_python_ok, make_script
 
 import sys
@@ -118,6 +118,7 @@ class GCTests(unittest.TestCase):
         del a
         self.assertNotEqual(gc.collect(), 0)
 
+    @requires_type_collecting
     def test_newinstance(self):
         class A(object):
             pass
@@ -678,6 +679,7 @@ class GCTests(unittest.TestCase):
         stderr = run_command(code % "gc.DEBUG_SAVEALL")
         self.assertNotIn(b"uncollectable objects at shutdown", stderr)
 
+    @requires_type_collecting
     def test_gc_main_module_at_shutdown(self):
         # Create a reference cycle through the __main__ module and check
         # it gets collected at interpreter shutdown.
@@ -692,6 +694,7 @@ class GCTests(unittest.TestCase):
         rc, out, err = assert_python_ok('-c', code)
         self.assertEqual(out.strip(), b'__del__ called')
 
+    @requires_type_collecting
     def test_gc_ordinary_module_at_shutdown(self):
         # Same as above, but with a non-__main__ module.
         with temp_dir() as script_dir:
index cd7d292..3db10b6 100644 (file)
@@ -25,6 +25,7 @@ def get_gdb_version():
     try:
         proc = subprocess.Popen(["gdb", "-nx", "--version"],
                                 stdout=subprocess.PIPE,
+                                stderr=subprocess.PIPE,
                                 universal_newlines=True)
         with proc:
             version = proc.communicate()[0]
@@ -91,7 +92,7 @@ if not gdbpy_version:
     raise unittest.SkipTest("gdb not built with embedded python support")
 
 # Verify that "gdb" can load our custom hooks, as OS security settings may
-# disallow this without a customised .gdbinit.
+# disallow this without a customized .gdbinit.
 _, gdbpy_errors = run_gdb('--args', sys.executable)
 if "auto-loading has been declined" in gdbpy_errors:
     msg = "gdb security settings prevent use of custom hooks: "
index 3f82462..cd6a43d 100644 (file)
@@ -277,6 +277,27 @@ class ExceptionTest(unittest.TestCase):
             # hence no warning.
             next(g)
 
+    def test_return_tuple(self):
+        def g():
+            return (yield 1)
+
+        gen = g()
+        self.assertEqual(next(gen), 1)
+        with self.assertRaises(StopIteration) as cm:
+            gen.send((2,))
+        self.assertEqual(cm.exception.value, (2,))
+
+    def test_return_stopiteration(self):
+        def g():
+            return (yield 1)
+
+        gen = g()
+        self.assertEqual(next(gen), 1)
+        with self.assertRaises(StopIteration) as cm:
+            gen.send(StopIteration(2))
+        self.assertIsInstance(cm.exception.value, StopIteration)
+        self.assertEqual(cm.exception.value.value, 2)
+
 
 class YieldFromTests(unittest.TestCase):
     def test_generator_gi_yieldfrom(self):
index 86fc2de..b77d1d7 100644 (file)
@@ -274,6 +274,15 @@ class TestGenericTest(GenericTest, unittest.TestCase):
     # and is only meant to be inherited by others.
     pathmodule = genericpath
 
+    def test_null_bytes(self):
+        for attr in GenericTest.common_attributes:
+            # os.path.commonprefix doesn't raise ValueError
+            if attr == 'commonprefix':
+                continue
+            with self.subTest(attr=attr):
+                with self.assertRaises(ValueError) as cm:
+                    getattr(self.pathmodule, attr)('/tmp\x00abcds')
+                self.assertIn('embedded null', str(cm.exception))
 
 # Following TestCase is not supposed to be run from test_genericpath.
 # It is inherited by other test modules (macpath, ntpath, posixpath).
index de610c7..f57e546 100644 (file)
@@ -306,7 +306,9 @@ class PluralFormsTestCase(GettextBaseTest):
         x = t.ngettext('There is %s file', 'There are %s files', 2)
         eq(x, 'Hay %s ficheros')
 
-    def test_hu(self):
+    # Examples from http://www.gnu.org/software/gettext/manual/gettext.html
+
+    def test_ja(self):
         eq = self.assertEqual
         f = gettext.c2py('0')
         s = ''.join([ str(f(x)) for x in range(200) ])
@@ -324,6 +326,12 @@ class PluralFormsTestCase(GettextBaseTest):
         s = ''.join([ str(f(x)) for x in range(200) ])
         eq(s, "00111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")
 
+    def test_lv(self):
+        eq = self.assertEqual
+        f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2')
+        s = ''.join([ str(f(x)) for x in range(200) ])
+        eq(s, "20111111111111111111101111111110111111111011111111101111111110111111111011111111101111111110111111111011111111111111111110111111111011111111101111111110111111111011111111101111111110111111111011111111")
+
     def test_gd(self):
         eq = self.assertEqual
         f = gettext.c2py('n==1 ? 0 : n==2 ? 1 : 2')
@@ -337,6 +345,12 @@ class PluralFormsTestCase(GettextBaseTest):
         s = ''.join([ str(f(x)) for x in range(200) ])
         eq(s, "20122222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222")
 
+    def test_ro(self):
+        eq = self.assertEqual
+        f = gettext.c2py('n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2')
+        s = ''.join([ str(f(x)) for x in range(200) ])
+        eq(s, "10111111111111111111222222222222222222222222222222222222222222222222222222222222222222222222222222222111111111111111111122222222222222222222222222222222222222222222222222222222222222222222222222222222")
+
     def test_lt(self):
         eq = self.assertEqual
         f = gettext.c2py('n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2')
@@ -349,6 +363,12 @@ class PluralFormsTestCase(GettextBaseTest):
         s = ''.join([ str(f(x)) for x in range(200) ])
         eq(s, "20111222222222222222201112222220111222222011122222201112222220111222222011122222201112222220111222222011122222222222222220111222222011122222201112222220111222222011122222201112222220111222222011122222")
 
+    def test_cs(self):
+        eq = self.assertEqual
+        f = gettext.c2py('(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2')
+        s = ''.join([ str(f(x)) for x in range(200) ])
+        eq(s, "20111222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222")
+
     def test_pl(self):
         eq = self.assertEqual
         f = gettext.c2py('n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2')
@@ -361,10 +381,77 @@ class PluralFormsTestCase(GettextBaseTest):
         s = ''.join([ str(f(x)) for x in range(200) ])
         eq(s, "30122333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333012233333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333")
 
+    def test_ar(self):
+        eq = self.assertEqual
+        f = gettext.c2py('n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5')
+        s = ''.join([ str(f(x)) for x in range(200) ])
+        eq(s, "01233333333444444444444444444444444444444444444444444444444444444444444444444444444444444444444444445553333333344444444444444444444444444444444444444444444444444444444444444444444444444444444444444444")
+
     def test_security(self):
         raises = self.assertRaises
         # Test for a dangerous expression
         raises(ValueError, gettext.c2py, "os.chmod('/etc/passwd',0777)")
+        # issue28563
+        raises(ValueError, gettext.c2py, '"(eval(foo) && ""')
+        raises(ValueError, gettext.c2py, 'f"{os.system(\'sh\')}"')
+        # Maximum recursion depth exceeded during compilation
+        raises(ValueError, gettext.c2py, 'n+'*10000 + 'n')
+        self.assertEqual(gettext.c2py('n+'*100 + 'n')(1), 101)
+        # MemoryError during compilation
+        raises(ValueError, gettext.c2py, '('*100 + 'n' + ')'*100)
+        # Maximum recursion depth exceeded in C to Python translator
+        raises(ValueError, gettext.c2py, '('*10000 + 'n' + ')'*10000)
+        self.assertEqual(gettext.c2py('('*20 + 'n' + ')'*20)(1), 1)
+
+    def test_chained_comparison(self):
+        # C doesn't chain comparison as Python so 2 == 2 == 2 gets different results
+        f = gettext.c2py('n == n == n')
+        self.assertEqual(''.join(str(f(x)) for x in range(3)), '010')
+        f = gettext.c2py('1 < n == n')
+        self.assertEqual(''.join(str(f(x)) for x in range(3)), '100')
+        f = gettext.c2py('n == n < 2')
+        self.assertEqual(''.join(str(f(x)) for x in range(3)), '010')
+        f = gettext.c2py('0 < n < 2')
+        self.assertEqual(''.join(str(f(x)) for x in range(3)), '111')
+
+    def test_decimal_number(self):
+        self.assertEqual(gettext.c2py('0123')(1), 123)
+
+    def test_invalid_syntax(self):
+        invalid_expressions = [
+            'x>1', '(n>1', 'n>1)', '42**42**42', '0xa', '1.0', '1e2',
+            'n>0x1', '+n', '-n', 'n()', 'n(1)', '1+', 'nn', 'n n',
+        ]
+        for expr in invalid_expressions:
+            with self.assertRaises(ValueError):
+                gettext.c2py(expr)
+
+    def test_nested_condition_operator(self):
+        self.assertEqual(gettext.c2py('n?1?2:3:4')(0), 4)
+        self.assertEqual(gettext.c2py('n?1?2:3:4')(1), 2)
+        self.assertEqual(gettext.c2py('n?1:3?4:5')(0), 4)
+        self.assertEqual(gettext.c2py('n?1:3?4:5')(1), 1)
+
+    def test_division(self):
+        f = gettext.c2py('2/n*3')
+        self.assertEqual(f(1), 6)
+        self.assertEqual(f(2), 3)
+        self.assertEqual(f(3), 0)
+        self.assertEqual(f(-1), -6)
+        self.assertRaises(ZeroDivisionError, f, 0)
+
+    def test_plural_number(self):
+        f = gettext.c2py('n != 1')
+        self.assertEqual(f(1), 0)
+        self.assertEqual(f(2), 1)
+        self.assertEqual(f(1.0), 0)
+        self.assertEqual(f(2.0), 1)
+        self.assertEqual(f(1.1), 1)
+        self.assertRaises(TypeError, f, '2')
+        self.assertRaises(TypeError, f, b'2')
+        self.assertRaises(TypeError, f, [])
+        self.assertRaises(TypeError, f, object())
+
 
 class GNUTranslationParsingTest(GettextBaseTest):
     def test_plural_form_error_issue17898(self):
index 585838b..49c01ae 100644 (file)
@@ -31,6 +31,28 @@ class DateTimeTests(unittest.TestCase):
             self.assertRegex(text, r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$",
                              "bad time2isoz format: %s %s" % (az, bz))
 
+    def test_time2netscape(self):
+        base = 1019227000
+        day = 24*3600
+        self.assertEqual(time2netscape(base), "Fri, 19-Apr-2002 14:36:40 GMT")
+        self.assertEqual(time2netscape(base+day),
+                         "Sat, 20-Apr-2002 14:36:40 GMT")
+
+        self.assertEqual(time2netscape(base+2*day),
+                         "Sun, 21-Apr-2002 14:36:40 GMT")
+
+        self.assertEqual(time2netscape(base+3*day),
+                         "Mon, 22-Apr-2002 14:36:40 GMT")
+
+        az = time2netscape()
+        bz = time2netscape(500000)
+        for text in (az, bz):
+            # Format "%s, %02d-%s-%04d %02d:%02d:%02d GMT"
+            self.assertRegex(
+                text,
+                r"[a-zA-Z]{3}, \d{2}-[a-zA-Z]{3}-\d{4} \d{2}:\d{2}:\d{2} GMT$",
+                "bad time2netscape format: %s %s" % (az, bz))
+
     def test_http2time(self):
         def parse_date(text):
             return time.gmtime(http2time(text))[:6]
@@ -374,7 +396,7 @@ class CookieTests(unittest.TestCase):
 ##   comma-separated list, it'll be a headache to parse (at least my head
 ##   starts hurting every time I think of that code).
 ## - Expires: You'll get all sorts of date formats in the expires,
-##   including emtpy expires attributes ("expires="). Be as flexible as you
+##   including empty expires attributes ("expires="). Be as flexible as you
 ##   can, and certainly don't expect the weekday to be there; if you can't
 ##   parse it, just ignore it and pretend it's a session cookie.
 ## - Domain-matching: Netscape uses the 2-dot rule for _all_ domains, not
index 329f068..61ed6bb 100644 (file)
@@ -283,6 +283,36 @@ class HeaderTests(TestCase):
         self.assertEqual(resp.getheader('First'), 'val')
         self.assertEqual(resp.getheader('Second'), 'val')
 
+    def test_parse_all_octets(self):
+        # Ensure no valid header field octet breaks the parser
+        body = (
+            b'HTTP/1.1 200 OK\r\n'
+            b"!#$%&'*+-.^_`|~: value\r\n"  # Special token characters
+            b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
+            b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
+            b'obs-fold: text\r\n'
+            b' folded with space\r\n'
+            b'\tfolded with tab\r\n'
+            b'Content-Length: 0\r\n'
+            b'\r\n'
+        )
+        sock = FakeSocket(body)
+        resp = client.HTTPResponse(sock)
+        resp.begin()
+        self.assertEqual(resp.getheader('Content-Length'), '0')
+        self.assertEqual(resp.msg['Content-Length'], '0')
+        self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
+        self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
+        vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
+        self.assertEqual(resp.getheader('VCHAR'), vchar)
+        self.assertEqual(resp.msg['VCHAR'], vchar)
+        self.assertIsNotNone(resp.getheader('obs-text'))
+        self.assertIn('obs-text', resp.msg)
+        for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
+            self.assertTrue(folded.startswith('text'))
+            self.assertIn(' folded with space', folded)
+            self.assertTrue(folded.endswith('folded with tab'))
+
     def test_invalid_headers(self):
         conn = client.HTTPConnection('example.com')
         conn.sock = FakeSocket('')
@@ -1242,7 +1272,7 @@ class SourceAddressTest(TestCase):
     def testHTTPSConnectionSourceAddress(self):
         self.conn = client.HTTPSConnection(HOST, self.port,
                 source_address=('', self.source_port))
-        # We don't test anything here other the constructor not barfing as
+        # We don't test anything here other than the constructor not barfing as
         # this code doesn't deal with setting up an active running SSL server
         # for an ssl_wrapped connect() to actually return from.
 
@@ -1402,6 +1432,7 @@ class HTTPSTest(TestCase):
             resp = h.getresponse()
             h.close()
             self.assertIn('nginx', resp.getheader('server'))
+            resp.close()
 
     @support.system_must_validate_cert
     def test_networked_trusted_by_default_cert(self):
@@ -1412,6 +1443,7 @@ class HTTPSTest(TestCase):
             h.request('GET', '/')
             resp = h.getresponse()
             content_type = resp.getheader('content-type')
+            resp.close()
             h.close()
             self.assertIn('text/html', content_type)
 
@@ -1427,6 +1459,7 @@ class HTTPSTest(TestCase):
             h.request('GET', '/')
             resp = h.getresponse()
             server_string = resp.getheader('server')
+            resp.close()
             h.close()
             self.assertIn('nginx', server_string)
 
@@ -1460,8 +1493,10 @@ class HTTPSTest(TestCase):
         context.verify_mode = ssl.CERT_REQUIRED
         context.load_verify_locations(CERT_localhost)
         h = client.HTTPSConnection('localhost', server.port, context=context)
+        self.addCleanup(h.close)
         h.request('GET', '/nonexistent')
         resp = h.getresponse()
+        self.addCleanup(resp.close)
         self.assertEqual(resp.status, 404)
 
     def test_local_bad_hostname(self):
@@ -1486,13 +1521,18 @@ class HTTPSTest(TestCase):
                                    check_hostname=False)
         h.request('GET', '/nonexistent')
         resp = h.getresponse()
+        resp.close()
+        h.close()
         self.assertEqual(resp.status, 404)
         # The context's check_hostname setting is used if one isn't passed to
         # HTTPSConnection.
         context.check_hostname = False
         h = client.HTTPSConnection('localhost', server.port, context=context)
         h.request('GET', '/nonexistent')
-        self.assertEqual(h.getresponse().status, 404)
+        resp = h.getresponse()
+        self.assertEqual(resp.status, 404)
+        resp.close()
+        h.close()
         # Passing check_hostname to HTTPSConnection should override the
         # context's setting.
         h = client.HTTPSConnection('localhost', server.port, context=context,
index 07157f5..6e4a90f 100644 (file)
@@ -10,10 +10,12 @@ import os.path
 import socketserver
 import time
 import calendar
+import inspect
 
 from test.support import (reap_threads, verbose, transient_internet,
                           run_with_tz, run_with_locale)
 import unittest
+from unittest import mock
 from datetime import datetime, timezone, timedelta
 try:
     import ssl
@@ -174,6 +176,334 @@ class SimpleIMAPHandler(socketserver.StreamRequestHandler):
         self._send_tagged(tag, 'OK', 'LOGIN completed')
 
 
+class NewIMAPTestsMixin():
+    client = None
+
+    def _setup(self, imap_handler, connect=True):
+        """
+        Sets up imap_handler for tests. imap_handler should inherit from either:
+        - SimpleIMAPHandler - for testing IMAP commands,
+        - socketserver.StreamRequestHandler - if raw access to stream is needed.
+        Returns (client, server).
+        """
+        class TestTCPServer(self.server_class):
+            def handle_error(self, request, client_address):
+                """
+                End request and raise the error if one occurs.
+                """
+                self.close_request(request)
+                self.server_close()
+                raise
+
+        self.addCleanup(self._cleanup)
+        self.server = self.server_class((support.HOST, 0), imap_handler)
+        self.thread = threading.Thread(
+            name=self._testMethodName+'-server',
+            target=self.server.serve_forever,
+            # Short poll interval to make the test finish quickly.
+            # Time between requests is short enough that we won't wake
+            # up spuriously too many times.
+            kwargs={'poll_interval': 0.01})
+        self.thread.daemon = True  # In case this function raises.
+        self.thread.start()
+
+        if connect:
+            self.client = self.imap_class(*self.server.server_address)
+
+        return self.client, self.server
+
+    def _cleanup(self):
+        """
+        Cleans up the test server. This method should not be called manually,
+        it is added to the cleanup queue in the _setup method already.
+        """
+        # if logout was called already we'd raise an exception trying to
+        # shutdown the client once again
+        if self.client is not None and self.client.state != 'LOGOUT':
+            self.client.shutdown()
+        # cleanup the server
+        self.server.shutdown()
+        self.server.server_close()
+        self.thread.join(3.0)
+
+    def test_EOF_without_complete_welcome_message(self):
+        # http://bugs.python.org/issue5949
+        class EOFHandler(socketserver.StreamRequestHandler):
+            def handle(self):
+                self.wfile.write(b'* OK')
+        _, server = self._setup(EOFHandler, connect=False)
+        self.assertRaises(imaplib.IMAP4.abort, self.imap_class,
+                          *server.server_address)
+
+    def test_line_termination(self):
+        class BadNewlineHandler(SimpleIMAPHandler):
+            def cmd_CAPABILITY(self, tag, args):
+                self._send(b'* CAPABILITY IMAP4rev1 AUTH\n')
+                self._send_tagged(tag, 'OK', 'CAPABILITY completed')
+        _, server = self._setup(BadNewlineHandler, connect=False)
+        self.assertRaises(imaplib.IMAP4.abort, self.imap_class,
+                          *server.server_address)
+
+    def test_enable_raises_error_if_not_AUTH(self):
+        class EnableHandler(SimpleIMAPHandler):
+            capabilities = 'AUTH ENABLE UTF8=ACCEPT'
+        client, _ = self._setup(EnableHandler)
+        self.assertFalse(client.utf8_enabled)
+        with self.assertRaisesRegex(imaplib.IMAP4.error, 'ENABLE.*NONAUTH'):
+            client.enable('foo')
+        self.assertFalse(client.utf8_enabled)
+
+    def test_enable_raises_error_if_no_capability(self):
+        client, _ = self._setup(SimpleIMAPHandler)
+        with self.assertRaisesRegex(imaplib.IMAP4.error,
+                'does not support ENABLE'):
+            client.enable('foo')
+
+    def test_enable_UTF8_raises_error_if_not_supported(self):
+        client, _ = self._setup(SimpleIMAPHandler)
+        typ, data = client.login('user', 'pass')
+        self.assertEqual(typ, 'OK')
+        with self.assertRaisesRegex(imaplib.IMAP4.error,
+                'does not support ENABLE'):
+            client.enable('UTF8=ACCEPT')
+
+    def test_enable_UTF8_True_append(self):
+        class UTF8AppendServer(SimpleIMAPHandler):
+            capabilities = 'ENABLE UTF8=ACCEPT'
+            def cmd_ENABLE(self, tag, args):
+                self._send_tagged(tag, 'OK', 'ENABLE successful')
+            def cmd_AUTHENTICATE(self, tag, args):
+                self._send_textline('+')
+                self.server.response = yield
+                self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
+            def cmd_APPEND(self, tag, args):
+                self._send_textline('+')
+                self.server.response = yield
+                self._send_tagged(tag, 'OK', 'okay')
+        client, server = self._setup(UTF8AppendServer)
+        self.assertEqual(client._encoding, 'ascii')
+        code, _ = client.authenticate('MYAUTH', lambda x: b'fake')
+        self.assertEqual(code, 'OK')
+        self.assertEqual(server.response, b'ZmFrZQ==\r\n')  # b64 encoded 'fake'
+        code, _ = client.enable('UTF8=ACCEPT')
+        self.assertEqual(code, 'OK')
+        self.assertEqual(client._encoding, 'utf-8')
+        msg_string = 'Subject: üñí©öðé'
+        typ, data = client.append(None, None, None, msg_string.encode('utf-8'))
+        self.assertEqual(typ, 'OK')
+        self.assertEqual(server.response,
+            ('UTF8 (%s)\r\n' % msg_string).encode('utf-8'))
+
+    def test_search_disallows_charset_in_utf8_mode(self):
+        class UTF8Server(SimpleIMAPHandler):
+            capabilities = 'AUTH ENABLE UTF8=ACCEPT'
+            def cmd_ENABLE(self, tag, args):
+                self._send_tagged(tag, 'OK', 'ENABLE successful')
+            def cmd_AUTHENTICATE(self, tag, args):
+                self._send_textline('+')
+                self.server.response = yield
+                self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
+        client, _ = self._setup(UTF8Server)
+        typ, _ = client.authenticate('MYAUTH', lambda x: b'fake')
+        self.assertEqual(typ, 'OK')
+        typ, _ = client.enable('UTF8=ACCEPT')
+        self.assertEqual(typ, 'OK')
+        self.assertTrue(client.utf8_enabled)
+        with self.assertRaisesRegex(imaplib.IMAP4.error, 'charset.*UTF8'):
+            client.search('foo', 'bar')
+
+    def test_bad_auth_name(self):
+        class MyServer(SimpleIMAPHandler):
+            def cmd_AUTHENTICATE(self, tag, args):
+                self._send_tagged(tag, 'NO',
+                    'unrecognized authentication type {}'.format(args[0]))
+        client, _ = self._setup(MyServer)
+        with self.assertRaisesRegex(imaplib.IMAP4.error,
+                'unrecognized authentication type METHOD'):
+            client.authenticate('METHOD', lambda: 1)
+
+    def test_invalid_authentication(self):
+        class MyServer(SimpleIMAPHandler):
+            def cmd_AUTHENTICATE(self, tag, args):
+                self._send_textline('+')
+                self.response = yield
+                self._send_tagged(tag, 'NO', '[AUTHENTICATIONFAILED] invalid')
+        client, _ = self._setup(MyServer)
+        with self.assertRaisesRegex(imaplib.IMAP4.error,
+                r'\[AUTHENTICATIONFAILED\] invalid'):
+            client.authenticate('MYAUTH', lambda x: b'fake')
+
+    def test_valid_authentication_bytes(self):
+        class MyServer(SimpleIMAPHandler):
+            def cmd_AUTHENTICATE(self, tag, args):
+                self._send_textline('+')
+                self.server.response = yield
+                self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
+        client, server = self._setup(MyServer)
+        code, _ = client.authenticate('MYAUTH', lambda x: b'fake')
+        self.assertEqual(code, 'OK')
+        self.assertEqual(server.response, b'ZmFrZQ==\r\n')  # b64 encoded 'fake'
+
+    def test_valid_authentication_plain_text(self):
+        class MyServer(SimpleIMAPHandler):
+            def cmd_AUTHENTICATE(self, tag, args):
+                self._send_textline('+')
+                self.server.response = yield
+                self._send_tagged(tag, 'OK', 'FAKEAUTH successful')
+        client, server = self._setup(MyServer)
+        code, _ = client.authenticate('MYAUTH', lambda x: 'fake')
+        self.assertEqual(code, 'OK')
+        self.assertEqual(server.response, b'ZmFrZQ==\r\n')  # b64 encoded 'fake'
+
+    def test_login_cram_md5_bytes(self):
+        class AuthHandler(SimpleIMAPHandler):
+            capabilities = 'LOGINDISABLED AUTH=CRAM-MD5'
+            def cmd_AUTHENTICATE(self, tag, args):
+                self._send_textline('+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2Uucm'
+                                    'VzdG9uLm1jaS5uZXQ=')
+                r = yield
+                if (r == b'dGltIGYxY2E2YmU0NjRiOWVmYT'
+                         b'FjY2E2ZmZkNmNmMmQ5ZjMy\r\n'):
+                    self._send_tagged(tag, 'OK', 'CRAM-MD5 successful')
+                else:
+                    self._send_tagged(tag, 'NO', 'No access')
+        client, _ = self._setup(AuthHandler)
+        self.assertTrue('AUTH=CRAM-MD5' in client.capabilities)
+        ret, _ = client.login_cram_md5("tim", b"tanstaaftanstaaf")
+        self.assertEqual(ret, "OK")
+
+    def test_login_cram_md5_plain_text(self):
+        class AuthHandler(SimpleIMAPHandler):
+            capabilities = 'LOGINDISABLED AUTH=CRAM-MD5'
+            def cmd_AUTHENTICATE(self, tag, args):
+                self._send_textline('+ PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2Uucm'
+                                    'VzdG9uLm1jaS5uZXQ=')
+                r = yield
+                if (r == b'dGltIGYxY2E2YmU0NjRiOWVmYT'
+                         b'FjY2E2ZmZkNmNmMmQ5ZjMy\r\n'):
+                    self._send_tagged(tag, 'OK', 'CRAM-MD5 successful')
+                else:
+                    self._send_tagged(tag, 'NO', 'No access')
+        client, _ = self._setup(AuthHandler)
+        self.assertTrue('AUTH=CRAM-MD5' in client.capabilities)
+        ret, _ = client.login_cram_md5("tim", "tanstaaftanstaaf")
+        self.assertEqual(ret, "OK")
+
+    def test_aborted_authentication(self):
+        class MyServer(SimpleIMAPHandler):
+            def cmd_AUTHENTICATE(self, tag, args):
+                self._send_textline('+')
+                self.response = yield
+                if self.response == b'*\r\n':
+                    self._send_tagged(
+                        tag,
+                        'NO',
+                        '[AUTHENTICATIONFAILED] aborted')
+                else:
+                    self._send_tagged(tag, 'OK', 'MYAUTH successful')
+        client, _ = self._setup(MyServer)
+        with self.assertRaisesRegex(imaplib.IMAP4.error,
+                r'\[AUTHENTICATIONFAILED\] aborted'):
+            client.authenticate('MYAUTH', lambda x: None)
+
+    @mock.patch('imaplib._MAXLINE', 10)
+    def test_linetoolong(self):
+        class TooLongHandler(SimpleIMAPHandler):
+            def handle(self):
+                # send response line longer than the limit set in the next line
+                self.wfile.write(b'* OK ' + 11 * b'x' + b'\r\n')
+        _, server = self._setup(TooLongHandler, connect=False)
+        with self.assertRaisesRegex(imaplib.IMAP4.error,
+                'got more than 10 bytes'):
+            self.imap_class(*server.server_address)
+
+    def test_simple_with_statement(self):
+        _, server = self._setup(SimpleIMAPHandler, connect=False)
+        with self.imap_class(*server.server_address):
+            pass
+
+    def test_with_statement(self):
+        _, server = self._setup(SimpleIMAPHandler, connect=False)
+        with self.imap_class(*server.server_address) as imap:
+            imap.login('user', 'pass')
+            self.assertEqual(server.logged, 'user')
+        self.assertIsNone(server.logged)
+
+    def test_with_statement_logout(self):
+        # It is legal to log out explicitly inside the with block
+        _, server = self._setup(SimpleIMAPHandler, connect=False)
+        with self.imap_class(*server.server_address) as imap:
+            imap.login('user', 'pass')
+            self.assertEqual(server.logged, 'user')
+            imap.logout()
+            self.assertIsNone(server.logged)
+        self.assertIsNone(server.logged)
+
+    # command tests
+
+    def test_login(self):
+        client, _ = self._setup(SimpleIMAPHandler)
+        typ, data = client.login('user', 'pass')
+        self.assertEqual(typ, 'OK')
+        self.assertEqual(data[0], b'LOGIN completed')
+        self.assertEqual(client.state, 'AUTH')
+
+    def test_logout(self):
+        client, _ = self._setup(SimpleIMAPHandler)
+        typ, data = client.login('user', 'pass')
+        self.assertEqual(typ, 'OK')
+        self.assertEqual(data[0], b'LOGIN completed')
+        typ, data = client.logout()
+        self.assertEqual(typ, 'BYE')
+        self.assertEqual(data[0], b'IMAP4ref1 Server logging out')
+        self.assertEqual(client.state, 'LOGOUT')
+
+    def test_lsub(self):
+        class LsubCmd(SimpleIMAPHandler):
+            def cmd_LSUB(self, tag, args):
+                self._send_textline('* LSUB () "." directoryA')
+                return self._send_tagged(tag, 'OK', 'LSUB completed')
+        client, _ = self._setup(LsubCmd)
+        client.login('user', 'pass')
+        typ, data = client.lsub()
+        self.assertEqual(typ, 'OK')
+        self.assertEqual(data[0], b'() "." directoryA')
+
+
+class NewIMAPTests(NewIMAPTestsMixin, unittest.TestCase):
+    imap_class = imaplib.IMAP4
+    server_class = socketserver.TCPServer
+
+
+@unittest.skipUnless(ssl, "SSL not available")
+class NewIMAPSSLTests(NewIMAPTestsMixin, unittest.TestCase):
+    imap_class = imaplib.IMAP4_SSL
+    server_class = SecureTCPServer
+
+    def test_ssl_raises(self):
+        ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+        ssl_context.verify_mode = ssl.CERT_REQUIRED
+        ssl_context.check_hostname = True
+        ssl_context.load_verify_locations(CAFILE)
+
+        with self.assertRaisesRegex(ssl.CertificateError,
+                "hostname '127.0.0.1' doesn't match 'localhost'"):
+            _, server = self._setup(SimpleIMAPHandler)
+            client = self.imap_class(*server.server_address,
+                                     ssl_context=ssl_context)
+            client.shutdown()
+
+    def test_ssl_verified(self):
+        ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+        ssl_context.verify_mode = ssl.CERT_REQUIRED
+        ssl_context.check_hostname = True
+        ssl_context.load_verify_locations(CAFILE)
+
+        _, server = self._setup(SimpleIMAPHandler)
+        client = self.imap_class("localhost", server.server_address[1],
+                                 ssl_context=ssl_context)
+        client.shutdown()
+
 class ThreadedNetworkedTests(unittest.TestCase):
     server_class = socketserver.TCPServer
     imap_class = imaplib.IMAP4
index 706c3e4..c112ca7 100644 (file)
@@ -5,6 +5,7 @@ import unittest
 
 from .. import util
 
+importlib = util.import_importlib('importlib')
 machinery = util.import_importlib('importlib.machinery')
 
 
@@ -12,7 +13,7 @@ machinery = util.import_importlib('importlib.machinery')
 
 @unittest.skipIf(util.EXTENSIONS.filename is None, '_testcapi not available')
 @util.case_insensitive_tests
-class ExtensionModuleCaseSensitivityTest:
+class ExtensionModuleCaseSensitivityTest(util.CASEOKTestBase):
 
     def find_module(self):
         good_name = util.EXTENSIONS.name
@@ -26,25 +27,22 @@ class ExtensionModuleCaseSensitivityTest:
     def test_case_sensitive(self):
         with support.EnvironmentVarGuard() as env:
             env.unset('PYTHONCASEOK')
-            if b'PYTHONCASEOK' in _bootstrap_external._os.environ:
-                self.skipTest('os.environ changes not reflected in '
-                              '_os.environ')
+            self.caseok_env_changed(should_exist=False)
             loader = self.find_module()
             self.assertIsNone(loader)
 
     def test_case_insensitivity(self):
         with support.EnvironmentVarGuard() as env:
             env.set('PYTHONCASEOK', '1')
-            if b'PYTHONCASEOK' not in _bootstrap_external._os.environ:
-                self.skipTest('os.environ changes not reflected in '
-                              '_os.environ')
+            self.caseok_env_changed(should_exist=True)
             loader = self.find_module()
             self.assertTrue(hasattr(loader, 'load_module'))
 
 
 (Frozen_ExtensionCaseSensitivity,
  Source_ExtensionCaseSensitivity
- ) = util.test_both(ExtensionModuleCaseSensitivityTest, machinery=machinery)
+ ) = util.test_both(ExtensionModuleCaseSensitivityTest, importlib=importlib,
+                    machinery=machinery)
 
 
 if __name__ == '__main__':
index 154a793..8d20040 100644 (file)
@@ -212,6 +212,15 @@ class MultiPhaseExtensionModuleTests(abc.LoaderTests):
         self.assertNotEqual(type(mod), type(unittest))
         self.assertEqual(mod.three, 3)
 
+    # issue 27782
+    def test_nonmodule_with_methods(self):
+        '''Test creating a non-module object with methods defined'''
+        name = self.name + '_nonmodule_with_methods'
+        mod = self.load_module_by_name(name)
+        self.assertNotEqual(type(mod), type(unittest))
+        self.assertEqual(mod.three, 3)
+        self.assertEqual(mod.bar(10, 1), 9)
+
     def test_null_slots(self):
         '''Test that NULL slots aren't a problem'''
         name = self.name + '_null_slots'
index c452cdd..5a41e89 100644 (file)
@@ -76,7 +76,6 @@ class CallSignature:
                 self.__import__(mod_name)
                 assert len(log) == 1
                 args = log[0][0]
-                kwargs = log[0][1]
                 # Assuming all arguments are positional.
                 self.assertEqual(args[0], mod_name)
                 self.assertIsNone(args[1])
index c274b38..34b86cd 100644 (file)
@@ -11,7 +11,7 @@ import unittest
 
 
 @util.case_insensitive_tests
-class CaseSensitivityTest:
+class CaseSensitivityTest(util.CASEOKTestBase):
 
     """PEP 235 dictates that on case-preserving, case-insensitive file systems
     that imports are case-sensitive unless the PYTHONCASEOK environment
@@ -42,9 +42,7 @@ class CaseSensitivityTest:
     def test_sensitive(self):
         with test_support.EnvironmentVarGuard() as env:
             env.unset('PYTHONCASEOK')
-            if b'PYTHONCASEOK' in self.importlib._bootstrap_external._os.environ:
-                self.skipTest('os.environ changes not reflected in '
-                              '_os.environ')
+            self.caseok_env_changed(should_exist=False)
             sensitive, insensitive = self.sensitivity_test()
             self.assertIsNotNone(sensitive)
             self.assertIn(self.name, sensitive.get_filename(self.name))
@@ -53,9 +51,7 @@ class CaseSensitivityTest:
     def test_insensitive(self):
         with test_support.EnvironmentVarGuard() as env:
             env.set('PYTHONCASEOK', '1')
-            if b'PYTHONCASEOK' not in self.importlib._bootstrap_external._os.environ:
-                self.skipTest('os.environ changes not reflected in '
-                              '_os.environ')
+            self.caseok_env_changed(should_exist=True)
             sensitive, insensitive = self.sensitivity_test()
             self.assertIsNotNone(sensitive)
             self.assertIn(self.name, sensitive.get_filename(self.name))
index 774b7a4..cc383c2 100644 (file)
@@ -1,6 +1,8 @@
 import importlib
 from importlib import abc
 from importlib import util
+import sys
+import types
 import unittest
 
 from . import util as test_util
@@ -122,12 +124,20 @@ class LazyLoaderTests(unittest.TestCase):
         self.assertFalse(hasattr(module, '__name__'))
 
     def test_module_substitution_error(self):
-        source_code = 'import sys; sys.modules[__name__] = 42'
-        module = self.new_module(source_code)
         with test_util.uncache(TestingImporter.module_name):
-            with self.assertRaises(ValueError):
+            fresh_module = types.ModuleType(TestingImporter.module_name)
+            sys.modules[TestingImporter.module_name] = fresh_module
+            module = self.new_module()
+            with self.assertRaisesRegex(ValueError, "substituted"):
                 module.__name__
 
+    def test_module_already_in_sys(self):
+        with test_util.uncache(TestingImporter.module_name):
+            module = self.new_module()
+            sys.modules[TestingImporter.module_name] = module
+            # Force the load; just care that no exception is raised.
+            module.__name__
+
 
 if __name__ == '__main__':
     unittest.main()
index 69466b2..41ca333 100644 (file)
@@ -372,7 +372,7 @@ class ResolveNameTests:
         # bacon
         self.assertEqual('bacon', self.util.resolve_name('bacon', None))
 
-    def test_aboslute_within_package(self):
+    def test_absolute_within_package(self):
         # bacon in spam
         self.assertEqual('bacon', self.util.resolve_name('bacon', 'spam'))
 
index ce20377..64e039e 100644 (file)
@@ -266,7 +266,6 @@ class mock_spec(_ImporterMock):
             module = self.modules[fullname]
         except KeyError:
             return None
-        is_package = hasattr(module, '__path__')
         spec = util.spec_from_file_location(
                 fullname, module.__file__, loader=self,
                 submodule_search_locations=getattr(module, '__path__', None))
@@ -378,3 +377,12 @@ def mock_path_hook(*entries, importer):
             raise ImportError
         return importer
     return hook
+
+
+class CASEOKTestBase:
+
+    def caseok_env_changed(self, *, should_exist):
+        possibilities = b'PYTHONCASEOK', 'PYTHONCASEOK'
+        if any(x in self.importlib._bootstrap_external._os.environ
+                    for x in possibilities) != should_exist:
+            self.skipTest('os.environ changes not reflected in _os.environ')
index 671e05a..d33de9e 100644 (file)
@@ -391,6 +391,11 @@ class TestRetrievingSourceCode(GetSourceBase):
         # Check filename override
         self.assertEqual(inspect.getmodule(None, modfile), mod)
 
+    def test_getframeinfo_get_first_line(self):
+        frame_info = inspect.getframeinfo(self.fodderModule.fr, 50)
+        self.assertEqual(frame_info.code_context[0], "# line 1\n")
+        self.assertEqual(frame_info.code_context[1], "'A module docstring.'\n")
+
     def test_getsource(self):
         self.assertSourceEqual(git.abuse, 29, 39)
         self.assertSourceEqual(mod.StupidGit, 21, 51)
index 000b525..5111882 100644 (file)
@@ -3135,6 +3135,7 @@ class TextIOWrapperTest(unittest.TestCase):
             """.format(iomod=iomod, kwargs=kwargs)
         return assert_python_ok("-c", code)
 
+    @support.requires_type_collecting
     def test_create_at_shutdown_without_encoding(self):
         rc, out, err = self._check_create_at_shutdown()
         if err:
@@ -3144,6 +3145,7 @@ class TextIOWrapperTest(unittest.TestCase):
         else:
             self.assertEqual("ok", out.decode().strip())
 
+    @support.requires_type_collecting
     def test_create_at_shutdown_with_encoding(self):
         rc, out, err = self._check_create_at_shutdown(encoding='utf-8',
                                                       errors='strict')
index be62fad..91ae8d8 100644 (file)
@@ -734,7 +734,7 @@ class IpaddrUnitTest(unittest.TestCase):
         self.assertEqual("IPv6Interface('::1/128')",
                          repr(ipaddress.IPv6Interface('::1')))
 
-    # issue #16531: constructing IPv4Network from a (address, mask) tuple
+    # issue #16531: constructing IPv4Network from an (address, mask) tuple
     def testIPv4Tuple(self):
         # /32
         ip = ipaddress.IPv4Address('192.0.2.1')
@@ -797,7 +797,7 @@ class IpaddrUnitTest(unittest.TestCase):
         self.assertEqual(ipaddress.IPv4Interface((3221225985, 24)),
                          ipaddress.IPv4Interface('192.0.2.1/24'))
 
-    # issue #16531: constructing IPv6Network from a (address, mask) tuple
+    # issue #16531: constructing IPv6Network from an (address, mask) tuple
     def testIPv6Tuple(self):
         # /128
         ip = ipaddress.IPv6Address('2001:db8::')
@@ -1262,7 +1262,7 @@ class IpaddrUnitTest(unittest.TestCase):
         ip4 = ipaddress.IPv4Address('1.1.1.3')
         ip5 = ipaddress.IPv4Address('1.1.1.4')
         ip6 = ipaddress.IPv4Address('1.1.1.0')
-        # check that addreses are subsumed properly.
+        # check that addresses are subsumed properly.
         collapsed = ipaddress.collapse_addresses(
             [ip1, ip2, ip3, ip4, ip5, ip6])
         self.assertEqual(list(collapsed),
@@ -1276,7 +1276,7 @@ class IpaddrUnitTest(unittest.TestCase):
         ip4 = ipaddress.IPv4Address('1.1.1.3')
         #ip5 = ipaddress.IPv4Interface('1.1.1.4/30')
         #ip6 = ipaddress.IPv4Interface('1.1.1.4/30')
-        # check that addreses are subsumed properly.
+        # check that addresses are subsumed properly.
         collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3, ip4])
         self.assertEqual(list(collapsed),
                          [ipaddress.IPv4Network('1.1.1.0/30')])
@@ -1290,7 +1290,7 @@ class IpaddrUnitTest(unittest.TestCase):
         # stored in no particular order b/c we want CollapseAddr to call
         # [].sort
         ip6 = ipaddress.IPv4Network('1.1.0.0/22')
-        # check that addreses are subsumed properly.
+        # check that addresses are subsumed properly.
         collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3, ip4, ip5,
                                                      ip6])
         self.assertEqual(list(collapsed),
index f940852..e054303 100644 (file)
@@ -184,6 +184,19 @@ class TestBasicOps(unittest.TestCase):
         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
             self.pickletest(proto, chain('abc', 'def'), compare=list('abcdef'))
 
+    def test_chain_setstate(self):
+        self.assertRaises(TypeError, chain().__setstate__, ())
+        self.assertRaises(TypeError, chain().__setstate__, [])
+        self.assertRaises(TypeError, chain().__setstate__, 0)
+        self.assertRaises(TypeError, chain().__setstate__, ([],))
+        self.assertRaises(TypeError, chain().__setstate__, (iter([]), []))
+        it = chain()
+        it.__setstate__((iter(['abc', 'def']),))
+        self.assertEqual(list(it), ['a', 'b', 'c', 'd', 'e', 'f'])
+        it = chain()
+        it.__setstate__((iter(['abc', 'def']), iter(['ghi'])))
+        self.assertEqual(list(it), ['ghi', 'a', 'b', 'c', 'd', 'e', 'f'])
+
     def test_combinations(self):
         self.assertRaises(TypeError, combinations, 'abc')       # missing r argument
         self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
@@ -511,12 +524,18 @@ class TestBasicOps(unittest.TestCase):
         self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
         self.assertRaises(TypeError, count, 2, 3, 4)
         self.assertRaises(TypeError, count, 'a')
-        self.assertEqual(list(islice(count(maxsize-5), 10)),
+        self.assertEqual(take(10, count(maxsize-5)),
                          list(range(maxsize-5, maxsize+5)))
-        self.assertEqual(list(islice(count(-maxsize-5), 10)),
+        self.assertEqual(take(10, count(-maxsize-5)),
                          list(range(-maxsize-5, -maxsize+5)))
-        self.assertEqual(list(islice(count(10, maxsize+5), 3)),
-                         list(range(10, 10+3*(maxsize+5), maxsize+5)))
+        self.assertEqual(take(3, count(3.25)), [3.25, 4.25, 5.25])
+        self.assertEqual(take(3, count(3.25-4j)), [3.25-4j, 4.25-4j, 5.25-4j])
+        self.assertEqual(take(3, count(Decimal('1.1'))),
+                         [Decimal('1.1'), Decimal('2.1'), Decimal('3.1')])
+        self.assertEqual(take(3, count(Fraction(2, 3))),
+                         [Fraction(2, 3), Fraction(5, 3), Fraction(8, 3)])
+        BIGINT = 1<<1000
+        self.assertEqual(take(3, count(BIGINT)), [BIGINT, BIGINT+1, BIGINT+2])
         c = count(3)
         self.assertEqual(repr(c), 'count(3)')
         next(c)
@@ -524,8 +543,10 @@ class TestBasicOps(unittest.TestCase):
         c = count(-9)
         self.assertEqual(repr(c), 'count(-9)')
         next(c)
-        self.assertEqual(repr(count(10.25)), 'count(10.25)')
         self.assertEqual(next(c), -8)
+        self.assertEqual(repr(count(10.25)), 'count(10.25)')
+        self.assertEqual(repr(count(10.0)), 'count(10.0)')
+        self.assertEqual(type(next(count(10.0))), float)
         for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
             # Test repr
             r1 = repr(count(i))
@@ -549,16 +570,22 @@ class TestBasicOps(unittest.TestCase):
                          [('a', 2), ('b', 5), ('c', 8)])
         self.assertEqual(lzip('abc',count(step=-1)),
                          [('a', 0), ('b', -1), ('c', -2)])
+        self.assertRaises(TypeError, count, 'a', 'b')
         self.assertEqual(lzip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
         self.assertEqual(lzip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
         self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
         self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
         self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
+        self.assertEqual(take(3, count(10, maxsize+5)),
+                         list(range(10, 10+3*(maxsize+5), maxsize+5)))
+        self.assertEqual(take(3, count(2, 1.25)), [2, 3.25, 4.5])
         self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
         self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
                          [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
         self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
                          [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
+        BIGINT = 1<<1000
+        self.assertEqual(take(3, count(step=BIGINT)), [0, BIGINT, 2*BIGINT])
         self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
         c = count(3, 5)
         self.assertEqual(repr(c), 'count(3, 5)')
@@ -576,6 +603,10 @@ class TestBasicOps(unittest.TestCase):
         self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
         self.assertEqual(repr(count(10.5, 1)), 'count(10.5)')           # suppress step=1 when it's an int
         self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)')   # do show float values lilke 1.0
+        self.assertEqual(repr(count(10, 1.00)), 'count(10, 1.0)')
+        c = count(10, 1.0)
+        self.assertEqual(type(next(c)), int)
+        self.assertEqual(type(next(c)), float)
         for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
             for j in  (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 1, 10, sys.maxsize-5, sys.maxsize+5):
                 # Test repr
@@ -613,6 +644,25 @@ class TestBasicOps(unittest.TestCase):
         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
             self.pickletest(proto, cycle('abc'))
 
+    def test_cycle_setstate(self):
+        self.assertRaises(TypeError, cycle('').__setstate__, ())
+        self.assertRaises(TypeError, cycle('').__setstate__, [])
+        self.assertRaises(TypeError, cycle('').__setstate__, 0)
+        self.assertRaises(TypeError, cycle('').__setstate__, ([],))
+        self.assertRaises(TypeError, cycle('').__setstate__, ((), 0))
+        it = cycle('abc')
+        it.__setstate__((['de', 'fg'], 0))
+        self.assertEqual(list(islice(it, 15)),
+                         ['a', 'b', 'c', 'de', 'fg',
+                          'a', 'b', 'c', 'de', 'fg',
+                          'a', 'b', 'c', 'de', 'fg'])
+        it = cycle('abc')
+        it.__setstate__((['de', 'fg'], 1))
+        self.assertEqual(list(islice(it, 15)),
+                         ['a', 'b', 'c', 'de', 'fg',
+                          'de', 'fg', 'de', 'fg', 'de',
+                          'fg', 'de', 'fg', 'de', 'fg'])
+
     def test_groupby(self):
         # Check whether it accepts arguments correctly
         self.assertEqual([], list(groupby([])))
index cc83b45..fdafeb6 100644 (file)
@@ -35,7 +35,7 @@ class TestDecode:
         self.assertEqual(self.loads(s, object_pairs_hook=OrderedDict,
                                     object_hook=lambda x: None),
                          OrderedDict(p))
-        # check that empty objects literals work (see #17368)
+        # check that empty object literals work (see #17368)
         self.assertEqual(self.loads('{}', object_pairs_hook=OrderedDict),
                          OrderedDict())
         self.assertEqual(self.loads('{"empty": {}}',
index 84fd8b5..0e70ccd 100644 (file)
@@ -1,4 +1,4 @@
-# Copyright 2001-2014 by Vinay Sajip. All Rights Reserved.
+# Copyright 2001-2016 by Vinay Sajip. All Rights Reserved.
 #
 # Permission to use, copy, modify, and distribute this software and its
 # documentation for any purpose and without fee is hereby granted,
@@ -16,7 +16,7 @@
 
 """Test harness for the logging module. Run all tests.
 
-Copyright (C) 2001-2014 Vinay Sajip. All Rights Reserved.
+Copyright (C) 2001-2016 Vinay Sajip. All Rights Reserved.
 """
 
 import logging
@@ -3022,6 +3022,86 @@ class QueueHandlerTest(BaseTest):
         self.assertFalse(handler.matches(levelno=logging.ERROR, message='5'))
         self.assertTrue(handler.matches(levelno=logging.CRITICAL, message='6'))
 
+if hasattr(logging.handlers, 'QueueListener'):
+    import multiprocessing
+    from unittest.mock import patch
+
+    class QueueListenerTest(BaseTest):
+        """
+        Tests based on patch submitted for issue #27930. Ensure that
+        QueueListener handles all log messages.
+        """
+
+        repeat = 20
+
+        @staticmethod
+        def setup_and_log(log_queue, ident):
+            """
+            Creates a logger with a QueueHandler that logs to a queue read by a
+            QueueListener. Starts the listener, logs five messages, and stops
+            the listener.
+            """
+            logger = logging.getLogger('test_logger_with_id_%s' % ident)
+            logger.setLevel(logging.DEBUG)
+            handler = logging.handlers.QueueHandler(log_queue)
+            logger.addHandler(handler)
+            listener = logging.handlers.QueueListener(log_queue)
+            listener.start()
+
+            logger.info('one')
+            logger.info('two')
+            logger.info('three')
+            logger.info('four')
+            logger.info('five')
+
+            listener.stop()
+            logger.removeHandler(handler)
+            handler.close()
+
+        @patch.object(logging.handlers.QueueListener, 'handle')
+        def test_handle_called_with_queue_queue(self, mock_handle):
+            for i in range(self.repeat):
+                log_queue = queue.Queue()
+                self.setup_and_log(log_queue, '%s_%s' % (self.id(), i))
+            self.assertEqual(mock_handle.call_count, 5 * self.repeat,
+                             'correct number of handled log messages')
+
+        @support.requires_multiprocessing_queue
+        @patch.object(logging.handlers.QueueListener, 'handle')
+        def test_handle_called_with_mp_queue(self, mock_handle):
+            for i in range(self.repeat):
+                log_queue = multiprocessing.Queue()
+                self.setup_and_log(log_queue, '%s_%s' % (self.id(), i))
+            self.assertEqual(mock_handle.call_count, 5 * self.repeat,
+                             'correct number of handled log messages')
+
+        @staticmethod
+        def get_all_from_queue(log_queue):
+            try:
+                while True:
+                    yield log_queue.get_nowait()
+            except queue.Empty:
+                return []
+
+        @support.requires_multiprocessing_queue
+        def test_no_messages_in_queue_after_stop(self):
+            """
+            Five messages are logged then the QueueListener is stopped. This
+            test then gets everything off the queue. Failure of this test
+            indicates that messages were not registered on the queue until
+            _after_ the QueueListener stopped.
+            """
+            for i in range(self.repeat):
+                queue = multiprocessing.Queue()
+                self.setup_and_log(queue, '%s_%s' %(self.id(), i))
+                # time.sleep(1)
+                items = list(self.get_all_from_queue(queue))
+                expected = [[], [logging.handlers.QueueListener._sentinel]]
+                self.assertIn(items, expected,
+                              'Found unexpected messages in queue: %s' % (
+                                    [m.msg if isinstance(m, logging.LogRecord)
+                                     else m for m in items]))
+
 
 ZERO = datetime.timedelta(0)
 
@@ -3389,6 +3469,7 @@ class ModuleLevelMiscTest(BaseTest):
         logging.setLoggerClass(logging.Logger)
         self.assertEqual(logging.getLoggerClass(), logging.Logger)
 
+    @support.requires_type_collecting
     def test_logging_at_shutdown(self):
         # Issue #20037
         code = """if 1:
@@ -4165,7 +4246,7 @@ class NTEventLogHandlerTest(BaseTest):
 # first and restore it at the end.
 @support.run_with_locale('LC_ALL', '')
 def test_main():
-    support.run_unittest(
+    tests = [
         BuiltinLevelsTest, BasicFilterTest, CustomLevelsAndFiltersTest,
         HandlerTest, MemoryHandlerTest, ConfigFileTest, SocketHandlerTest,
         DatagramHandlerTest, MemoryTest, EncodingTest, WarningsTest,
@@ -4176,7 +4257,11 @@ def test_main():
         RotatingFileHandlerTest,  LastResortTest, LogRecordTest,
         ExceptionTest, SysLogHandlerTest, HTTPHandlerTest,
         NTEventLogHandlerTest, TimedRotatingFileHandlerTest,
-        UnixSocketHandlerTest, UnixDatagramHandlerTest, UnixSysLogHandlerTest)
+        UnixSocketHandlerTest, UnixDatagramHandlerTest, UnixSysLogHandlerTest,
+    ]
+    if hasattr(logging.handlers, 'QueueListener'):
+        tests.append(QueueListenerTest)
+    support.run_unittest(*tests)
 
 if __name__ == "__main__":
     test_main()
index b2d008b..4b2d81c 100644 (file)
@@ -967,7 +967,7 @@ class LongTest(unittest.TestCase):
             self.assertIs(type(got), int)
 
         # bad second argument
-        bad_exponents = ('brian', 2.0, 0j, None)
+        bad_exponents = ('brian', 2.0, 0j)
         for e in bad_exponents:
             self.assertRaises(TypeError, round, 3, e)
 
index 6c698e2..b69da06 100644 (file)
@@ -136,6 +136,21 @@ class CompressorDecompressorTestCase(unittest.TestCase):
         self.assertTrue(lzd.eof)
         self.assertEqual(lzd.unused_data, b"")
 
+    def test_decompressor_chunks_empty(self):
+        lzd = LZMADecompressor()
+        out = []
+        for i in range(0, len(COMPRESSED_XZ), 10):
+            self.assertFalse(lzd.eof)
+            out.append(lzd.decompress(b''))
+            out.append(lzd.decompress(b''))
+            out.append(lzd.decompress(b''))
+            out.append(lzd.decompress(COMPRESSED_XZ[i:i+10]))
+        out = b"".join(out)
+        self.assertEqual(out, INPUT)
+        self.assertEqual(lzd.check, lzma.CHECK_CRC64)
+        self.assertTrue(lzd.eof)
+        self.assertEqual(lzd.unused_data, b"")
+
     def test_decompressor_chunks_maxsize(self):
         lzd = LZMADecompressor()
         max_length = 100
@@ -246,6 +261,13 @@ class CompressorDecompressorTestCase(unittest.TestCase):
         lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_1)
         self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_XZ)
 
+    def test_decompressor_bug_28275(self):
+        # Test coverage for Issue 28275
+        lzd = LZMADecompressor()
+        self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_RAW_1)
+        # Previously, a second call could crash due to internal inconsistency
+        self.assertRaises(LZMAError, lzd.decompress, COMPRESSED_RAW_1)
+
     # Test that LZMACompressor->LZMADecompressor preserves the input data.
 
     def test_roundtrip_xz(self):
@@ -266,6 +288,16 @@ class CompressorDecompressorTestCase(unittest.TestCase):
         lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
         self._test_decompressor(lzd, cdata, lzma.CHECK_NONE)
 
+    def test_roundtrip_raw_empty(self):
+        lzc = LZMACompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
+        cdata = lzc.compress(INPUT)
+        cdata += lzc.compress(b'')
+        cdata += lzc.compress(b'')
+        cdata += lzc.compress(b'')
+        cdata += lzc.flush()
+        lzd = LZMADecompressor(lzma.FORMAT_RAW, filters=FILTERS_RAW_4)
+        self._test_decompressor(lzd, cdata, lzma.CHECK_NONE)
+
     def test_roundtrip_chunks(self):
         lzc = LZMACompressor()
         cdata = []
@@ -276,6 +308,19 @@ class CompressorDecompressorTestCase(unittest.TestCase):
         lzd = LZMADecompressor()
         self._test_decompressor(lzd, cdata, lzma.CHECK_CRC64)
 
+    def test_roundtrip_empty_chunks(self):
+        lzc = LZMACompressor()
+        cdata = []
+        for i in range(0, len(INPUT), 10):
+            cdata.append(lzc.compress(INPUT[i:i+10]))
+            cdata.append(lzc.compress(b''))
+            cdata.append(lzc.compress(b''))
+            cdata.append(lzc.compress(b''))
+        cdata.append(lzc.flush())
+        cdata = b"".join(cdata)
+        lzd = LZMADecompressor()
+        self._test_decompressor(lzd, cdata, lzma.CHECK_CRC64)
+
     # LZMADecompressor intentionally does not handle concatenated streams.
 
     def test_decompressor_multistream(self):
index 22b2fcc..a85c691 100644 (file)
@@ -1,6 +1,7 @@
 import mailcap
 import os
 import shutil
+import copy
 import test.support
 import unittest
 
@@ -14,43 +15,55 @@ MAILCAPDICT = {
         [{'compose': 'moviemaker %s',
           'x11-bitmap': '"/usr/lib/Zmail/bitmaps/movie.xbm"',
           'description': '"Movie"',
-          'view': 'movieplayer %s'}],
+          'view': 'movieplayer %s',
+          'lineno': 4}],
     'application/*':
         [{'copiousoutput': '',
-          'view': 'echo "This is \\"%t\\" but        is 50 \\% Greek to me" \\; cat %s'}],
+          'view': 'echo "This is \\"%t\\" but        is 50 \\% Greek to me" \\; cat %s',
+          'lineno': 5}],
     'audio/basic':
         [{'edit': 'audiocompose %s',
           'compose': 'audiocompose %s',
           'description': '"An audio fragment"',
-          'view': 'showaudio %s'}],
+          'view': 'showaudio %s',
+          'lineno': 6}],
     'video/mpeg':
-        [{'view': 'mpeg_play %s'}],
+        [{'view': 'mpeg_play %s', 'lineno': 13}],
     'application/postscript':
-        [{'needsterminal': '', 'view': 'ps-to-terminal %s'},
-         {'compose': 'idraw %s', 'view': 'ps-to-terminal %s'}],
+        [{'needsterminal': '', 'view': 'ps-to-terminal %s', 'lineno': 1},
+         {'compose': 'idraw %s', 'view': 'ps-to-terminal %s', 'lineno': 2}],
     'application/x-dvi':
-        [{'view': 'xdvi %s'}],
+        [{'view': 'xdvi %s', 'lineno': 3}],
     'message/external-body':
         [{'composetyped': 'extcompose %s',
           'description': '"A reference to data stored in an external location"',
           'needsterminal': '',
-          'view': 'showexternal %s %{access-type} %{name} %{site}     %{directory} %{mode} %{server}'}],
+          'view': 'showexternal %s %{access-type} %{name} %{site}     %{directory} %{mode} %{server}',
+          'lineno': 10}],
     'text/richtext':
         [{'test': 'test "`echo     %{charset} | tr \'[A-Z]\' \'[a-z]\'`"  = iso-8859-8',
           'copiousoutput': '',
-          'view': 'shownonascii iso-8859-8 -e richtext -p %s'}],
+          'view': 'shownonascii iso-8859-8 -e richtext -p %s',
+          'lineno': 11}],
     'image/x-xwindowdump':
-        [{'view': 'display %s'}],
+        [{'view': 'display %s', 'lineno': 9}],
     'audio/*':
-        [{'view': '/usr/local/bin/showaudio %t'}],
+        [{'view': '/usr/local/bin/showaudio %t', 'lineno': 7}],
     'video/*':
-        [{'view': 'animate %s'}],
+        [{'view': 'animate %s', 'lineno': 12}],
     'application/frame':
-        [{'print': '"cat %s | lp"', 'view': 'showframe %s'}],
+        [{'print': '"cat %s | lp"', 'view': 'showframe %s', 'lineno': 0}],
     'image/rgb':
-        [{'view': 'display %s'}]
+        [{'view': 'display %s', 'lineno': 8}]
 }
 
+# For backwards compatibility, readmailcapfile() and lookup() still support
+# the old version of mailcapdict without line numbers.
+MAILCAPDICT_DEPRECATED = copy.deepcopy(MAILCAPDICT)
+for entry_list in MAILCAPDICT_DEPRECATED.values():
+    for entry in entry_list:
+        entry.pop('lineno')
+
 
 class HelperFunctionTest(unittest.TestCase):
 
@@ -76,12 +89,14 @@ class HelperFunctionTest(unittest.TestCase):
     def test_readmailcapfile(self):
         # Test readmailcapfile() using test file. It should match MAILCAPDICT.
         with open(MAILCAPFILE, 'r') as mcf:
-            d = mailcap.readmailcapfile(mcf)
-        self.assertDictEqual(d, MAILCAPDICT)
+            with self.assertWarns(DeprecationWarning):
+                d = mailcap.readmailcapfile(mcf)
+        self.assertDictEqual(d, MAILCAPDICT_DEPRECATED)
 
     def test_lookup(self):
         # Test without key
-        expected = [{'view': 'mpeg_play %s'}, {'view': 'animate %s'}]
+        expected = [{'view': 'animate %s', 'lineno': 12},
+                    {'view': 'mpeg_play %s', 'lineno': 13}]
         actual = mailcap.lookup(MAILCAPDICT, 'video/mpeg')
         self.assertListEqual(expected, actual)
 
@@ -90,10 +105,16 @@ class HelperFunctionTest(unittest.TestCase):
         expected = [{'edit': 'audiocompose %s',
                      'compose': 'audiocompose %s',
                      'description': '"An audio fragment"',
-                     'view': 'showaudio %s'}]
+                     'view': 'showaudio %s',
+                     'lineno': 6}]
         actual = mailcap.lookup(MAILCAPDICT, 'audio/basic', key)
         self.assertListEqual(expected, actual)
 
+        # Test on user-defined dicts without line numbers
+        expected = [{'view': 'mpeg_play %s'}, {'view': 'animate %s'}]
+        actual = mailcap.lookup(MAILCAPDICT_DEPRECATED, 'video/mpeg')
+        self.assertListEqual(expected, actual)
+
     def test_subst(self):
         plist = ['id=1', 'number=2', 'total=3']
         # test case: ([field, MIMEtype, filename, plist=[]], <expected string>)
@@ -152,14 +173,16 @@ class FindmatchTest(unittest.TestCase):
             'edit': 'audiocompose %s',
             'compose': 'audiocompose %s',
             'description': '"An audio fragment"',
-            'view': 'showaudio %s'
+            'view': 'showaudio %s',
+            'lineno': 6
         }
-        audio_entry = {"view": "/usr/local/bin/showaudio %t"}
-        video_entry = {'view': 'animate %s'}
+        audio_entry = {"view": "/usr/local/bin/showaudio %t", 'lineno': 7}
+        video_entry = {'view': 'animate %s', 'lineno': 12}
         message_entry = {
             'composetyped': 'extcompose %s',
             'description': '"A reference to data stored in an external location"', 'needsterminal': '',
-            'view': 'showexternal %s %{access-type} %{name} %{site}     %{directory} %{mode} %{server}'
+            'view': 'showexternal %s %{access-type} %{name} %{site}     %{directory} %{mode} %{server}',
+            'lineno': 10,
         }
 
         # test case: (findmatch args, findmatch keyword args, expected output)
@@ -169,7 +192,7 @@ class FindmatchTest(unittest.TestCase):
         cases = [
             ([{}, "video/mpeg"], {}, (None, None)),
             ([c, "foo/bar"], {}, (None, None)),
-            ([c, "video/mpeg"], {}, ('mpeg_play /dev/null', {'view': 'mpeg_play %s'})),
+            ([c, "video/mpeg"], {}, ('animate /dev/null', video_entry)),
             ([c, "audio/basic", "edit"], {}, ("audiocompose /dev/null", audio_basic_entry)),
             ([c, "audio/basic", "compose"], {}, ("audiocompose /dev/null", audio_basic_entry)),
             ([c, "audio/basic", "description"], {}, ('"An audio fragment"', audio_basic_entry)),
index 6c7b99d..a379a6a 100644 (file)
@@ -1254,8 +1254,8 @@ class IsCloseTests(unittest.TestCase):
                                              (1.0e200, .999999999999999e200)]
         self.assertAllNotClose(zero_tolerance_not_close_examples, rel_tol=0.0)
 
-    def test_assymetry(self):
-        # test the assymetry example from PEP 485
+    def test_asymmetry(self):
+        # test the asymmetry example from PEP 485
         self.assertAllClose([(9, 10), (10, 9)], rel_tol=0.1)
 
     def test_integers(self):
index b365d84..f3f70cc 100644 (file)
@@ -713,6 +713,21 @@ class MmapTests(unittest.TestCase):
         gc_collect()
         self.assertIs(wr(), None)
 
+    @unittest.skipIf(os.name == 'nt', 'cannot resize anonymous mmaps on Windows')
+    def test_resize_past_pos(self):
+        m = mmap.mmap(-1, 8192)
+        self.addCleanup(m.close)
+        m.read(5000)
+        try:
+            m.resize(4096)
+        except SystemError:
+            self.skipTest("resizing not supported")
+        self.assertEqual(m.read(14), b'')
+        self.assertRaises(ValueError, m.read_byte)
+        self.assertRaises(ValueError, m.write_byte, 42)
+        self.assertRaises(ValueError, m.write, b'abc')
+
+
 class LargeMmapTests(unittest.TestCase):
 
     def setUp(self):
index ea6e897..6d0d594 100644 (file)
@@ -1,7 +1,7 @@
 # Test the module type
 import unittest
 import weakref
-from test.support import gc_collect
+from test.support import gc_collect, requires_type_collecting
 from test.support.script_helper import assert_python_ok
 
 import sys
@@ -101,6 +101,7 @@ class ModuleTests(unittest.TestCase):
         gc_collect()
         self.assertEqual(f().__dict__["bar"], 4)
 
+    @requires_type_collecting
     def test_clear_dict_in_ref_cycle(self):
         destroyed = []
         m = ModuleType("foo")
@@ -214,6 +215,7 @@ a = A(destroyed)"""
         self.assertEqual(r[-len(ends_with):], ends_with,
                          '{!r} does not end with {!r}'.format(r, ends_with))
 
+    @requires_type_collecting
     def test_module_finalization_at_shutdown(self):
         # Module globals and builtins should still be available during shutdown
         rc, out, err = assert_python_ok("-c", "from test import final_a")
index 994532b..66ef930 100644 (file)
@@ -132,6 +132,8 @@ class NetworkedNNTPTestsMixin:
         self.assertLessEqual(art_num, last)
         self._check_art_dict(art_dict)
 
+    @unittest.skipIf(True, 'temporarily skipped until a permanent solution'
+                           ' is found for issue #28971')
     def test_over(self):
         resp, count, first, last, name = self.server.group(self.GROUP_NAME)
         start = last - 10
@@ -1465,14 +1467,14 @@ class MockSocketTests(unittest.TestCase):
     def test_service_temporarily_unavailable(self):
         #Test service temporarily unavailable
         class Handler(NNTPv1Handler):
-            welcome = '400 Service temporarily unavilable'
+            welcome = '400 Service temporarily unavailable'
         self.check_constructor_error_conditions(
             Handler, nntplib.NNTPTemporaryError, Handler.welcome)
 
     def test_service_permanently_unavailable(self):
         #Test service permanently unavailable
         class Handler(NNTPv1Handler):
-            welcome = '502 Service permanently unavilable'
+            welcome = '502 Service permanently unavailable'
         self.check_constructor_error_conditions(
             Handler, nntplib.NNTPPermanentError, Handler.welcome)
 
index 874f9e4..10383cf 100644 (file)
@@ -82,6 +82,11 @@ else:
 # Issue #14110: Some tests fail on FreeBSD if the user is in the wheel group.
 HAVE_WHEEL_GROUP = sys.platform.startswith('freebsd') and os.getgid() == 0
 
+def create_file(filename, content=b'content'):
+    with open(filename, "xb", 0) as fp:
+        fp.write(content)
+
+
 # Tests creating TESTFN
 class FileTests(unittest.TestCase):
     def setUp(self):
@@ -226,15 +231,9 @@ class FileTests(unittest.TestCase):
 # Test attributes on return values from os.*stat* family.
 class StatAttributeTests(unittest.TestCase):
     def setUp(self):
-        os.mkdir(support.TESTFN)
-        self.fname = os.path.join(support.TESTFN, "f1")
-        f = open(self.fname, 'wb')
-        f.write(b"ABC")
-        f.close()
-
-    def tearDown(self):
-        os.unlink(self.fname)
-        os.rmdir(support.TESTFN)
+        self.fname = support.TESTFN
+        self.addCleanup(support.unlink, self.fname)
+        create_file(self.fname, b"ABC")
 
     @unittest.skipUnless(hasattr(os, 'stat'), 'test needs os.stat()')
     def check_stat_attributes(self, fname):
@@ -426,12 +425,35 @@ class StatAttributeTests(unittest.TestCase):
             0)
 
         # test directory st_file_attributes (FILE_ATTRIBUTE_DIRECTORY set)
-        result = os.stat(support.TESTFN)
+        dirname = support.TESTFN + "dir"
+        os.mkdir(dirname)
+        self.addCleanup(os.rmdir, dirname)
+
+        result = os.stat(dirname)
         self.check_file_attributes(result)
         self.assertEqual(
             result.st_file_attributes & stat.FILE_ATTRIBUTE_DIRECTORY,
             stat.FILE_ATTRIBUTE_DIRECTORY)
 
+    @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
+    def test_access_denied(self):
+        # Default to FindFirstFile WIN32_FIND_DATA when access is
+        # denied. See issue 28075.
+        # os.environ['TEMP'] should be located on a volume that
+        # supports file ACLs.
+        fname = os.path.join(os.environ['TEMP'], self.fname)
+        self.addCleanup(support.unlink, fname)
+        create_file(fname, b'ABC')
+        # Deny the right to [S]YNCHRONIZE on the file to
+        # force CreateFile to fail with ERROR_ACCESS_DENIED.
+        DETACHED_PROCESS = 8
+        subprocess.check_call(
+            ['icacls.exe', fname, '/deny', 'Users:(S)'],
+            creationflags=DETACHED_PROCESS
+        )
+        result = os.stat(fname)
+        self.assertNotEqual(result.st_size, 0)
+
 
 class UtimeTests(unittest.TestCase):
     def setUp(self):
@@ -808,39 +830,63 @@ class WalkTests(unittest.TestCase):
         #           SUB11/          no kids
         #         SUB2/             a file kid and a dirsymlink kid
         #           tmp3
+        #           SUB21/          not readable
+        #             tmp5
         #           link/           a symlink to TESTFN.2
         #           broken_link
+        #           broken_link2
+        #           broken_link3
         #       TEST2/
         #         tmp4              a lone file
         self.walk_path = join(support.TESTFN, "TEST1")
         self.sub1_path = join(self.walk_path, "SUB1")
         self.sub11_path = join(self.sub1_path, "SUB11")
         sub2_path = join(self.walk_path, "SUB2")
+        self.sub21_path = join(sub2_path, "SUB21")
         tmp1_path = join(self.walk_path, "tmp1")
         tmp2_path = join(self.sub1_path, "tmp2")
         tmp3_path = join(sub2_path, "tmp3")
+        tmp5_path = join(self.sub21_path, "tmp3")
         self.link_path = join(sub2_path, "link")
         t2_path = join(support.TESTFN, "TEST2")
         tmp4_path = join(support.TESTFN, "TEST2", "tmp4")
         broken_link_path = join(sub2_path, "broken_link")
+        broken_link2_path = join(sub2_path, "broken_link2")
+        broken_link3_path = join(sub2_path, "broken_link3")
 
         # Create stuff.
         os.makedirs(self.sub11_path)
         os.makedirs(sub2_path)
+        os.makedirs(self.sub21_path)
         os.makedirs(t2_path)
 
-        for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path:
-            f = open(path, "w")
-            f.write("I'm " + path + " and proud of it.  Blame test_os.\n")
-            f.close()
+        for path in tmp1_path, tmp2_path, tmp3_path, tmp4_path, tmp5_path:
+            with open(path, "x") as f:
+                f.write("I'm " + path + " and proud of it.  Blame test_os.\n")
 
         if support.can_symlink():
             os.symlink(os.path.abspath(t2_path), self.link_path)
             os.symlink('broken', broken_link_path, True)
-            self.sub2_tree = (sub2_path, ["link"], ["broken_link", "tmp3"])
+            os.symlink(join('tmp3', 'broken'), broken_link2_path, True)
+            os.symlink(join('SUB21', 'tmp5'), broken_link3_path, True)
+            self.sub2_tree = (sub2_path, ["SUB21", "link"],
+                              ["broken_link", "broken_link2", "broken_link3",
+                               "tmp3"])
         else:
             self.sub2_tree = (sub2_path, [], ["tmp3"])
 
+        os.chmod(self.sub21_path, 0)
+        try:
+            os.listdir(self.sub21_path)
+        except PermissionError:
+            pass
+        else:
+            os.chmod(self.sub21_path, stat.S_IRWXU)
+            os.unlink(tmp5_path)
+            os.rmdir(self.sub21_path)
+            self.sub21_path = None
+            del self.sub2_tree[1][:1]
+
     def test_walk_topdown(self):
         # Walk top-down.
         all = list(self.walk(self.walk_path))
@@ -852,6 +898,7 @@ class WalkTests(unittest.TestCase):
         flipped = all[0][1][0] != "SUB1"
         all[0][1].sort()
         all[3 - 2 * flipped][-1].sort()
+        all[3 - 2 * flipped][1].sort()
         self.assertEqual(all[0], (self.walk_path, ["SUB1", "SUB2"], ["tmp1"]))
         self.assertEqual(all[1 + flipped], (self.sub1_path, ["SUB11"], ["tmp2"]))
         self.assertEqual(all[2 + flipped], (self.sub11_path, [], []))
@@ -872,6 +919,7 @@ class WalkTests(unittest.TestCase):
                          (self.walk_path, ["SUB2"], ["tmp1"]))
 
         all[1][-1].sort()
+        all[1][1].sort()
         self.assertEqual(all[1], self.sub2_tree)
 
     def test_walk_bottom_up(self):
@@ -885,6 +933,7 @@ class WalkTests(unittest.TestCase):
         flipped = all[3][1][0] != "SUB1"
         all[3][1].sort()
         all[2 - 2 * flipped][-1].sort()
+        all[2 - 2 * flipped][1].sort()
         self.assertEqual(all[3],
                          (self.walk_path, ["SUB1", "SUB2"], ["tmp1"]))
         self.assertEqual(all[flipped],
@@ -913,6 +962,8 @@ class WalkTests(unittest.TestCase):
         # Windows, which doesn't have a recursive delete command.  The
         # (not so) subtlety is that rmdir will fail unless the dir's
         # kids are removed first, so bottom up is essential.
+        if self.sub21_path:
+            os.chmod(self.sub21_path, stat.S_IRWXU)
         for root, dirs, files in os.walk(support.TESTFN, topdown=False):
             for name in files:
                 os.remove(os.path.join(root, name))
@@ -929,16 +980,21 @@ class WalkTests(unittest.TestCase):
         errors = []
         walk_it = self.walk(self.walk_path, onerror=errors.append)
         root, dirs, files = next(walk_it)
-        self.assertFalse(errors)
-        dir1 = dirs[0]
-        dir1new = dir1 + '.new'
-        os.rename(os.path.join(root, dir1), os.path.join(root, dir1new))
-        roots = [r for r, d, f in walk_it]
-        self.assertTrue(errors)
-        self.assertNotIn(os.path.join(root, dir1), roots)
-        self.assertNotIn(os.path.join(root, dir1new), roots)
-        for dir2 in dirs[1:]:
-            self.assertIn(os.path.join(root, dir2), roots)
+        self.assertEqual(errors, [])
+        dir1 = 'SUB1'
+        path1 = os.path.join(root, dir1)
+        path1new = os.path.join(root, dir1 + '.new')
+        os.rename(path1, path1new)
+        try:
+            roots = [r for r, d, f in walk_it]
+            self.assertTrue(errors)
+            self.assertNotIn(path1, roots)
+            self.assertNotIn(path1new, roots)
+            for dir2 in dirs:
+                if dir2 != dir1:
+                    self.assertIn(os.path.join(root, dir2), roots)
+        finally:
+            os.rename(path1new, path1)
 
 
 @unittest.skipUnless(hasattr(os, 'fwalk'), "Test needs os.fwalk()")
@@ -1008,6 +1064,8 @@ class FwalkTests(WalkTests):
 
     def tearDown(self):
         # cleanup
+        if self.sub21_path:
+            os.chmod(self.sub21_path, stat.S_IRWXU)
         for root, dirs, files, rootfd in os.fwalk(support.TESTFN, topdown=False):
             for name in files:
                 os.unlink(name, dir_fd=rootfd)
@@ -1471,7 +1529,7 @@ class TestInvalidFD(unittest.TestCase):
     singles = ["fchdir", "dup", "fdopen", "fdatasync", "fstat",
                "fstatvfs", "fsync", "tcgetpgrp", "ttyname"]
     #singles.append("close")
-    #We omit close because it doesn'r raise an exception on some platforms
+    #We omit close because it doesn't raise an exception on some platforms
     def get_single(f):
         def helper(self):
             if  hasattr(os, f):
index 3d301b4..ab6577f 100644 (file)
@@ -627,6 +627,22 @@ class CompileTestCase(unittest.TestCase):
         code2 = parser.compilest(st)
         self.assertEqual(eval(code2), -3)
 
+    def test_compile_filename(self):
+        st = parser.expr('a + 5')
+        code = parser.compilest(st)
+        self.assertEqual(code.co_filename, '<syntax-tree>')
+        code = st.compile()
+        self.assertEqual(code.co_filename, '<syntax-tree>')
+        for filename in ('file.py', b'file.py',
+                         bytearray(b'file.py'), memoryview(b'file.py')):
+            code = parser.compilest(st, filename)
+            self.assertEqual(code.co_filename, 'file.py')
+            code = st.compile(filename)
+            self.assertEqual(code.co_filename, 'file.py')
+        self.assertRaises(TypeError, parser.compilest, st, list(b'file.py'))
+        self.assertRaises(TypeError, st.compile, list(b'file.py'))
+
+
 class ParserStackLimitTestCase(unittest.TestCase):
     """try to push the parser to/over its limits.
     see http://bugs.python.org/issue1881 for a discussion
index 45ba5a9..66a7b55 100644 (file)
@@ -911,6 +911,29 @@ def test_pdb_next_command_subiterator():
     (Pdb) continue
     """
 
+def test_pdb_issue_20766():
+    """Test for reference leaks when the SIGINT handler is set.
+
+    >>> def test_function():
+    ...     i = 1
+    ...     while i <= 2:
+    ...         sess = pdb.Pdb()
+    ...         sess.set_trace(sys._getframe())
+    ...         print('pdb %d: %s' % (i, sess._previous_sigint_handler))
+    ...         i += 1
+
+    >>> with PdbTestInput(['continue',
+    ...                    'continue']):
+    ...     test_function()
+    > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
+    -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
+    (Pdb) continue
+    pdb 1: <built-in function default_int_handler>
+    > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
+    -> sess.set_trace(sys._getframe())
+    (Pdb) continue
+    pdb 2: <built-in function default_int_handler>
+    """
 
 class PdbTestCase(unittest.TestCase):
 
index ab5f418..c17ceed 100644 (file)
@@ -1,5 +1,5 @@
 """
-Test suite to check compilance with PEP 247, the standard API
+Test suite to check compliance with PEP 247, the standard API
 for hashing algorithms
 """
 
index ee7a667..d467d52 100644 (file)
@@ -14,6 +14,7 @@ from test.pickletester import AbstractUnpickleTests
 from test.pickletester import AbstractPickleTests
 from test.pickletester import AbstractPickleModuleTests
 from test.pickletester import AbstractPersistentPicklerTests
+from test.pickletester import AbstractIdentityPersistentPicklerTests
 from test.pickletester import AbstractPicklerUnpicklerObjectTests
 from test.pickletester import AbstractDispatchTableTests
 from test.pickletester import BigmemPickleTests
@@ -82,10 +83,7 @@ class InMemoryPickleTests(AbstractPickleTests, AbstractUnpickleTests,
         return pickle.loads(buf, **kwds)
 
 
-class PyPersPicklerTests(AbstractPersistentPicklerTests):
-
-    pickler = pickle._Pickler
-    unpickler = pickle._Unpickler
+class PersistentPicklerUnpicklerMixin(object):
 
     def dumps(self, arg, proto=None):
         class PersPickler(self.pickler):
@@ -94,8 +92,7 @@ class PyPersPicklerTests(AbstractPersistentPicklerTests):
         f = io.BytesIO()
         p = PersPickler(f, proto)
         p.dump(arg)
-        f.seek(0)
-        return f.read()
+        return f.getvalue()
 
     def loads(self, buf, **kwds):
         class PersUnpickler(self.unpickler):
@@ -106,6 +103,20 @@ class PyPersPicklerTests(AbstractPersistentPicklerTests):
         return u.load()
 
 
+class PyPersPicklerTests(AbstractPersistentPicklerTests,
+                         PersistentPicklerUnpicklerMixin):
+
+    pickler = pickle._Pickler
+    unpickler = pickle._Unpickler
+
+
+class PyIdPersPicklerTests(AbstractIdentityPersistentPicklerTests,
+                           PersistentPicklerUnpicklerMixin):
+
+    pickler = pickle._Pickler
+    unpickler = pickle._Unpickler
+
+
 class PyPicklerUnpicklerObjectTests(AbstractPicklerUnpicklerObjectTests):
 
     pickler_class = pickle._Pickler
@@ -144,6 +155,10 @@ if has_c_implementation:
         pickler = _pickle.Pickler
         unpickler = _pickle.Unpickler
 
+    class CIdPersPicklerTests(PyIdPersPicklerTests):
+        pickler = _pickle.Pickler
+        unpickler = _pickle.Unpickler
+
     class CDumpPickle_LoadPickle(PyPicklerTests):
         pickler = _pickle.Pickler
         unpickler = pickle._Unpickler
@@ -409,11 +424,13 @@ class CompatPickleTests(unittest.TestCase):
 
 
 def test_main():
-    tests = [PickleTests, PyUnpicklerTests, PyPicklerTests, PyPersPicklerTests,
+    tests = [PickleTests, PyUnpicklerTests, PyPicklerTests,
+             PyPersPicklerTests, PyIdPersPicklerTests,
              PyDispatchTableTests, PyChainDispatchTableTests,
              CompatPickleTests]
     if has_c_implementation:
-        tests.extend([CUnpicklerTests, CPicklerTests, CPersPicklerTests,
+        tests.extend([CUnpicklerTests, CPicklerTests,
+                      CPersPicklerTests, CIdPersPicklerTests,
                       CDumpPickle_LoadPickle, DumpPickle_CLoadPickle,
                       PyPicklerUnpicklerObjectTests,
                       CPicklerUnpicklerObjectTests,
index 9d20354..a820587 100644 (file)
@@ -205,7 +205,7 @@ class PkgutilPEP302Tests(unittest.TestCase):
         del sys.meta_path[0]
 
     def test_getdata_pep302(self):
-        # Use a dummy importer/loader
+        # Use a dummy finder/loader
         self.assertEqual(pkgutil.get_data('foo', 'dummy'), "Hello, world!")
         del sys.modules['foo']
 
index ed18773..18de110 100644 (file)
@@ -15,11 +15,18 @@ class PlatformTest(unittest.TestCase):
 
     @support.skip_unless_symlink
     def test_architecture_via_symlink(self): # issue3762
-        # On Windows, the EXE needs to know where pythonXY.dll is at so we have
-        # to add the directory to the path.
+        # On Windows, the EXE needs to know where pythonXY.dll and *.pyd is at
+        # so we add the directory to the path and PYTHONPATH.
         if sys.platform == "win32":
+            def restore_environ(old_env):
+                os.environ.clear()
+                os.environ.update(old_env)
+
+            self.addCleanup(restore_environ, dict(os.environ))
+
             os.environ["Path"] = "{};{}".format(
                 os.path.dirname(sys.executable), os.environ["Path"])
+            os.environ["PYTHONPATH"] = os.path.dirname(sys.executable)
 
         def get(python):
             cmd = [python, '-c',
index 16114f9..692cac4 100644 (file)
@@ -361,6 +361,13 @@ class TestPlistlib(unittest.TestCase):
                                   plistlib.dumps,
                                   testString)
 
+    def test_non_bmp_characters(self):
+        pl = {'python': '\U0001f40d'}
+        for fmt in ALL_FORMATS:
+            with self.subTest(fmt=fmt):
+                data = plistlib.dumps(pl, fmt=fmt)
+                self.assertEqual(plistlib.loads(data), pl)
+
     def test_nondictroot(self):
         for fmt in ALL_FORMATS:
             with self.subTest(fmt=fmt):
index a0a332b..6a2bf6e 100644 (file)
@@ -125,6 +125,8 @@ class PollTests(unittest.TestCase):
         cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done'
         proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                                 bufsize=0)
+        proc.__enter__()
+        self.addCleanup(proc.__exit__, None, None, None)
         p = proc.stdout
         pollster = select.poll()
         pollster.register( p, select.POLLIN )
@@ -147,7 +149,6 @@ class PollTests(unittest.TestCase):
                 continue
             else:
                 self.fail('Unexpected return value from select.poll: %s' % fdlist)
-        p.close()
 
     def test_poll3(self):
         # test int overflow
index acf1102..0783c36 100644 (file)
@@ -1,7 +1,5 @@
-import itertools
 import os
 import posixpath
-import sys
 import unittest
 import warnings
 from posixpath import realpath, abspath, dirname, basename
@@ -213,6 +211,28 @@ class PosixPathTest(unittest.TestCase):
         finally:
             os.lstat = save_lstat
 
+    @unittest.skipIf(posix is None, "Test requires posix module")
+    def test_ismount_directory_not_readable(self):
+        # issue #2466: Simulate ismount run on a directory that is not
+        # readable, which used to return False.
+        save_lstat = os.lstat
+        def fake_lstat(path):
+            st_ino = 0
+            st_dev = 0
+            if path.startswith(ABSTFN) and path != ABSTFN:
+                # ismount tries to read something inside the ABSTFN directory;
+                # simulate this being forbidden (no read permission).
+                raise OSError("Fake [Errno 13] Permission denied")
+            if path == ABSTFN:
+                st_dev = 1
+                st_ino = 1
+            return posix.stat_result((0, st_ino, st_dev, 0, 0, 0, 0, 0, 0, 0))
+        try:
+            os.lstat = fake_lstat
+            self.assertIs(posixpath.ismount(ABSTFN), True)
+        finally:
+            os.lstat = save_lstat
+
     def test_expanduser(self):
         self.assertEqual(posixpath.expanduser("foo"), "foo")
         self.assertEqual(posixpath.expanduser(b"foo"), b"foo")
index 59aa715..1f7ab7f 100644 (file)
@@ -15,6 +15,7 @@ import string
 import test.support
 import time
 import types
+import typing
 import unittest
 import urllib.parse
 import xml.etree
@@ -356,7 +357,7 @@ def get_pydoc_html(module):
 def get_pydoc_link(module):
     "Returns a documentation web link of a module"
     dirname = os.path.dirname
-    basedir = os.path.join(dirname(dirname(__file__)))
+    basedir = dirname(dirname(__file__))
     doc = pydoc.TextDoc()
     loc = doc.getdocloc(module, basedir=basedir)
     return loc
@@ -815,6 +816,18 @@ class TestDescriptions(unittest.TestCase):
         expected = 'C in module %s object' % __name__
         self.assertIn(expected, pydoc.render_doc(c))
 
+    def test_typing_pydoc(self):
+        def foo(data: typing.List[typing.Any],
+                x: int) -> typing.Iterator[typing.Tuple[int, typing.Any]]:
+            ...
+        T = typing.TypeVar('T')
+        class C(typing.Generic[T], typing.Mapping[int, str]): ...
+        self.assertEqual(pydoc.render_doc(foo).splitlines()[-1],
+                         'f\x08fo\x08oo\x08o(data:List[Any], x:int)'
+                         ' -> Iterator[Tuple[int, Any]]')
+        self.assertEqual(pydoc.render_doc(C).splitlines()[2],
+                         'class C\x08C(typing.Mapping)')
+
     def test_builtin(self):
         for name in ('str', 'str.translate', 'builtins.str',
                      'builtins.str.translate'):
index 0b68bfa..92fffc4 100644 (file)
@@ -656,11 +656,9 @@ class MalformedInputTest(unittest.TestCase):
         # \xc2\x85 is UTF-8 encoded U+0085 (NEXT LINE)
         xml = b"<?xml version\xc2\x85='1.0'?>\r\n"
         parser = expat.ParserCreate()
-        try:
+        err_pattern = r'XML declaration not well-formed: line 1, column \d+'
+        with self.assertRaisesRegex(expat.ExpatError, err_pattern):
             parser.Parse(xml, True)
-            self.fail()
-        except expat.ExpatError as e:
-            self.assertEqual(str(e), 'XML declaration not well-formed: line 1, column 14')
 
 class ErrorMessageTest(unittest.TestCase):
     def test_codes(self):
index 5393431..e80ed17 100644 (file)
@@ -326,6 +326,24 @@ class MersenneTwister_TestBasicOps(TestBasicOps, unittest.TestCase):
             ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
              '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
 
+    def test_bug_27706(self):
+        # Verify that version 1 seeds are unaffected by hash randomization
+
+        self.gen.seed('nofar', version=1)   # hash('nofar') == 5990528763808513177
+        self.assertEqual([self.gen.random().hex() for i in range(4)],
+            ['0x1.8645314505ad7p-1', '0x1.afb1f82e40a40p-5',
+             '0x1.2a59d2285e971p-1', '0x1.56977142a7880p-6'])
+
+        self.gen.seed('rachel', version=1)  # hash('rachel') == -9091735575445484789
+        self.assertEqual([self.gen.random().hex() for i in range(4)],
+            ['0x1.0b294cc856fcdp-1', '0x1.2ad22d79e77b8p-3',
+             '0x1.3052b9c072678p-2', '0x1.578f332106574p-3'])
+
+        self.gen.seed('', version=1)        # hash('') == 0
+        self.assertEqual([self.gen.random().hex() for i in range(4)],
+            ['0x1.b0580f98a7dbep-1', '0x1.84129978f9c1ap-1',
+             '0x1.aeaa51052e978p-2', '0x1.092178fb945a6p-2'])
+
     def test_setstate_first_arg(self):
         self.assertRaises(ValueError, self.gen.setstate, (1, None, None))
 
index 106c732..c022f07 100644 (file)
@@ -493,6 +493,35 @@ class RangeTest(unittest.TestCase):
             test_id = "reversed(range({}, {}, {}))".format(start, end, step)
             self.assert_iterators_equal(iter1, iter2, test_id, limit=100)
 
+    @test.support.cpython_only
+    def test_range_iterator_invocation(self):
+        import _testcapi
+        rangeiter_type = type(iter(range(0)))
+
+        # rangeiter_new doesn't take keyword arguments
+        with self.assertRaises(TypeError):
+            rangeiter_type(a=1)
+
+        # rangeiter_new takes exactly 3 arguments
+        self.assertRaises(TypeError, rangeiter_type)
+        self.assertRaises(TypeError, rangeiter_type, 1)
+        self.assertRaises(TypeError, rangeiter_type, 1, 1)
+        self.assertRaises(TypeError, rangeiter_type, 1, 1, 1, 1)
+
+        # start, stop and stop must fit in C long
+        for good_val in [_testcapi.LONG_MAX, _testcapi.LONG_MIN]:
+            rangeiter_type(good_val, good_val, good_val)
+        for bad_val in [_testcapi.LONG_MAX + 1, _testcapi.LONG_MIN - 1]:
+            self.assertRaises(OverflowError,
+                              rangeiter_type, bad_val, 1, 1)
+            self.assertRaises(OverflowError,
+                              rangeiter_type, 1, bad_val, 1)
+            self.assertRaises(OverflowError,
+                              rangeiter_type, 1, 1, bad_val)
+
+        # step mustn't be zero
+        self.assertRaises(ValueError, rangeiter_type, 1, 1, 0)
+
     def test_slice(self):
         def check(start, stop, step=None):
             i = slice(start, stop, step)
index 7a74141..0834fe0 100644 (file)
@@ -102,6 +102,8 @@ class ReTests(unittest.TestCase):
         self.assertEqual(re.sub("(?i)b+", "x", "bbbb BBBB"), 'x x')
         self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'),
                          '9.3 -3 24x100y')
+        self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3),
+                         '9.3 -3 23x99y')
         self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', count=3),
                          '9.3 -3 23x99y')
 
@@ -206,6 +208,7 @@ class ReTests(unittest.TestCase):
 
     def test_qualified_re_sub(self):
         self.assertEqual(re.sub('a', 'b', 'aaaaa'), 'bbbbb')
+        self.assertEqual(re.sub('a', 'b', 'aaaaa', 1), 'baaaa')
         self.assertEqual(re.sub('a', 'b', 'aaaaa', count=1), 'baaaa')
 
     def test_bug_114660(self):
@@ -291,6 +294,7 @@ class ReTests(unittest.TestCase):
         self.assertEqual(re.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1))
         self.assertEqual(re.subn("b+", "x", "xyz"), ('xyz', 0))
         self.assertEqual(re.subn("b*", "x", "xyz"), ('xxxyxzx', 4))
+        self.assertEqual(re.subn("b*", "x", "xyz", 2), ('xxxyz', 2))
         self.assertEqual(re.subn("b*", "x", "xyz", count=2), ('xxxyz', 2))
 
     def test_re_split(self):
@@ -347,6 +351,7 @@ class ReTests(unittest.TestCase):
                 self.assertTypedEqual(re.split(sep, ':a:b::c'), expected)
 
     def test_qualified_re_split(self):
+        self.assertEqual(re.split(":", ":a:b::c", 2), ['', 'a', 'b::c'])
         self.assertEqual(re.split(":", ":a:b::c", maxsplit=2), ['', 'a', 'b::c'])
         self.assertEqual(re.split(':', 'a:b:c:d', maxsplit=2), ['a', 'b', 'c:d'])
         self.assertEqual(re.split("(:)", ":a:b::c", maxsplit=2),
@@ -1270,6 +1275,9 @@ class ReTests(unittest.TestCase):
         q = p.match(upper_char)
         self.assertTrue(q)
 
+        self.assertTrue(re.match('(?ixu) ' + upper_char, lower_char))
+        self.assertTrue(re.match('(?ixu) ' + lower_char, upper_char))
+
     def test_dollar_matches_twice(self):
         "$ matches the end of string, and just before the terminating \n"
         pattern = re.compile('$')
index 35330ab..2c73df2 100644 (file)
@@ -1,15 +1,25 @@
 """
 Very minimal unittests for parts of the readline module.
 """
+from contextlib import ExitStack
+from errno import EIO
 import os
+import selectors
+import subprocess
+import sys
 import tempfile
 import unittest
-from test.support import import_module, unlink
+from test.support import import_module, unlink, TESTFN
 from test.support.script_helper import assert_python_ok
 
 # Skip tests if there is no readline module
 readline = import_module('readline')
 
+is_editline = readline.__doc__ and "libedit" in readline.__doc__
+
+@unittest.skipUnless(hasattr(readline, "clear_history"),
+                     "The history update test cannot be run because the "
+                     "clear_history method is not available.")
 class TestHistoryManipulation (unittest.TestCase):
     """
     These tests were added to check that the libedit emulation on OSX and the
@@ -17,9 +27,6 @@ class TestHistoryManipulation (unittest.TestCase):
     why the tests cover only a small subset of the interface.
     """
 
-    @unittest.skipUnless(hasattr(readline, "clear_history"),
-                         "The history update test cannot be run because the "
-                         "clear_history method is not available.")
     def testHistoryUpdates(self):
         readline.clear_history()
 
@@ -82,11 +89,29 @@ class TestHistoryManipulation (unittest.TestCase):
         # write_history_file can create the target
         readline.write_history_file(hfilename)
 
+    def test_nonascii_history(self):
+        readline.clear_history()
+        try:
+            readline.add_history("entrée 1")
+        except UnicodeEncodeError as err:
+            self.skipTest("Locale cannot encode test data: " + format(err))
+        readline.add_history("entrée 2")
+        readline.replace_history_item(1, "entrée 22")
+        readline.write_history_file(TESTFN)
+        self.addCleanup(os.remove, TESTFN)
+        readline.clear_history()
+        readline.read_history_file(TESTFN)
+        if is_editline:
+            # An add_history() call seems to be required for get_history_
+            # item() to register items from the file
+            readline.add_history("dummy")
+        self.assertEqual(readline.get_history_item(1), "entrée 1")
+        self.assertEqual(readline.get_history_item(2), "entrée 22")
+
 
 class TestReadline(unittest.TestCase):
 
-    @unittest.skipIf(readline._READLINE_VERSION < 0x0600
-                     and "libedit" not in readline.__doc__,
+    @unittest.skipIf(readline._READLINE_VERSION < 0x0601 and not is_editline,
                      "not supported in this library version")
     def test_init(self):
         # Issue #19884: Ensure that the ANSI sequence "\033[1034h" is not
@@ -96,6 +121,130 @@ class TestReadline(unittest.TestCase):
                                               TERM='xterm-256color')
         self.assertEqual(stdout, b'')
 
+    def test_nonascii(self):
+        try:
+            readline.add_history("\xEB\xEF")
+        except UnicodeEncodeError as err:
+            self.skipTest("Locale cannot encode test data: " + format(err))
+
+        script = r"""import readline
+
+is_editline = readline.__doc__ and "libedit" in readline.__doc__
+inserted = "[\xEFnserted]"
+macro = "|t\xEB[after]"
+set_pre_input_hook = getattr(readline, "set_pre_input_hook", None)
+if is_editline or not set_pre_input_hook:
+    # The insert_line() call via pre_input_hook() does nothing with Editline,
+    # so include the extra text that would have been inserted here
+    macro = inserted + macro
+
+if is_editline:
+    readline.parse_and_bind(r'bind ^B ed-prev-char')
+    readline.parse_and_bind(r'bind "\t" rl_complete')
+    readline.parse_and_bind(r'bind -s ^A "{}"'.format(macro))
+else:
+    readline.parse_and_bind(r'Control-b: backward-char')
+    readline.parse_and_bind(r'"\t": complete')
+    readline.parse_and_bind(r'set disable-completion off')
+    readline.parse_and_bind(r'set show-all-if-ambiguous off')
+    readline.parse_and_bind(r'set show-all-if-unmodified off')
+    readline.parse_and_bind(r'Control-a: "{}"'.format(macro))
+
+def pre_input_hook():
+    readline.insert_text(inserted)
+    readline.redisplay()
+if set_pre_input_hook:
+    set_pre_input_hook(pre_input_hook)
+
+def completer(text, state):
+    if text == "t\xEB":
+        if state == 0:
+            print("text", ascii(text))
+            print("line", ascii(readline.get_line_buffer()))
+            print("indexes", readline.get_begidx(), readline.get_endidx())
+            return "t\xEBnt"
+        if state == 1:
+            return "t\xEBxt"
+    if text == "t\xEBx" and state == 0:
+        return "t\xEBxt"
+    return None
+readline.set_completer(completer)
+
+def display(substitution, matches, longest_match_length):
+    print("substitution", ascii(substitution))
+    print("matches", ascii(matches))
+readline.set_completion_display_matches_hook(display)
+
+print("result", ascii(input()))
+print("history", ascii(readline.get_history_item(1)))
+"""
+
+        input = b"\x01"  # Ctrl-A, expands to "|t\xEB[after]"
+        input += b"\x02" * len("[after]")  # Move cursor back
+        input += b"\t\t"  # Display possible completions
+        input += b"x\t"  # Complete "t\xEBx" -> "t\xEBxt"
+        input += b"\r"
+        output = run_pty(script, input)
+        self.assertIn(b"text 't\\xeb'\r\n", output)
+        self.assertIn(b"line '[\\xefnserted]|t\\xeb[after]'\r\n", output)
+        self.assertIn(b"indexes 11 13\r\n", output)
+        if not is_editline and hasattr(readline, "set_pre_input_hook"):
+            self.assertIn(b"substitution 't\\xeb'\r\n", output)
+            self.assertIn(b"matches ['t\\xebnt', 't\\xebxt']\r\n", output)
+        expected = br"'[\xefnserted]|t\xebxt[after]'"
+        self.assertIn(b"result " + expected + b"\r\n", output)
+        self.assertIn(b"history " + expected + b"\r\n", output)
+
+
+def run_pty(script, input=b"dummy input\r"):
+    pty = import_module('pty')
+    output = bytearray()
+    [master, slave] = pty.openpty()
+    args = (sys.executable, '-c', script)
+    proc = subprocess.Popen(args, stdin=slave, stdout=slave, stderr=slave)
+    os.close(slave)
+    with ExitStack() as cleanup:
+        cleanup.enter_context(proc)
+        def terminate(proc):
+            try:
+                proc.terminate()
+            except ProcessLookupError:
+                # Workaround for Open/Net BSD bug (Issue 16762)
+                pass
+        cleanup.callback(terminate, proc)
+        cleanup.callback(os.close, master)
+        # Avoid using DefaultSelector and PollSelector. Kqueue() does not
+        # work with pseudo-terminals on OS X < 10.9 (Issue 20365) and Open
+        # BSD (Issue 20667). Poll() does not work with OS X 10.6 or 10.4
+        # either (Issue 20472). Hopefully the file descriptor is low enough
+        # to use with select().
+        sel = cleanup.enter_context(selectors.SelectSelector())
+        sel.register(master, selectors.EVENT_READ | selectors.EVENT_WRITE)
+        os.set_blocking(master, False)
+        while True:
+            for [_, events] in sel.select():
+                if events & selectors.EVENT_READ:
+                    try:
+                        chunk = os.read(master, 0x10000)
+                    except OSError as err:
+                        # Linux raises EIO when slave is closed (Issue 5380)
+                        if err.errno != EIO:
+                            raise
+                        chunk = b""
+                    if not chunk:
+                        return output
+                    output.extend(chunk)
+                if events & selectors.EVENT_WRITE:
+                    try:
+                        input = input[os.write(master, input):]
+                    except OSError as err:
+                        # Apparently EIO means the slave was closed
+                        if err.errno != EIO:
+                            raise
+                        input = b""  # Stop writing
+                    if not input:
+                        sel.modify(master, selectors.EVENT_READ)
+
 
 if __name__ == "__main__":
     unittest.main()
index a398a4f..e2c2f2d 100644 (file)
@@ -200,6 +200,9 @@ class ParseArgsTestCase(unittest.TestCase):
                 self.checkError([opt, '2', '-T'], "don't go together")
                 self.checkError([opt, '2', '-l'], "don't go together")
                 self.checkError([opt, '2', '-M', '4G'], "don't go together")
+                self.checkError([opt, '0', '-T'], "don't go together")
+                self.checkError([opt, '0', '-l'], "don't go together")
+                self.checkError([opt, '0', '-M', '4G'], "don't go together")
 
     def test_coverage(self):
         for opt in '-T', '--coverage':
@@ -270,6 +273,16 @@ class ParseArgsTestCase(unittest.TestCase):
         self.assertEqual(ns.verbose, 0)
         self.assertEqual(ns.args, ['foo'])
 
+    def test_arg_option_arg(self):
+        ns = regrtest._parse_args(['test_unaryop', '-v', 'test_binop'])
+        self.assertEqual(ns.verbose, 1)
+        self.assertEqual(ns.args, ['test_unaryop', 'test_binop'])
+
+    def test_unknown_option(self):
+        self.checkError(['--unknown-option'],
+                        'unrecognized arguments: --unknown-option')
+
+
 
 if __name__ == '__main__':
     unittest.main()
index 2ecae0f..cc9c570 100644 (file)
@@ -158,6 +158,20 @@ class ResourceTest(unittest.TestCase):
         self.assertEqual(resource.prlimit(0, resource.RLIMIT_AS, limit),
                          limit)
 
+    # Issue 20191: Reference counting bug
+    @unittest.skipUnless(hasattr(resource, 'prlimit'), 'no prlimit')
+    @support.requires_linux_version(2, 6, 36)
+    def test_prlimit_refcount(self):
+        class BadSeq:
+            def __len__(self):
+                return 2
+            def __getitem__(self, key):
+                return limits[key] - 1  # new reference
+
+        limits = resource.getrlimit(resource.RLIMIT_AS)
+        self.assertEqual(resource.prlimit(0, resource.RLIMIT_AS, BadSeq()),
+                         limits)
+
 
 def test_main(verbose=None):
     support.run_unittest(ResourceTest)
index 87c83ec..db55db7 100644 (file)
@@ -7,6 +7,7 @@ import re
 import tempfile
 import importlib, importlib.machinery, importlib.util
 import py_compile
+import warnings
 from test.support import (
     forget, make_legacy_pyc, unload, verbose, no_tracing,
     create_empty_file, temp_dir)
@@ -246,7 +247,7 @@ class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin):
                                                           mod_fname)
         return pkg_dir, mod_fname, mod_name, mod_spec
 
-    def _del_pkg(self, top, depth, mod_name):
+    def _del_pkg(self, top):
         for entry in list(sys.modules):
             if entry.startswith("__runpy_pkg__"):
                 del sys.modules[entry]
@@ -320,7 +321,7 @@ class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin):
                 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
                 self.check_code_execution(create_ns, expected_ns)
         finally:
-            self._del_pkg(pkg_dir, depth, mod_name)
+            self._del_pkg(pkg_dir)
         if verbose > 1: print("Module executed successfully")
 
     def _check_package(self, depth, alter_sys=False,
@@ -361,7 +362,7 @@ class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin):
                 self._fix_ns_for_legacy_pyc(expected_ns, alter_sys)
                 self.check_code_execution(create_ns, expected_ns)
         finally:
-            self._del_pkg(pkg_dir, depth, pkg_name)
+            self._del_pkg(pkg_dir)
         if verbose > 1: print("Package executed successfully")
 
     def _add_relative_modules(self, base_dir, source, depth):
@@ -424,7 +425,7 @@ from ..uncle.cousin import nephew
                 self.assertIn("nephew", d2)
                 del d2 # Ensure __loader__ entry doesn't keep file open
         finally:
-            self._del_pkg(pkg_dir, depth, mod_name)
+            self._del_pkg(pkg_dir)
         if verbose > 1: print("Module executed successfully")
 
     def test_run_module(self):
@@ -447,7 +448,7 @@ from ..uncle.cousin import nephew
         result = self._make_pkg("", 1, "__main__")
         pkg_dir, _, mod_name, _ = result
         mod_name = mod_name.replace(".__main__", "")
-        self.addCleanup(self._del_pkg, pkg_dir, 1, mod_name)
+        self.addCleanup(self._del_pkg, pkg_dir)
         init = os.path.join(pkg_dir, "__runpy_pkg__", "__init__.py")
 
         exceptions = (ImportError, AttributeError, TypeError, ValueError)
@@ -470,6 +471,31 @@ from ..uncle.cousin import nephew
                 else:
                     self.fail("Nothing raised; expected {}".format(name))
 
+    def test_submodule_imported_warning(self):
+        pkg_dir, _, mod_name, _ = self._make_pkg("", 1)
+        try:
+            __import__(mod_name)
+            with self.assertWarnsRegex(RuntimeWarning,
+                    r"found in sys\.modules"):
+                run_module(mod_name)
+        finally:
+            self._del_pkg(pkg_dir)
+
+    def test_package_imported_no_warning(self):
+        pkg_dir, _, mod_name, _ = self._make_pkg("", 1, "__main__")
+        self.addCleanup(self._del_pkg, pkg_dir)
+        package = mod_name.replace(".__main__", "")
+        # No warning should occur if we only imported the parent package
+        __import__(package)
+        self.assertIn(package, sys.modules)
+        with warnings.catch_warnings():
+            warnings.simplefilter("error", RuntimeWarning)
+            run_module(package)
+        # But the warning should occur if we imported the __main__ submodule
+        __import__(mod_name)
+        with self.assertWarnsRegex(RuntimeWarning, r"found in sys\.modules"):
+            run_module(package)
+
     def test_run_package_in_namespace_package(self):
         for depth in range(1, 4):
             if verbose > 1: print("Testing package depth:", depth)
@@ -524,7 +550,7 @@ from ..uncle.cousin import nephew
         try:
             self.check_code_execution(create_ns, expected_ns)
         finally:
-            self._del_pkg(pkg_dir, depth, mod_name)
+            self._del_pkg(pkg_dir)
 
     def test_pkgutil_walk_packages(self):
         # This is a dodgy hack to use the test_runpy infrastructure to test
@@ -548,7 +574,7 @@ from ..uncle.cousin import nephew
         expected_modules.add(pkg_name + ".runpy_test")
         pkg_dir, mod_fname, mod_name, mod_spec = (
                self._make_pkg("", max_depth))
-        self.addCleanup(self._del_pkg, pkg_dir, max_depth, mod_name)
+        self.addCleanup(self._del_pkg, pkg_dir)
         for depth in range(2, max_depth+1):
             self._add_relative_modules(pkg_dir, "", depth)
         for finder, mod_name, ispkg in pkgutil.walk_packages([pkg_dir]):
index 454c17b..852b2fe 100644 (file)
@@ -9,6 +9,7 @@ from test import support
 from time import sleep
 import unittest
 import unittest.mock
+import tempfile
 from time import monotonic as time
 try:
     import resource
@@ -475,6 +476,16 @@ class EpollSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn):
 
     SELECTOR = getattr(selectors, 'EpollSelector', None)
 
+    def test_register_file(self):
+        # epoll(7) returns EPERM when given a file to watch
+        s = self.SELECTOR()
+        with tempfile.NamedTemporaryFile() as f:
+            with self.assertRaises(IOError):
+                s.register(f, selectors.EVENT_READ)
+            # the SelectorKey has been removed
+            with self.assertRaises(KeyError):
+                s.get_key(f)
+
 
 @unittest.skipUnless(hasattr(selectors, 'KqueueSelector'),
                      "Test needs selectors.KqueueSelector)")
@@ -482,6 +493,18 @@ class KqueueSelectorTestCase(BaseSelectorTestCase, ScalableSelectorMixIn):
 
     SELECTOR = getattr(selectors, 'KqueueSelector', None)
 
+    def test_register_bad_fd(self):
+        # a file descriptor that's been closed should raise an OSError
+        # with EBADF
+        s = self.SELECTOR()
+        bad_f = support.make_bad_fd()
+        with self.assertRaises(OSError) as cm:
+            s.register(bad_f, selectors.EVENT_READ)
+        self.assertEqual(cm.exception.errno, errno.EBADF)
+        # the SelectorKey has been removed
+        with self.assertRaises(KeyError):
+            s.get_key(bad_f)
+
 
 @unittest.skipUnless(hasattr(selectors, 'DevpollSelector'),
                      "Test needs selectors.DevpollSelector")
index 1a49edf..7594303 100644 (file)
@@ -388,6 +388,21 @@ class TestSet(TestJointOps, unittest.TestCase):
         t = {1,2,3}
         self.assertEqual(s, t)
 
+    def test_set_literal_insertion_order(self):
+        # SF Issue #26020 -- Expect left to right insertion
+        s = {1, 1.0, True}
+        self.assertEqual(len(s), 1)
+        stored_value = s.pop()
+        self.assertEqual(type(stored_value), int)
+
+    def test_set_literal_evaluation_order(self):
+        # Expect left to right expression evaluation
+        events = []
+        def record(obj):
+            events.append(obj)
+        s = {record(1), record(2), record(3)}
+        self.assertEqual(events, [1, 2, 3])
+
     def test_hash(self):
         self.assertRaises(TypeError, hash, self.s)
 
index bd51d86..b71af2b 100644 (file)
@@ -162,6 +162,10 @@ class TestCase(unittest.TestCase):
         else:
             self.fail('Closed shelf should not find a key')
 
+    def test_default_protocol(self):
+        with shelve.Shelf({}) as s:
+            self.assertEqual(s._protocol, 3)
+
 from test import mapping_tests
 
 class TestShelveBase(mapping_tests.BasicTestMappingProtocol):
index 4fafdd4..55b533d 100644 (file)
@@ -173,6 +173,18 @@ class ShlexTest(unittest.TestCase):
                              "%s: %s != %s" %
                              (self.data[i][0], l, self.data[i][1:]))
 
+    def testEmptyStringHandling(self):
+        """Test that parsing of empty strings is correctly handled."""
+        # see Issue #21999
+        expected = ['', ')', 'abc']
+
+        s = shlex.shlex("'')abc", posix=True)
+        slist = list(s)
+        self.assertEqual(slist, expected)
+        expected = ["''", ')', 'abc']
+        s = shlex.shlex("'')abc")
+        self.assertEqual(list(s), expected)
+
     def testQuote(self):
         safeunquoted = string.ascii_letters + string.digits + '@%_-+=:,./'
         unicode_sample = '\xe9\xe0\xdf'  # e + acute accent, a + grave, sharp s
index 13b30b9..709feeb 100644 (file)
@@ -19,22 +19,11 @@ from shutil import (make_archive,
                     unregister_unpack_format, get_unpack_formats,
                     SameFileError)
 import tarfile
+import zipfile
 import warnings
 
 from test import support
-from test.support import TESTFN, check_warnings, captured_stdout, requires_zlib
-
-try:
-    import bz2
-    BZ2_SUPPORTED = True
-except ImportError:
-    BZ2_SUPPORTED = False
-
-try:
-    import lzma
-    LZMA_SUPPORTED = True
-except ImportError:
-    LZMA_SUPPORTED = False
+from test.support import TESTFN, check_warnings, captured_stdout
 
 TESTFN2 = TESTFN + "2"
 
@@ -45,12 +34,6 @@ try:
 except ImportError:
     UID_GID_SUPPORT = False
 
-try:
-    import zipfile
-    ZIP_SUPPORT = True
-except ImportError:
-    ZIP_SUPPORT = shutil.which('zip')
-
 def _fake_rename(*args, **kwargs):
     # Pretend the destination path is on a different filesystem.
     raise OSError(getattr(errno, 'EXDEV', 18), "Invalid cross-device link")
@@ -964,7 +947,7 @@ class TestShutil(unittest.TestCase):
             self.assertEqual(getattr(file1_stat, 'st_flags'),
                              getattr(file2_stat, 'st_flags'))
 
-    @requires_zlib
+    @support.requires_zlib
     def test_make_tarball(self):
         # creating something to tar
         root_dir, base_dir = self._create_files('')
@@ -1020,7 +1003,7 @@ class TestShutil(unittest.TestCase):
             write_file((root_dir, 'outer'), 'xxx')
         return root_dir, base_dir
 
-    @requires_zlib
+    @support.requires_zlib
     @unittest.skipUnless(shutil.which('tar'),
                          'Need the tar command to run')
     def test_tarfile_vs_tar(self):
@@ -1053,8 +1036,7 @@ class TestShutil(unittest.TestCase):
         self.assertEqual(tarball, base_name + '.tar')
         self.assertTrue(os.path.isfile(tarball))
 
-    @requires_zlib
-    @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
+    @support.requires_zlib
     def test_make_zipfile(self):
         # creating something to zip
         root_dir, base_dir = self._create_files()
@@ -1068,6 +1050,19 @@ class TestShutil(unittest.TestCase):
 
         with support.change_cwd(work_dir):
             base_name = os.path.abspath(rel_base_name)
+            res = make_archive(rel_base_name, 'zip', root_dir)
+
+        self.assertEqual(res, base_name + '.zip')
+        self.assertTrue(os.path.isfile(res))
+        self.assertTrue(zipfile.is_zipfile(res))
+        with zipfile.ZipFile(res) as zf:
+            self.assertCountEqual(zf.namelist(),
+                    ['dist/', 'dist/sub/', 'dist/sub2/',
+                     'dist/file1', 'dist/file2', 'dist/sub/file3',
+                     'outer'])
+
+        with support.change_cwd(work_dir):
+            base_name = os.path.abspath(rel_base_name)
             res = make_archive(rel_base_name, 'zip', root_dir, base_dir)
 
         self.assertEqual(res, base_name + '.zip')
@@ -1078,8 +1073,7 @@ class TestShutil(unittest.TestCase):
                     ['dist/', 'dist/sub/', 'dist/sub2/',
                      'dist/file1', 'dist/file2', 'dist/sub/file3'])
 
-    @requires_zlib
-    @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
+    @support.requires_zlib
     @unittest.skipUnless(shutil.which('zip'),
                          'Need the zip command to run')
     def test_zipfile_vs_zip(self):
@@ -1105,8 +1099,7 @@ class TestShutil(unittest.TestCase):
             names2 = zf.namelist()
         self.assertEqual(sorted(names), sorted(names2))
 
-    @requires_zlib
-    @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
+    @support.requires_zlib
     @unittest.skipUnless(shutil.which('unzip'),
                          'Need the unzip command to run')
     def test_unzip_zipfile(self):
@@ -1133,7 +1126,7 @@ class TestShutil(unittest.TestCase):
         base_name = os.path.join(tmpdir, 'archive')
         self.assertRaises(ValueError, make_archive, base_name, 'xxx')
 
-    @requires_zlib
+    @support.requires_zlib
     def test_make_archive_owner_group(self):
         # testing make_archive with owner and group, with various combinations
         # this works even if there's not gid/uid support
@@ -1161,7 +1154,7 @@ class TestShutil(unittest.TestCase):
         self.assertTrue(os.path.isfile(res))
 
 
-    @requires_zlib
+    @support.requires_zlib
     @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
     def test_tarfile_root_owner(self):
         root_dir, base_dir = self._create_files()
@@ -1206,7 +1199,7 @@ class TestShutil(unittest.TestCase):
             self.assertEqual(make_archive('test', 'tar'), 'test.tar')
             self.assertTrue(os.path.isfile('test.tar'))
 
-    @requires_zlib
+    @support.requires_zlib
     def test_make_zipfile_in_curdir(self):
         # Issue #21280
         root_dir = self.mkdtemp()
@@ -1230,34 +1223,47 @@ class TestShutil(unittest.TestCase):
         formats = [name for name, params in get_archive_formats()]
         self.assertNotIn('xxx', formats)
 
-    @requires_zlib
-    def test_unpack_archive(self):
-        formats = ['tar', 'gztar', 'zip']
-        if BZ2_SUPPORTED:
-            formats.append('bztar')
-        if LZMA_SUPPORTED:
-            formats.append('xztar')
-
+    def check_unpack_archive(self, format):
         root_dir, base_dir = self._create_files()
         expected = rlistdir(root_dir)
         expected.remove('outer')
-        for format in formats:
-            base_name = os.path.join(self.mkdtemp(), 'archive')
-            filename = make_archive(base_name, format, root_dir, base_dir)
-
-            # let's try to unpack it now
-            tmpdir2 = self.mkdtemp()
-            unpack_archive(filename, tmpdir2)
-            self.assertEqual(rlistdir(tmpdir2), expected)
-
-            # and again, this time with the format specified
-            tmpdir3 = self.mkdtemp()
-            unpack_archive(filename, tmpdir3, format=format)
-            self.assertEqual(rlistdir(tmpdir3), expected)
+
+        base_name = os.path.join(self.mkdtemp(), 'archive')
+        filename = make_archive(base_name, format, root_dir, base_dir)
+
+        # let's try to unpack it now
+        tmpdir2 = self.mkdtemp()
+        unpack_archive(filename, tmpdir2)
+        self.assertEqual(rlistdir(tmpdir2), expected)
+
+        # and again, this time with the format specified
+        tmpdir3 = self.mkdtemp()
+        unpack_archive(filename, tmpdir3, format=format)
+        self.assertEqual(rlistdir(tmpdir3), expected)
+
         self.assertRaises(shutil.ReadError, unpack_archive, TESTFN)
         self.assertRaises(ValueError, unpack_archive, TESTFN, format='xxx')
 
-    def test_unpack_registery(self):
+    def test_unpack_archive_tar(self):
+        self.check_unpack_archive('tar')
+
+    @support.requires_zlib
+    def test_unpack_archive_gztar(self):
+        self.check_unpack_archive('gztar')
+
+    @support.requires_bz2
+    def test_unpack_archive_bztar(self):
+        self.check_unpack_archive('bztar')
+
+    @support.requires_lzma
+    def test_unpack_archive_xztar(self):
+        self.check_unpack_archive('xztar')
+
+    @support.requires_zlib
+    def test_unpack_archive_zip(self):
+        self.check_unpack_archive('zip')
+
+    def test_unpack_registry(self):
 
         formats = get_unpack_formats()
 
index c151a50..ea3ca28 100644 (file)
@@ -709,7 +709,7 @@ class GeneralModuleTests(unittest.TestCase):
             raise socket.gaierror
 
     def testSendtoErrors(self):
-        # Testing that sendto doesn't masks failures. See #10169.
+        # Testing that sendto doesn't mask failures. See #10169.
         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         self.addCleanup(s.close)
         s.bind(('', 0))
@@ -1442,11 +1442,31 @@ class GeneralModuleTests(unittest.TestCase):
         # type and populates the socket object.
         #
         # On Windows this trick won't work, so the test is skipped.
-        fd, _ = tempfile.mkstemp()
+        fd, path = tempfile.mkstemp()
+        self.addCleanup(os.unlink, path)
         with socket.socket(family=42424, type=13331, fileno=fd) as s:
             self.assertEqual(s.family, 42424)
             self.assertEqual(s.type, 13331)
 
+    @unittest.skipUnless(hasattr(os, 'sendfile'), 'test needs os.sendfile()')
+    def test__sendfile_use_sendfile(self):
+        class File:
+            def __init__(self, fd):
+                self.fd = fd
+
+            def fileno(self):
+                return self.fd
+        with socket.socket() as sock:
+            fd = os.open(os.curdir, os.O_RDONLY)
+            os.close(fd)
+            with self.assertRaises(socket._GiveupOnSendfile):
+                sock._sendfile_use_sendfile(File(fd))
+            with self.assertRaises(OverflowError):
+                sock._sendfile_use_sendfile(File(2**1000))
+            with self.assertRaises(TypeError):
+                sock._sendfile_use_sendfile(File(None))
+
+
 @unittest.skipUnless(HAVE_SOCKET_CAN, 'SocketCan required for this test.')
 class BasicCANTest(unittest.TestCase):
 
@@ -4610,9 +4630,10 @@ class BufferIOTest(SocketConnectedTest):
         SocketConnectedTest.__init__(self, methodName=methodName)
 
     def testRecvIntoArray(self):
-        buf = bytearray(1024)
+        buf = array.array("B", [0] * len(MSG))
         nbytes = self.cli_conn.recv_into(buf)
         self.assertEqual(nbytes, len(MSG))
+        buf = buf.tobytes()
         msg = buf[:len(MSG)]
         self.assertEqual(msg, MSG)
 
@@ -4639,9 +4660,10 @@ class BufferIOTest(SocketConnectedTest):
     _testRecvIntoMemoryview = _testRecvIntoArray
 
     def testRecvFromIntoArray(self):
-        buf = bytearray(1024)
+        buf = array.array("B", [0] * len(MSG))
         nbytes, addr = self.cli_conn.recvfrom_into(buf)
         self.assertEqual(nbytes, len(MSG))
+        buf = buf.tobytes()
         msg = buf[:len(MSG)]
         self.assertEqual(msg, MSG)
 
@@ -4695,9 +4717,17 @@ def isTipcAvailable():
     """
     if not hasattr(socket, "AF_TIPC"):
         return False
-    if not os.path.isfile("/proc/modules"):
-        return False
-    with open("/proc/modules") as f:
+    try:
+        f = open("/proc/modules")
+    except IOError as e:
+        # It's ok if the file does not exist, is a directory or if we
+        # have not the permission to read it. In any other case it's a
+        # real error, so raise it again.
+        if e.errno in (errno.ENOENT, errno.EISDIR, errno.EACCES):
+            return False
+        else:
+            raise
+    with f:
         for line in f:
             if line.startswith("tipc "):
                 return True
index d2fc36d..5515583 100644 (file)
@@ -23,6 +23,9 @@ ssl = support.import_module("ssl")
 
 PROTOCOLS = sorted(ssl._PROTOCOL_NAMES)
 HOST = support.HOST
+IS_LIBRESSL = ssl.OPENSSL_VERSION.startswith('LibreSSL')
+IS_OPENSSL_1_1 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0)
+
 
 def data_file(*name):
     return os.path.join(os.path.dirname(__file__), *name)
@@ -54,6 +57,8 @@ CRLFILE = data_file("revocation.crl")
 SIGNED_CERTFILE = data_file("keycert3.pem")
 SIGNED_CERTFILE2 = data_file("keycert4.pem")
 SIGNING_CA = data_file("pycacert.pem")
+# cert with all kinds of subject alt names
+ALLSANFILE = data_file("allsans.pem")
 
 REMOTE_HOST = "self-signed.pythontest.net"
 REMOTE_ROOT_CERT = data_file("selfsigned_pythontestdotnet.pem")
@@ -143,8 +148,8 @@ class BasicSocketTests(unittest.TestCase):
     def test_str_for_enums(self):
         # Make sure that the PROTOCOL_* constants have enum-like string
         # reprs.
-        proto = ssl.PROTOCOL_SSLv23
-        self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_SSLv23')
+        proto = ssl.PROTOCOL_TLS
+        self.assertEqual(str(proto), '_SSLMethod.PROTOCOL_TLS')
         ctx = ssl.SSLContext(proto)
         self.assertIs(ctx.protocol, proto)
 
@@ -276,6 +281,27 @@ class BasicSocketTests(unittest.TestCase):
 
         self.assertEqual(p['subjectAltName'], san)
 
+    def test_parse_all_sans(self):
+        p = ssl._ssl._test_decode_cert(ALLSANFILE)
+        self.assertEqual(p['subjectAltName'],
+            (
+                ('DNS', 'allsans'),
+                ('othername', '<unsupported>'),
+                ('othername', '<unsupported>'),
+                ('email', 'user@example.org'),
+                ('DNS', 'www.example.org'),
+                ('DirName',
+                    ((('countryName', 'XY'),),
+                    (('localityName', 'Castle Anthrax'),),
+                    (('organizationName', 'Python Software Foundation'),),
+                    (('commonName', 'dirname example'),))),
+                ('URI', 'https://www.python.org/'),
+                ('IP Address', '127.0.0.1'),
+                ('IP Address', '0:0:0:0:0:0:0:1\n'),
+                ('Registered ID', '1.2.3.4.5')
+            )
+        )
+
     def test_DER_to_PEM(self):
         with open(CAFILE_CACERT, 'r') as f:
             pem = f.read()
@@ -312,8 +338,8 @@ class BasicSocketTests(unittest.TestCase):
         self.assertGreaterEqual(status, 0)
         self.assertLessEqual(status, 15)
         # Version string as returned by {Open,Libre}SSL, the format might change
-        if "LibreSSL" in s:
-            self.assertTrue(s.startswith("LibreSSL {:d}.{:d}".format(major, minor)),
+        if IS_LIBRESSL:
+            self.assertTrue(s.startswith("LibreSSL {:d}".format(major)),
                             (s, t, hex(n)))
         else:
             self.assertTrue(s.startswith("OpenSSL {:d}.{:d}.{:d}".format(major, minor, fix)),
@@ -790,7 +816,8 @@ class ContextTests(unittest.TestCase):
     def test_constructor(self):
         for protocol in PROTOCOLS:
             ssl.SSLContext(protocol)
-        self.assertRaises(TypeError, ssl.SSLContext)
+        ctx = ssl.SSLContext()
+        self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
         self.assertRaises(ValueError, ssl.SSLContext, -1)
         self.assertRaises(ValueError, ssl.SSLContext, 42)
 
@@ -811,15 +838,15 @@ class ContextTests(unittest.TestCase):
     def test_options(self):
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
         # OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 is the default value
-        self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3,
-                         ctx.options)
+        default = (ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3)
+        if not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0):
+            default |= ssl.OP_NO_COMPRESSION
+        self.assertEqual(default, ctx.options)
         ctx.options |= ssl.OP_NO_TLSv1
-        self.assertEqual(ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1,
-                         ctx.options)
+        self.assertEqual(default | ssl.OP_NO_TLSv1, ctx.options)
         if can_clear_options():
-            ctx.options = (ctx.options & ~ssl.OP_NO_SSLv2) | ssl.OP_NO_TLSv1
-            self.assertEqual(ssl.OP_ALL | ssl.OP_NO_TLSv1 | ssl.OP_NO_SSLv3,
-                             ctx.options)
+            ctx.options = (ctx.options & ~ssl.OP_NO_TLSv1)
+            self.assertEqual(default, ctx.options)
             ctx.options = 0
             # Ubuntu has OP_NO_SSLv3 forced on by default
             self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3)
@@ -1155,6 +1182,7 @@ class ContextTests(unittest.TestCase):
         self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH')
 
     @unittest.skipIf(sys.platform == "win32", "not-Windows specific")
+    @unittest.skipIf(IS_LIBRESSL, "LibreSSL doesn't support env vars")
     def test_load_default_certs_env(self):
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
         with support.EnvironmentVarGuard() as env:
@@ -1750,13 +1778,13 @@ class NetworkedBIOTests(unittest.TestCase):
             sslobj = ctx.wrap_bio(incoming, outgoing, False, REMOTE_HOST)
             self.assertIs(sslobj._sslobj.owner, sslobj)
             self.assertIsNone(sslobj.cipher())
-            self.assertIsNone(sslobj.shared_ciphers())
+            self.assertIsNotNone(sslobj.shared_ciphers())
             self.assertRaises(ValueError, sslobj.getpeercert)
             if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
                 self.assertIsNone(sslobj.get_channel_binding('tls-unique'))
             self.ssl_io_loop(sock, incoming, outgoing, sslobj.do_handshake)
             self.assertTrue(sslobj.cipher())
-            self.assertIsNone(sslobj.shared_ciphers())
+            self.assertIsNotNone(sslobj.shared_ciphers())
             self.assertTrue(sslobj.getpeercert())
             if 'tls-unique' in ssl.CHANNEL_BINDING_TYPES:
                 self.assertTrue(sslobj.get_channel_binding('tls-unique'))
@@ -2633,7 +2661,7 @@ else:
                     s.close()
 
         def test_socketserver(self):
-            """Using a SocketServer to create and manage SSL connections."""
+            """Using socketserver to create and manage SSL connections."""
             server = make_https_server(self, certfile=CERTFILE)
             # try to connect
             if support.verbose:
@@ -2660,8 +2688,6 @@ else:
 
         def test_asyncore_server(self):
             """Check the example asyncore integration."""
-            indata = "TEST MESSAGE of mixed case\n"
-
             if support.verbose:
                 sys.stdout.write("\n")
 
@@ -2793,20 +2819,13 @@ else:
                         # consume data
                         s.read()
 
-                data = b"data"
-
                 # read(-1, buffer) is supported, even though read(-1) is not
+                data = b"data"
                 s.send(data)
                 buffer = bytearray(len(data))
                 self.assertEqual(s.read(-1, buffer), len(data))
                 self.assertEqual(buffer, data)
 
-                # recv/read(0) should return no data
-                s.send(data)
-                self.assertEqual(s.recv(0), b"")
-                self.assertEqual(s.read(0), b"")
-                self.assertEqual(s.read(), data)
-
                 # Make sure sendmsg et al are disallowed to avoid
                 # inadvertent disclosure of data and/or corruption
                 # of the encrypted data stream
@@ -2822,6 +2841,26 @@ else:
 
                 s.close()
 
+        def test_recv_zero(self):
+            server = ThreadedEchoServer(CERTFILE)
+            server.__enter__()
+            self.addCleanup(server.__exit__, None, None)
+            s = socket.create_connection((HOST, server.port))
+            self.addCleanup(s.close)
+            s = ssl.wrap_socket(s, suppress_ragged_eofs=False)
+            self.addCleanup(s.close)
+
+            # recv/read(0) should return no data
+            s.send(b"data")
+            self.assertEqual(s.recv(0), b"")
+            self.assertEqual(s.read(0), b"")
+            self.assertEqual(s.read(), b"data")
+
+            # Should not block if the other end sends no data
+            s.setblocking(False)
+            self.assertEqual(s.recv(0), b"")
+            self.assertEqual(s.recv_into(bytearray()), 0)
+
         def test_nonblocking_send(self):
             server = ThreadedEchoServer(CERTFILE,
                                         certreqs=ssl.CERT_NONE,
@@ -2980,7 +3019,7 @@ else:
                 with context.wrap_socket(socket.socket()) as s:
                     self.assertIs(s.version(), None)
                     s.connect((HOST, server.port))
-                    self.assertEqual(s.version(), "TLSv1")
+                    self.assertEqual(s.version(), 'TLSv1')
                 self.assertIs(s.version(), None)
 
         @unittest.skipUnless(ssl.HAS_ECDH, "test requires ECDH-enabled OpenSSL")
@@ -3122,24 +3161,36 @@ else:
                 (['http/3.0', 'http/4.0'], None)
             ]
             for client_protocols, expected in protocol_tests:
-                server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+                server_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
                 server_context.load_cert_chain(CERTFILE)
                 server_context.set_alpn_protocols(server_protocols)
-                client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+                client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
                 client_context.load_cert_chain(CERTFILE)
                 client_context.set_alpn_protocols(client_protocols)
-                stats = server_params_test(client_context, server_context,
-                                           chatty=True, connectionchatty=True)
 
-                msg = "failed trying %s (s) and %s (c).\n" \
-                      "was expecting %s, but got %%s from the %%s" \
-                          % (str(server_protocols), str(client_protocols),
-                             str(expected))
-                client_result = stats['client_alpn_protocol']
-                self.assertEqual(client_result, expected, msg % (client_result, "client"))
-                server_result = stats['server_alpn_protocols'][-1] \
-                    if len(stats['server_alpn_protocols']) else 'nothing'
-                self.assertEqual(server_result, expected, msg % (server_result, "server"))
+                try:
+                    stats = server_params_test(client_context,
+                                               server_context,
+                                               chatty=True,
+                                               connectionchatty=True)
+                except ssl.SSLError as e:
+                    stats = e
+
+                if expected is None and IS_OPENSSL_1_1:
+                    # OpenSSL 1.1.0 raises handshake error
+                    self.assertIsInstance(stats, ssl.SSLError)
+                else:
+                    msg = "failed trying %s (s) and %s (c).\n" \
+                        "was expecting %s, but got %%s from the %%s" \
+                            % (str(server_protocols), str(client_protocols),
+                                str(expected))
+                    client_result = stats['client_alpn_protocol']
+                    self.assertEqual(client_result, expected,
+                                     msg % (client_result, "client"))
+                    server_result = stats['server_alpn_protocols'][-1] \
+                        if len(stats['server_alpn_protocols']) else 'nothing'
+                    self.assertEqual(server_result, expected,
+                                     msg % (server_result, "server"))
 
         def test_selected_npn_protocol(self):
             # selected_npn_protocol() is None unless NPN is used
@@ -3287,13 +3338,23 @@ else:
             client_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
             client_context.verify_mode = ssl.CERT_REQUIRED
             client_context.load_verify_locations(SIGNING_CA)
-            client_context.set_ciphers("RC4")
-            server_context.set_ciphers("AES:RC4")
+            if ssl.OPENSSL_VERSION_INFO >= (1, 0, 2):
+                client_context.set_ciphers("AES128:AES256")
+                server_context.set_ciphers("AES256")
+                alg1 = "AES256"
+                alg2 = "AES-256"
+            else:
+                client_context.set_ciphers("AES:3DES")
+                server_context.set_ciphers("3DES")
+                alg1 = "3DES"
+                alg2 = "DES-CBC3"
+
             stats = server_params_test(client_context, server_context)
             ciphers = stats['server_shared_ciphers'][0]
             self.assertGreater(len(ciphers), 0)
             for name, tls_version, bits in ciphers:
-                self.assertIn("RC4", name.split("-"))
+                if not alg1 in name.split("-") and alg2 not in name:
+                    self.fail(name)
 
         def test_read_write_after_close_raises_valuerror(self):
             context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
index 3ecb27d..36630a1 100644 (file)
@@ -97,7 +97,7 @@ class StructSeqTest(unittest.TestCase):
         class Exc(Exception):
             pass
 
-        # Devious code could crash structseqs' contructors
+        # Devious code could crash structseqs' constructors
         class C:
             def __getitem__(self, i):
                 raise Exc
index 4704d49..758e094 100644 (file)
@@ -686,7 +686,7 @@ class ProcessTestCase(BaseTestCase):
         self.assertEqual(stdout, "banana")
         self.assertStderrEqual(stderr.encode(), b"pineapple\npear\n")
 
-    def test_communicate_timeout_large_ouput(self):
+    def test_communicate_timeout_large_output(self):
         # Test an expiring timeout while the child is outputting lots of data.
         p = subprocess.Popen([sys.executable, "-c",
                               'import sys,os,time;'
@@ -1354,7 +1354,7 @@ class POSIXProcessTestCase(BaseTestCase):
             desired_exception = e
             desired_exception.strerror += ': ' + repr(self._nonexistent_dir)
         else:
-            self.fail("chdir to nonexistant directory %s succeeded." %
+            self.fail("chdir to nonexistent directory %s succeeded." %
                       self._nonexistent_dir)
         return desired_exception
 
index 2c00417..5e0f990 100644 (file)
@@ -1,5 +1,6 @@
 import importlib
 import shutil
+import stat
 import sys
 import os
 import unittest
@@ -9,14 +10,9 @@ import errno
 from test import support
 
 TESTFN = support.TESTFN
-TESTDIRN = os.path.basename(tempfile.mkdtemp(dir='.'))
 
 
 class TestSupport(unittest.TestCase):
-    def setUp(self):
-        support.unlink(TESTFN)
-        support.rmtree(TESTDIRN)
-    tearDown = setUp
 
     def test_import_module(self):
         support.import_module("ftplib")
@@ -48,11 +44,28 @@ class TestSupport(unittest.TestCase):
         support.unlink(TESTFN)
 
     def test_rmtree(self):
-        os.mkdir(TESTDIRN)
-        os.mkdir(os.path.join(TESTDIRN, TESTDIRN))
-        support.rmtree(TESTDIRN)
-        self.assertFalse(os.path.exists(TESTDIRN))
-        support.rmtree(TESTDIRN)
+        dirpath = support.TESTFN + 'd'
+        subdirpath = os.path.join(dirpath, 'subdir')
+        os.mkdir(dirpath)
+        os.mkdir(subdirpath)
+        support.rmtree(dirpath)
+        self.assertFalse(os.path.exists(dirpath))
+        with support.swap_attr(support, 'verbose', 0):
+            support.rmtree(dirpath)
+
+        os.mkdir(dirpath)
+        os.mkdir(subdirpath)
+        os.chmod(dirpath, stat.S_IRUSR|stat.S_IXUSR)
+        with support.swap_attr(support, 'verbose', 0):
+            support.rmtree(dirpath)
+        self.assertFalse(os.path.exists(dirpath))
+
+        os.mkdir(dirpath)
+        os.mkdir(subdirpath)
+        os.chmod(dirpath, 0)
+        with support.swap_attr(support, 'verbose', 0):
+            support.rmtree(dirpath)
+        self.assertFalse(os.path.exists(dirpath))
 
     def test_forget(self):
         mod_filename = TESTFN + '.py'
@@ -227,8 +240,10 @@ class TestSupport(unittest.TestCase):
         self.assertEqual(cm.exception.errno, errno.EBADF)
 
     def test_check_syntax_error(self):
-        support.check_syntax_error(self, "def class")
+        support.check_syntax_error(self, "def class", lineno=1, offset=9)
         self.assertRaises(AssertionError, support.check_syntax_error, self, "1")
+        #with self.assertRaises(AssertionError):
+            #support.check_syntax_error(self, "x=1")
 
     def test_CleanImport(self):
         import importlib
index e5e7b83..fbb1bdc 100644 (file)
@@ -148,15 +148,23 @@ class SymtableTest(unittest.TestCase):
     def test_filename_correct(self):
         ### Bug tickler: SyntaxError file name correct whether error raised
         ### while parsing or building symbol table.
-        def checkfilename(brokencode):
+        def checkfilename(brokencode, offset):
             try:
                 symtable.symtable(brokencode, "spam", "exec")
             except SyntaxError as e:
                 self.assertEqual(e.filename, "spam")
+                self.assertEqual(e.lineno, 1)
+                self.assertEqual(e.offset, offset)
             else:
                 self.fail("no SyntaxError for %r" % (brokencode,))
-        checkfilename("def f(x): foo)(")  # parse-time
-        checkfilename("def f(x): global x")  # symtable-build-time
+        checkfilename("def f(x): foo)(", 14)  # parse-time
+        checkfilename("def f(x): global x", 10)  # symtable-build-time
+        symtable.symtable("pass", b"spam", "exec")
+        with self.assertRaises(TypeError):
+            symtable.symtable("pass", bytearray(b"spam"), "exec")
+        symtable.symtable("pass", memoryview(b"spam"), "exec")
+        with self.assertRaises(TypeError):
+            symtable.symtable("pass", list(b"spam"), "exec")
 
     def test_eval(self):
         symbols = symtable.symtable("42", "?", "eval")
index 057441c..301c142 100644 (file)
@@ -342,7 +342,9 @@ isn't, there should be a syntax error.
      ...
    SyntaxError: 'break' outside loop
 
-This should probably raise a better error than a SystemError (or none at all).
+This raises a SyntaxError, it used to raise a SystemError.
+Context for this change can be found on issue #27514
+
 In 2.5 there was a missing exception and an assert was triggered in a debug
 build.  The number of blocks must be greater than CO_MAXBLOCKS.  SF #1565514
 
@@ -370,7 +372,7 @@ build.  The number of blocks must be greater than CO_MAXBLOCKS.  SF #1565514
    ...                      break
    Traceback (most recent call last):
      ...
-   SystemError: too many statically nested blocks
+   SyntaxError: too many statically nested blocks
 
 Misuse of the nonlocal statement can lead to a few unique syntax errors.
 
@@ -538,7 +540,7 @@ from test import support
 class SyntaxTestCase(unittest.TestCase):
 
     def _check_error(self, code, errtext,
-                     filename="<testcase>", mode="exec", subclass=None):
+                     filename="<testcase>", mode="exec", subclass=None, lineno=None, offset=None):
         """Check that compiling code raises SyntaxError with errtext.
 
         errtest is a regular expression that must be present in the
@@ -553,6 +555,11 @@ class SyntaxTestCase(unittest.TestCase):
             mo = re.search(errtext, str(err))
             if mo is None:
                 self.fail("SyntaxError did not contain '%r'" % (errtext,))
+            self.assertEqual(err.filename, filename)
+            if lineno is not None:
+                self.assertEqual(err.lineno, lineno)
+            if offset is not None:
+                self.assertEqual(err.offset, offset)
         else:
             self.fail("compile() did not raise SyntaxError")
 
@@ -563,7 +570,7 @@ class SyntaxTestCase(unittest.TestCase):
         self._check_error("del f()", "delete")
 
     def test_global_err_then_warn(self):
-        # Bug tickler:  The SyntaxError raised for one global statement
+        # Bug #763201:  The SyntaxError raised for one global statement
         # shouldn't be clobbered by a SyntaxWarning issued for a later one.
         source = """if 1:
             def error(a):
@@ -573,7 +580,7 @@ class SyntaxTestCase(unittest.TestCase):
                 global b  # SyntaxWarning
             """
         warnings.filterwarnings(action='ignore', category=SyntaxWarning)
-        self._check_error(source, "global")
+        self._check_error(source, "global", lineno=3, offset=16)
         warnings.filters.pop(0)
 
     def test_break_outside_loop(self):
index a531879..4435d69 100644 (file)
@@ -803,6 +803,7 @@ class SysModuleTest(unittest.TestCase):
         c = sys.getallocatedblocks()
         self.assertIn(c, range(b - 50, b + 50))
 
+    @test.support.requires_type_collecting
     def test_is_finalizing(self):
         self.assertIs(sys.is_finalizing(), False)
         # Don't use the atexit module because _Py_Finalizing is only set
@@ -1083,9 +1084,12 @@ class SizeofTest(unittest.TestCase):
         check((1,2,3), vsize('') + 3*self.P)
         # type
         # static type: PyTypeObject
-        s = vsize('P2n15Pl4Pn9Pn11PIP')
+        fmt = 'P2n15Pl4Pn9Pn11PIP'
+        if hasattr(sys, 'getcounts'):
+            fmt += '3n2P'
+        s = vsize(fmt)
         check(int, s)
-        s = vsize('P2n15Pl4Pn9Pn11PIP'  # PyTypeObject
+        s = vsize(fmt +                 # PyTypeObject
                   '3P'                  # PyAsyncMethods
                   '36P'                 # PyNumberMethods
                   '3P'                  # PyMappingMethods
index abfb34d..1efb841 100644 (file)
@@ -3,6 +3,7 @@ import os
 import io
 from hashlib import md5
 from contextlib import contextmanager
+from random import Random
 
 import unittest
 import unittest.mock
@@ -349,12 +350,17 @@ class CommonReadTest(ReadTest):
 
     def test_ignore_zeros(self):
         # Test TarFile's ignore_zeros option.
+        # generate 512 pseudorandom bytes
+        data = Random(0).getrandbits(512*8).to_bytes(512, 'big')
         for char in (b'\0', b'a'):
             # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
             # are ignored correctly.
             with self.open(tmpname, "w") as fobj:
                 fobj.write(char * 1024)
-                fobj.write(tarfile.TarInfo("foo").tobuf())
+                tarinfo = tarfile.TarInfo("foo")
+                tarinfo.size = len(data)
+                fobj.write(tarinfo.tobuf())
+                fobj.write(data)
 
             tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
             try:
index a44184f..5a33c15 100644 (file)
@@ -444,6 +444,37 @@ What a mess!
         text = "aa \xe4\xe4-\xe4\xe4"
         self.check_wrap(text, 7, ["aa \xe4\xe4-", "\xe4\xe4"])
 
+    def test_non_breaking_space(self):
+        text = 'This is a sentence with non-breaking\N{NO-BREAK SPACE}space.'
+
+        self.check_wrap(text, 20,
+                        ['This is a sentence',
+                         'with non-',
+                         'breaking\N{NO-BREAK SPACE}space.'],
+                        break_on_hyphens=True)
+
+        self.check_wrap(text, 20,
+                        ['This is a sentence',
+                         'with',
+                         'non-breaking\N{NO-BREAK SPACE}space.'],
+                        break_on_hyphens=False)
+
+    def test_narrow_non_breaking_space(self):
+        text = ('This is a sentence with non-breaking'
+                '\N{NARROW NO-BREAK SPACE}space.')
+
+        self.check_wrap(text, 20,
+                        ['This is a sentence',
+                         'with non-',
+                         'breaking\N{NARROW NO-BREAK SPACE}space.'],
+                        break_on_hyphens=True)
+
+        self.check_wrap(text, 20,
+                        ['This is a sentence',
+                         'with',
+                         'non-breaking\N{NARROW NO-BREAK SPACE}space.'],
+                        break_on_hyphens=False)
+
 
 class MaxLinesTestCase(BaseTestCase):
     text = "Hello there, how are you this fine day?  I'm glad to hear it!"
index b49a961..b630509 100644 (file)
@@ -3,7 +3,8 @@ Tests for the threading module.
 """
 
 import test.support
-from test.support import verbose, strip_python_stderr, import_module, cpython_only
+from test.support import (verbose, import_module, cpython_only,
+                          requires_type_collecting)
 from test.support.script_helper import assert_python_ok, assert_python_failure
 
 import random
@@ -987,6 +988,7 @@ class ThreadingExceptionTests(BaseTestCase):
         self.assertIn("ZeroDivisionError", err)
         self.assertNotIn("Unhandled exception", err)
 
+    @requires_type_collecting
     def test_print_exception_stderr_is_none_1(self):
         script = r"""if True:
             import sys
@@ -1041,6 +1043,24 @@ class ThreadingExceptionTests(BaseTestCase):
         self.assertEqual(out, b'')
         self.assertNotIn("Unhandled exception", err.decode())
 
+    def test_bare_raise_in_brand_new_thread(self):
+        def bare_raise():
+            raise
+
+        class Issue27558(threading.Thread):
+            exc = None
+
+            def run(self):
+                try:
+                    bare_raise()
+                except Exception as exc:
+                    self.exc = exc
+
+        thread = Issue27558()
+        thread.start()
+        thread.join()
+        self.assertIsNotNone(thread.exc)
+        self.assertIsInstance(thread.exc, RuntimeError)
 
 class TimerTests(BaseTestCase):
 
diff --git a/Lib/test/test_tools/test_fixcid.py b/Lib/test/test_tools/test_fixcid.py
new file mode 100644 (file)
index 0000000..bce029b
--- /dev/null
@@ -0,0 +1,92 @@
+'''Test Tools/scripts/fixcid.py.'''
+
+from io import StringIO
+import os, os.path
+import runpy
+import sys
+from test import support
+from test.test_tools import skip_if_missing, scriptsdir
+import unittest
+
+skip_if_missing()
+
+class Test(unittest.TestCase):
+    def test_parse_strings(self):
+        old1 = 'int xx = "xx\\"xx"[xx];\n'
+        old2 = "int xx = 'x\\'xx' + xx;\n"
+        output = self.run_script(old1 + old2)
+        new1 = 'int yy = "xx\\"xx"[yy];\n'
+        new2 = "int yy = 'x\\'xx' + yy;\n"
+        self.assertMultiLineEqual(output,
+            "1\n"
+            "< {old1}"
+            "> {new1}"
+            "{new1}"
+            "2\n"
+            "< {old2}"
+            "> {new2}"
+            "{new2}".format(old1=old1, old2=old2, new1=new1, new2=new2)
+        )
+
+    def test_alter_comments(self):
+        output = self.run_script(
+            substfile=
+                "xx yy\n"
+                "*aa bb\n",
+            args=("-c", "-",),
+            input=
+                "/* xx altered */\n"
+                "int xx;\n"
+                "/* aa unaltered */\n"
+                "int aa;\n",
+        )
+        self.assertMultiLineEqual(output,
+            "1\n"
+            "< /* xx altered */\n"
+            "> /* yy altered */\n"
+            "/* yy altered */\n"
+            "2\n"
+            "< int xx;\n"
+            "> int yy;\n"
+            "int yy;\n"
+            "/* aa unaltered */\n"
+            "4\n"
+            "< int aa;\n"
+            "> int bb;\n"
+            "int bb;\n"
+        )
+
+    def test_directory(self):
+        os.mkdir(support.TESTFN)
+        self.addCleanup(support.rmtree, support.TESTFN)
+        c_filename = os.path.join(support.TESTFN, "file.c")
+        with open(c_filename, "w") as file:
+            file.write("int xx;\n")
+        with open(os.path.join(support.TESTFN, "file.py"), "w") as file:
+            file.write("xx = 'unaltered'\n")
+        script = os.path.join(scriptsdir, "fixcid.py")
+        output = self.run_script(args=(support.TESTFN,))
+        self.assertMultiLineEqual(output,
+            "{}:\n"
+            "1\n"
+            '< int xx;\n'
+            '> int yy;\n'.format(c_filename)
+        )
+
+    def run_script(self, input="", *, args=("-",), substfile="xx yy\n"):
+        substfilename = support.TESTFN + ".subst"
+        with open(substfilename, "w") as file:
+            file.write(substfile)
+        self.addCleanup(support.unlink, substfilename)
+
+        argv = ["fixcid.py", "-s", substfilename] + list(args)
+        script = os.path.join(scriptsdir, "fixcid.py")
+        with support.swap_attr(sys, "argv", argv), \
+                support.swap_attr(sys, "stdin", StringIO(input)), \
+                support.captured_stdout() as output, \
+                support.captured_stderr():
+            try:
+                runpy.run_path(script, run_name="__main__")
+            except SystemExit as exit:
+                self.assertEqual(exit.code, 0)
+        return output.getvalue()
index 6eaa8dd..ce6f549 100644 (file)
@@ -4,9 +4,13 @@ import os
 import unittest
 
 from test.support.script_helper import assert_python_ok
-from test.test_tools import toolsdir
+from test.test_tools import skip_if_missing, toolsdir
 from test.support import temp_cwd
 
+
+skip_if_missing()
+
+
 class Test_pygettext(unittest.TestCase):
     """Tests for the pygettext.py tool"""
 
index 03dff84..f66a3bc 100644 (file)
@@ -311,11 +311,11 @@ class TestCoverage(unittest.TestCase):
         with captured_stdout() as stdout:
             self._coverage(tracer)
         stdout = stdout.getvalue()
-        self.assertTrue("pprint.py" in stdout)
-        self.assertTrue("case.py" in stdout)   # from unittest
+        self.assertIn("pprint.py", stdout)
+        self.assertIn("case.py", stdout)   # from unittest
         files = os.listdir(TESTFN)
-        self.assertTrue("pprint.cover" in files)
-        self.assertTrue("unittest.case.cover" in files)
+        self.assertIn("pprint.cover", files)
+        self.assertIn("unittest.case.cover", files)
 
     def test_coverage_ignore(self):
         # Ignore all files, nothing should be traced nor printed
index b7695d6..49cedda 100644 (file)
@@ -19,7 +19,7 @@ test_frame = namedtuple('frame', ['f_code', 'f_globals', 'f_locals'])
 test_tb = namedtuple('tb', ['tb_frame', 'tb_lineno', 'tb_next'])
 
 
-class SyntaxTracebackCases(unittest.TestCase):
+class TracebackCases(unittest.TestCase):
     # For now, a very minimal set of tests.  I want to be sure that
     # formatting of SyntaxErrors works based on changes for 2.1.
 
@@ -106,10 +106,6 @@ class SyntaxTracebackCases(unittest.TestCase):
             str_name = '.'.join([X.__module__, X.__qualname__])
         self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value))
 
-    def test_without_exception(self):
-        err = traceback.format_exception_only(None, None)
-        self.assertEqual(err, ['None\n'])
-
     def test_encoded_file(self):
         # Test that tracebacks are correctly printed for encoded source files:
         # - correct line number (Issue2384)
@@ -178,6 +174,7 @@ class SyntaxTracebackCases(unittest.TestCase):
         # Issue #18960: coding spec should has no effect
         do_test("0\n# coding: GBK\n", "h\xe9 ho", 'utf-8', 5)
 
+    @support.requires_type_collecting
     def test_print_traceback_at_exit(self):
         # Issue #22599: Ensure that it is possible to use the traceback module
         # to display an exception at Python exit
@@ -455,6 +452,17 @@ class BaseExceptionReportingTests:
         msg = self.get_report(e).splitlines()
         self.assertEqual(msg[-2], '              ^')
 
+    def test_message_none(self):
+        # A message that looks like "None" should not be treated specially
+        err = self.get_report(Exception(None))
+        self.assertIn('Exception: None\n', err)
+        err = self.get_report(Exception('None'))
+        self.assertIn('Exception: None\n', err)
+        err = self.get_report(Exception())
+        self.assertIn('Exception\n', err)
+        err = self.get_report(Exception(''))
+        self.assertIn('Exception\n', err)
+
 
 class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
     #
@@ -680,8 +688,12 @@ class TestFrame(unittest.TestCase):
 class TestStack(unittest.TestCase):
 
     def test_walk_stack(self):
-        s = list(traceback.walk_stack(None))
-        self.assertGreater(len(s), 10)
+        def deeper():
+            return list(traceback.walk_stack(None))
+        s1 = list(traceback.walk_stack(None))
+        s2 = deeper()
+        self.assertEqual(len(s2) - len(s1), 1)
+        self.assertEqual(s2[1:], s1)
 
     def test_walk_tb(self):
         try:
index a7f8dd5..d203ce3 100644 (file)
@@ -4,14 +4,15 @@ import pickle
 import re
 import sys
 from unittest import TestCase, main, skipUnless, SkipTest
+from copy import copy, deepcopy
 
 from typing import Any
 from typing import TypeVar, AnyStr
 from typing import T, KT, VT  # Not in __all__.
 from typing import Union, Optional
-from typing import Tuple
+from typing import Tuple, List, MutableMapping
 from typing import Callable
-from typing import Generic
+from typing import Generic, ClassVar
 from typing import cast
 from typing import get_type_hints
 from typing import no_type_check, no_type_check_decorator
@@ -20,7 +21,12 @@ from typing import NewType
 from typing import NamedTuple
 from typing import IO, TextIO, BinaryIO
 from typing import Pattern, Match
+import abc
 import typing
+try:
+    import collections.abc as collections_abc
+except ImportError:
+    import collections as collections_abc  # Fallback for PY3.2.
 
 
 class BaseTestCase(TestCase):
@@ -39,6 +45,10 @@ class BaseTestCase(TestCase):
                 message += ' : %s' % msg
             raise self.failureException(message)
 
+    def clear_caches(self):
+        for f in typing._cleanups:
+            f()
+
 
 class Employee:
     pass
@@ -62,18 +72,11 @@ class AnyTests(BaseTestCase):
         with self.assertRaises(TypeError):
             isinstance(42, Any)
 
-    def test_any_subclass(self):
-        self.assertTrue(issubclass(Employee, Any))
-        self.assertTrue(issubclass(int, Any))
-        self.assertTrue(issubclass(type(None), Any))
-        self.assertTrue(issubclass(object, Any))
-
-    def test_others_any(self):
-        self.assertFalse(issubclass(Any, Employee))
-        self.assertFalse(issubclass(Any, int))
-        self.assertFalse(issubclass(Any, type(None)))
-        # However, Any is a subclass of object (this can't be helped).
-        self.assertTrue(issubclass(Any, object))
+    def test_any_subclass_type_error(self):
+        with self.assertRaises(TypeError):
+            issubclass(Employee, Any)
+        with self.assertRaises(TypeError):
+            issubclass(Any, Employee)
 
     def test_repr(self):
         self.assertEqual(repr(Any), 'typing.Any')
@@ -88,32 +91,21 @@ class AnyTests(BaseTestCase):
         with self.assertRaises(TypeError):
             class A(Any):
                 pass
+        with self.assertRaises(TypeError):
+            class A(type(Any)):
+                pass
 
     def test_cannot_instantiate(self):
         with self.assertRaises(TypeError):
             Any()
+        with self.assertRaises(TypeError):
+            type(Any)()
 
     def test_cannot_subscript(self):
         with self.assertRaises(TypeError):
             Any[int]
 
-    def test_any_is_subclass(self):
-        # Any should be considered a subclass of everything.
-        self.assertIsSubclass(Any, Any)
-        self.assertIsSubclass(Any, typing.List)
-        self.assertIsSubclass(Any, typing.List[int])
-        self.assertIsSubclass(Any, typing.List[T])
-        self.assertIsSubclass(Any, typing.Mapping)
-        self.assertIsSubclass(Any, typing.Mapping[str, int])
-        self.assertIsSubclass(Any, typing.Mapping[KT, VT])
-        self.assertIsSubclass(Any, Generic)
-        self.assertIsSubclass(Any, Generic[T])
-        self.assertIsSubclass(Any, Generic[KT, VT])
-        self.assertIsSubclass(Any, AnyStr)
-        self.assertIsSubclass(Any, Union)
-        self.assertIsSubclass(Any, Union[int, str])
-        self.assertIsSubclass(Any, typing.Match)
-        self.assertIsSubclass(Any, typing.Match[str])
+    def test_any_works_with_alias(self):
         # These expressions must simply not fail.
         typing.Match[Any]
         typing.Pattern[Any]
@@ -124,13 +116,8 @@ class TypeVarTests(BaseTestCase):
 
     def test_basic_plain(self):
         T = TypeVar('T')
-        # Every class is a subclass of T.
-        self.assertIsSubclass(int, T)
-        self.assertIsSubclass(str, T)
         # T equals itself.
         self.assertEqual(T, T)
-        # T is a subclass of itself.
-        self.assertIsSubclass(T, T)
         # T is an instance of TypeVar
         self.assertIsInstance(T, TypeVar)
 
@@ -139,16 +126,12 @@ class TypeVarTests(BaseTestCase):
         with self.assertRaises(TypeError):
             isinstance(42, T)
 
-    def test_basic_constrained(self):
-        A = TypeVar('A', str, bytes)
-        # Only str and bytes are subclasses of A.
-        self.assertIsSubclass(str, A)
-        self.assertIsSubclass(bytes, A)
-        self.assertNotIsSubclass(int, A)
-        # A equals itself.
-        self.assertEqual(A, A)
-        # A is a subclass of itself.
-        self.assertIsSubclass(A, A)
+    def test_typevar_subclass_type_error(self):
+        T = TypeVar('T')
+        with self.assertRaises(TypeError):
+            issubclass(int, T)
+        with self.assertRaises(TypeError):
+            issubclass(T, int)
 
     def test_constrained_error(self):
         with self.assertRaises(TypeError):
@@ -164,8 +147,9 @@ class TypeVarTests(BaseTestCase):
         self.assertEqual(Union[X, X], X)
         self.assertNotEqual(Union[X, int], Union[X])
         self.assertNotEqual(Union[X, int], Union[int])
-        self.assertEqual(Union[X, int].__union_params__, (X, int))
-        self.assertEqual(Union[X, int].__union_set_params__, {X, int})
+        self.assertEqual(Union[X, int].__args__, (X, int))
+        self.assertEqual(Union[X, int].__parameters__, (X,))
+        self.assertIs(Union[X, int].__origin__, Union)
 
     def test_union_constrained(self):
         A = TypeVar('A', str, bytes)
@@ -185,19 +169,6 @@ class TypeVarTests(BaseTestCase):
         self.assertNotEqual(TypeVar('T'), TypeVar('T'))
         self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str))
 
-    def test_subclass_as_unions(self):
-        # None of these are true -- each type var is its own world.
-        self.assertFalse(issubclass(TypeVar('T', int, str),
-                                    TypeVar('T', int, str)))
-        self.assertFalse(issubclass(TypeVar('T', int, float),
-                                    TypeVar('T', int, float, str)))
-        self.assertFalse(issubclass(TypeVar('T', int, str),
-                                    TypeVar('T', str, int)))
-        A = TypeVar('A', int, str)
-        B = TypeVar('B', int, str, float)
-        self.assertFalse(issubclass(A, B))
-        self.assertFalse(issubclass(B, A))
-
     def test_cannot_subclass_vars(self):
         with self.assertRaises(TypeError):
             class V(TypeVar('T')):
@@ -212,12 +183,6 @@ class TypeVarTests(BaseTestCase):
         with self.assertRaises(TypeError):
             TypeVar('A')()
 
-    def test_bound(self):
-        X = TypeVar('X', bound=Employee)
-        self.assertIsSubclass(Employee, X)
-        self.assertIsSubclass(Manager, X)
-        self.assertNotIsSubclass(int, X)
-
     def test_bound_errors(self):
         with self.assertRaises(TypeError):
             TypeVar('X', bound=42)
@@ -230,16 +195,27 @@ class UnionTests(BaseTestCase):
     def test_basics(self):
         u = Union[int, float]
         self.assertNotEqual(u, Union)
-        self.assertTrue(issubclass(int, u))
-        self.assertTrue(issubclass(float, u))
+
+    def test_subclass_error(self):
+        with self.assertRaises(TypeError):
+            issubclass(int, Union)
+        with self.assertRaises(TypeError):
+            issubclass(Union, int)
+        with self.assertRaises(TypeError):
+            issubclass(int, Union[int, str])
+        with self.assertRaises(TypeError):
+            issubclass(Union[int, str], int)
 
     def test_union_any(self):
         u = Union[Any]
         self.assertEqual(u, Any)
-        u = Union[int, Any]
-        self.assertEqual(u, Any)
-        u = Union[Any, int]
-        self.assertEqual(u, Any)
+        u1 = Union[int, Any]
+        u2 = Union[Any, int]
+        u3 = Union[Any, object]
+        self.assertEqual(u1, u2)
+        self.assertNotEqual(u1, Any)
+        self.assertNotEqual(u2, Any)
+        self.assertNotEqual(u3, Any)
 
     def test_union_object(self):
         u = Union[object]
@@ -249,29 +225,11 @@ class UnionTests(BaseTestCase):
         u = Union[object, int]
         self.assertEqual(u, object)
 
-    def test_union_any_object(self):
-        u = Union[object, Any]
-        self.assertEqual(u, Any)
-        u = Union[Any, object]
-        self.assertEqual(u, Any)
-
     def test_unordered(self):
         u1 = Union[int, float]
         u2 = Union[float, int]
         self.assertEqual(u1, u2)
 
-    def test_subclass(self):
-        u = Union[int, Employee]
-        self.assertTrue(issubclass(Manager, u))
-
-    def test_self_subclass(self):
-        self.assertTrue(issubclass(Union[KT, VT], Union))
-        self.assertFalse(issubclass(Union, Union[KT, VT]))
-
-    def test_multiple_inheritance(self):
-        u = Union[int, Employee]
-        self.assertTrue(issubclass(ManagingFounder, u))
-
     def test_single_class_disappears(self):
         t = Union[Employee]
         self.assertIs(t, Employee)
@@ -284,13 +242,6 @@ class UnionTests(BaseTestCase):
         u = Union[Employee, Manager]
         self.assertIs(u, Employee)
 
-    def test_weird_subclasses(self):
-        u = Union[Employee, int, float]
-        v = Union[int, float]
-        self.assertTrue(issubclass(v, u))
-        w = Union[int, Manager]
-        self.assertTrue(issubclass(w, u))
-
     def test_union_union(self):
         u = Union[int, float]
         v = Union[u, Employee]
@@ -308,15 +259,27 @@ class UnionTests(BaseTestCase):
             class C(Union):
                 pass
         with self.assertRaises(TypeError):
+            class C(type(Union)):
+                pass
+        with self.assertRaises(TypeError):
             class C(Union[int, str]):
                 pass
 
     def test_cannot_instantiate(self):
         with self.assertRaises(TypeError):
             Union()
+        with self.assertRaises(TypeError):
+            type(Union)()
         u = Union[int, float]
         with self.assertRaises(TypeError):
             u()
+        with self.assertRaises(TypeError):
+            type(u)()
+
+    def test_union_generalization(self):
+        self.assertFalse(Union[str, typing.Iterable[int]] == str)
+        self.assertFalse(Union[str, typing.Iterable[int]] == typing.Iterable[int])
+        self.assertTrue(Union[str, typing.Iterable] == typing.Iterable)
 
     def test_optional(self):
         o = Optional[int]
@@ -327,10 +290,6 @@ class UnionTests(BaseTestCase):
         with self.assertRaises(TypeError):
             Union[()]
 
-    def test_issubclass_union(self):
-        self.assertIsSubclass(Union[int, str], Union)
-        self.assertNotIsSubclass(int, Union)
-
     def test_union_instance_type_error(self):
         with self.assertRaises(TypeError):
             isinstance(42, Union[int, str])
@@ -355,43 +314,17 @@ class UnionTests(BaseTestCase):
         Union[Elem, str]  # Nor should this
 
 
-class TypeVarUnionTests(BaseTestCase):
-
-    def test_simpler(self):
-        A = TypeVar('A', int, str, float)
-        B = TypeVar('B', int, str)
-        self.assertIsSubclass(A, A)
-        self.assertIsSubclass(B, B)
-        self.assertNotIsSubclass(B, A)
-        self.assertIsSubclass(A, Union[int, str, float])
-        self.assertNotIsSubclass(Union[int, str, float], A)
-        self.assertNotIsSubclass(Union[int, str], B)
-        self.assertIsSubclass(B, Union[int, str])
-        self.assertNotIsSubclass(A, B)
-        self.assertNotIsSubclass(Union[int, str, float], B)
-        self.assertNotIsSubclass(A, Union[int, str])
-
-    def test_var_union_subclass(self):
-        self.assertTrue(issubclass(T, Union[int, T]))
-        self.assertTrue(issubclass(KT, Union[KT, VT]))
-
-    def test_var_union(self):
-        TU = TypeVar('TU', Union[int, float], None)
-        self.assertIsSubclass(int, TU)
-        self.assertIsSubclass(float, TU)
-
-
 class TupleTests(BaseTestCase):
 
     def test_basics(self):
-        self.assertTrue(issubclass(Tuple[int, str], Tuple))
-        self.assertTrue(issubclass(Tuple[int, str], Tuple[int, str]))
-        self.assertFalse(issubclass(int, Tuple))
-        self.assertFalse(issubclass(Tuple[float, str], Tuple[int, str]))
-        self.assertFalse(issubclass(Tuple[int, str, int], Tuple[int, str]))
-        self.assertFalse(issubclass(Tuple[int, str], Tuple[int, str, int]))
+        with self.assertRaises(TypeError):
+            issubclass(Tuple, Tuple[int, str])
+        with self.assertRaises(TypeError):
+            issubclass(tuple, Tuple[int, str])
+
+        class TP(tuple): ...
         self.assertTrue(issubclass(tuple, Tuple))
-        self.assertFalse(issubclass(Tuple, tuple))  # Can't have it both ways.
+        self.assertTrue(issubclass(TP, Tuple))
 
     def test_equality(self):
         self.assertEqual(Tuple[int], Tuple[int])
@@ -407,21 +340,7 @@ class TupleTests(BaseTestCase):
     def test_tuple_instance_type_error(self):
         with self.assertRaises(TypeError):
             isinstance((0, 0), Tuple[int, int])
-        with self.assertRaises(TypeError):
-            isinstance((0, 0), Tuple)
-
-    def test_tuple_ellipsis_subclass(self):
-
-        class B:
-            pass
-
-        class C(B):
-            pass
-
-        self.assertNotIsSubclass(Tuple[B], Tuple[B, ...])
-        self.assertIsSubclass(Tuple[C, ...], Tuple[B, ...])
-        self.assertNotIsSubclass(Tuple[C, ...], Tuple[B])
-        self.assertNotIsSubclass(Tuple[C], Tuple[B, ...])
+        self.assertIsInstance((0, 0), Tuple)
 
     def test_repr(self):
         self.assertEqual(repr(Tuple), 'typing.Tuple')
@@ -439,17 +358,9 @@ class TupleTests(BaseTestCase):
 class CallableTests(BaseTestCase):
 
     def test_self_subclass(self):
-        self.assertTrue(issubclass(Callable[[int], int], Callable))
-        self.assertFalse(issubclass(Callable, Callable[[int], int]))
-        self.assertTrue(issubclass(Callable[[int], int], Callable[[int], int]))
-        self.assertFalse(issubclass(Callable[[Employee], int],
-                                    Callable[[Manager], int]))
-        self.assertFalse(issubclass(Callable[[Manager], int],
-                                    Callable[[Employee], int]))
-        self.assertFalse(issubclass(Callable[[int], Employee],
-                                    Callable[[int], Manager]))
-        self.assertFalse(issubclass(Callable[[int], Manager],
-                                    Callable[[int], Employee]))
+        with self.assertRaises(TypeError):
+            self.assertTrue(issubclass(type(lambda x: x), Callable[[int], int]))
+        self.assertTrue(issubclass(type(lambda x: x), Callable))
 
     def test_eq_hash(self):
         self.assertEqual(Callable[[int], int], Callable[[int], int])
@@ -460,23 +371,26 @@ class CallableTests(BaseTestCase):
         self.assertNotEqual(Callable[[int], int], Callable[[], int])
         self.assertNotEqual(Callable[[int], int], Callable)
 
-    def test_cannot_subclass(self):
-        with self.assertRaises(TypeError):
-
-            class C(Callable):
-                pass
-
-        with self.assertRaises(TypeError):
-
-            class C(Callable[[int], int]):
-                pass
-
     def test_cannot_instantiate(self):
         with self.assertRaises(TypeError):
             Callable()
+        with self.assertRaises(TypeError):
+            type(Callable)()
         c = Callable[[int], str]
         with self.assertRaises(TypeError):
             c()
+        with self.assertRaises(TypeError):
+            type(c)()
+
+    def test_callable_wrong_forms(self):
+        with self.assertRaises(TypeError):
+            Callable[[...], int]
+        with self.assertRaises(TypeError):
+            Callable[(), int]
+        with self.assertRaises(TypeError):
+            Callable[[()], int]
+        with self.assertRaises(TypeError):
+            Callable[[int, 1], 2]
 
     def test_callable_instance_works(self):
         def f():
@@ -512,6 +426,10 @@ class CallableTests(BaseTestCase):
         self.assertEqual(get_type_hints(foo, globals(), locals()),
                          {'a': Callable[..., T]})
 
+    def test_ellipsis_in_generic(self):
+        # Shouldn't crash; see https://github.com/python/typing/issues/259
+        typing.List[Callable[..., str]]
+
 
 XK = TypeVar('XK', str, bytes)
 XV = TypeVar('XV')
@@ -595,6 +513,13 @@ class ProtocolTests(BaseTestCase):
     def test_protocol_instance_type_error(self):
         with self.assertRaises(TypeError):
             isinstance(0, typing.SupportsAbs)
+        class C1(typing.SupportsInt):
+            def __int__(self) -> int:
+                return 42
+        class C2(C1):
+            pass
+        c = C2()
+        self.assertIsInstance(c, C1)
 
 
 class GenericTests(BaseTestCase):
@@ -612,6 +537,15 @@ class GenericTests(BaseTestCase):
         with self.assertRaises(TypeError):
             Y[str, str]
 
+    def test_generic_errors(self):
+        T = TypeVar('T')
+        with self.assertRaises(TypeError):
+            Generic[T]()
+        with self.assertRaises(TypeError):
+            isinstance([], List[int])
+        with self.assertRaises(TypeError):
+            issubclass(list, List[int])
+
     def test_init(self):
         T = TypeVar('T')
         S = TypeVar('S')
@@ -622,9 +556,9 @@ class GenericTests(BaseTestCase):
 
     def test_repr(self):
         self.assertEqual(repr(SimpleMapping),
-                         __name__ + '.' + 'SimpleMapping<~XK, ~XV>')
+                         __name__ + '.' + 'SimpleMapping')
         self.assertEqual(repr(MySimpleMapping),
-                         __name__ + '.' + 'MySimpleMapping<~XK, ~XV>')
+                         __name__ + '.' + 'MySimpleMapping')
 
     def test_chain_repr(self):
         T = TypeVar('T')
@@ -648,7 +582,36 @@ class GenericTests(BaseTestCase):
         self.assertNotEqual(Z, Y[T])
 
         self.assertTrue(str(Z).endswith(
-            '.C<~T>[typing.Tuple[~S, ~T]]<~S, ~T>[~T, int]<~T>[str]'))
+            '.C[typing.Tuple[str, int]]'))
+
+    def test_new_repr(self):
+        T = TypeVar('T')
+        U = TypeVar('U', covariant=True)
+        S = TypeVar('S')
+
+        self.assertEqual(repr(List), 'typing.List')
+        self.assertEqual(repr(List[T]), 'typing.List[~T]')
+        self.assertEqual(repr(List[U]), 'typing.List[+U]')
+        self.assertEqual(repr(List[S][T][int]), 'typing.List[int]')
+        self.assertEqual(repr(List[int]), 'typing.List[int]')
+
+    def test_new_repr_complex(self):
+        T = TypeVar('T')
+        TS = TypeVar('TS')
+
+        self.assertEqual(repr(typing.Mapping[T, TS][TS, T]), 'typing.Mapping[~TS, ~T]')
+        self.assertEqual(repr(List[Tuple[T, TS]][int, T]),
+                         'typing.List[typing.Tuple[int, ~T]]')
+        self.assertEqual(repr(List[Tuple[T, T]][List[int]]),
+                 'typing.List[typing.Tuple[typing.List[int], typing.List[int]]]')
+
+    def test_new_repr_bare(self):
+        T = TypeVar('T')
+        self.assertEqual(repr(Generic[T]), 'typing.Generic[~T]')
+        self.assertEqual(repr(typing._Protocol[T]), 'typing.Protocol[~T]')
+        class C(typing.Dict[Any, Any]): ...
+        # this line should just work
+        repr(C.__mro__)
 
     def test_dict(self):
         T = TypeVar('T')
@@ -667,6 +630,234 @@ class GenericTests(BaseTestCase):
         c.bar = 'abc'
         self.assertEqual(c.__dict__, {'bar': 'abc'})
 
+    def test_false_subclasses(self):
+        class MyMapping(MutableMapping[str, str]): pass
+        self.assertNotIsInstance({}, MyMapping)
+        self.assertNotIsSubclass(dict, MyMapping)
+
+    def test_abc_bases(self):
+        class MM(MutableMapping[str, str]):
+            def __getitem__(self, k):
+                return None
+            def __setitem__(self, k, v):
+                pass
+            def __delitem__(self, k):
+                pass
+            def __iter__(self):
+                return iter(())
+            def __len__(self):
+                return 0
+        # this should just work
+        MM().update()
+        self.assertIsInstance(MM(), collections_abc.MutableMapping)
+        self.assertIsInstance(MM(), MutableMapping)
+        self.assertNotIsInstance(MM(), List)
+        self.assertNotIsInstance({}, MM)
+
+    def test_multiple_bases(self):
+        class MM1(MutableMapping[str, str], collections_abc.MutableMapping):
+            pass
+        with self.assertRaises(TypeError):
+            # consistent MRO not possible
+            class MM2(collections_abc.MutableMapping, MutableMapping[str, str]):
+                pass
+
+    def test_orig_bases(self):
+        T = TypeVar('T')
+        class C(typing.Dict[str, T]): ...
+        self.assertEqual(C.__orig_bases__, (typing.Dict[str, T],))
+
+    def test_naive_runtime_checks(self):
+        def naive_dict_check(obj, tp):
+            # Check if a dictionary conforms to Dict type
+            if len(tp.__parameters__) > 0:
+                raise NotImplementedError
+            if tp.__args__:
+                KT, VT = tp.__args__
+                return all(isinstance(k, KT) and isinstance(v, VT)
+                   for k, v in obj.items())
+        self.assertTrue(naive_dict_check({'x': 1}, typing.Dict[str, int]))
+        self.assertFalse(naive_dict_check({1: 'x'}, typing.Dict[str, int]))
+        with self.assertRaises(NotImplementedError):
+            naive_dict_check({1: 'x'}, typing.Dict[str, T])
+
+        def naive_generic_check(obj, tp):
+            # Check if an instance conforms to the generic class
+            if not hasattr(obj, '__orig_class__'):
+                raise NotImplementedError
+            return obj.__orig_class__ == tp
+        class Node(Generic[T]): ...
+        self.assertTrue(naive_generic_check(Node[int](), Node[int]))
+        self.assertFalse(naive_generic_check(Node[str](), Node[int]))
+        self.assertFalse(naive_generic_check(Node[str](), List))
+        with self.assertRaises(NotImplementedError):
+            naive_generic_check([1,2,3], Node[int])
+
+        def naive_list_base_check(obj, tp):
+            # Check if list conforms to a List subclass
+            return all(isinstance(x, tp.__orig_bases__[0].__args__[0])
+                       for x in obj)
+        class C(List[int]): ...
+        self.assertTrue(naive_list_base_check([1, 2, 3], C))
+        self.assertFalse(naive_list_base_check(['a', 'b'], C))
+
+    def test_multi_subscr_base(self):
+        T = TypeVar('T')
+        U = TypeVar('U')
+        V = TypeVar('V')
+        class C(List[T][U][V]): ...
+        class D(C, List[T][U][V]): ...
+        self.assertEqual(C.__parameters__, (V,))
+        self.assertEqual(D.__parameters__, (V,))
+        self.assertEqual(C[int].__parameters__, ())
+        self.assertEqual(D[int].__parameters__, ())
+        self.assertEqual(C[int].__args__, (int,))
+        self.assertEqual(D[int].__args__, (int,))
+        self.assertEqual(C.__bases__, (List,))
+        self.assertEqual(D.__bases__, (C, List))
+        self.assertEqual(C.__orig_bases__, (List[T][U][V],))
+        self.assertEqual(D.__orig_bases__, (C, List[T][U][V]))
+
+    def test_extended_generic_rules_eq(self):
+        T = TypeVar('T')
+        U = TypeVar('U')
+        self.assertEqual(Tuple[T, T][int], Tuple[int, int])
+        self.assertEqual(typing.Iterable[Tuple[T, T]][T], typing.Iterable[Tuple[T, T]])
+        with self.assertRaises(TypeError):
+            Tuple[T, int][()]
+        with self.assertRaises(TypeError):
+            Tuple[T, U][T, ...]
+
+        self.assertEqual(Union[T, int][int], int)
+        self.assertEqual(Union[T, U][int, Union[int, str]], Union[int, str])
+        class Base: ...
+        class Derived(Base): ...
+        self.assertEqual(Union[T, Base][Derived], Base)
+        with self.assertRaises(TypeError):
+            Union[T, int][1]
+
+        self.assertEqual(Callable[[T], T][KT], Callable[[KT], KT])
+        self.assertEqual(Callable[..., List[T]][int], Callable[..., List[int]])
+        with self.assertRaises(TypeError):
+            Callable[[T], U][..., int]
+        with self.assertRaises(TypeError):
+            Callable[[T], U][[], int]
+
+    def test_extended_generic_rules_repr(self):
+        T = TypeVar('T')
+        self.assertEqual(repr(Union[Tuple, Callable]).replace('typing.', ''),
+                         'Union[Tuple, Callable]')
+        self.assertEqual(repr(Union[Tuple, Tuple[int]]).replace('typing.', ''),
+                         'Tuple')
+        self.assertEqual(repr(Callable[..., Optional[T]][int]).replace('typing.', ''),
+                         'Callable[..., Union[int, NoneType]]')
+        self.assertEqual(repr(Callable[[], List[T]][int]).replace('typing.', ''),
+                         'Callable[[], List[int]]')
+
+    def test_generic_forward_ref(self):
+        def foobar(x: List[List['CC']]): ...
+        class CC: ...
+        self.assertEqual(get_type_hints(foobar, globals(), locals()), {'x': List[List[CC]]})
+        T = TypeVar('T')
+        AT = Tuple[T, ...]
+        def barfoo(x: AT): ...
+        self.assertIs(get_type_hints(barfoo, globals(), locals())['x'], AT)
+        CT = Callable[..., List[T]]
+        def barfoo2(x: CT): ...
+        self.assertIs(get_type_hints(barfoo2, globals(), locals())['x'], CT)
+
+    def test_extended_generic_rules_subclassing(self):
+        class T1(Tuple[T, KT]): ...
+        class T2(Tuple[T, ...]): ...
+        class C1(Callable[[T], T]): ...
+        class C2(Callable[..., int]):
+            def __call__(self):
+                return None
+
+        self.assertEqual(T1.__parameters__, (T, KT))
+        self.assertEqual(T1[int, str].__args__, (int, str))
+        self.assertEqual(T1[int, T].__origin__, T1)
+
+        self.assertEqual(T2.__parameters__, (T,))
+        with self.assertRaises(TypeError):
+            T1[int]
+        with self.assertRaises(TypeError):
+            T2[int, str]
+
+        self.assertEqual(repr(C1[int]).split('.')[-1], 'C1[int]')
+        self.assertEqual(C2.__parameters__, ())
+        self.assertIsInstance(C2(), collections_abc.Callable)
+        self.assertIsSubclass(C2, collections_abc.Callable)
+        self.assertIsSubclass(C1, collections_abc.Callable)
+        self.assertIsInstance(T1(), tuple)
+        self.assertIsSubclass(T2, tuple)
+        self.assertIsSubclass(Tuple[int, ...], typing.Sequence)
+        self.assertIsSubclass(Tuple[int, ...], typing.Iterable)
+
+    def test_fail_with_bare_union(self):
+        with self.assertRaises(TypeError):
+            List[Union]
+        with self.assertRaises(TypeError):
+            Tuple[Optional]
+        with self.assertRaises(TypeError):
+            ClassVar[ClassVar]
+        with self.assertRaises(TypeError):
+            List[ClassVar[int]]
+
+    def test_fail_with_bare_generic(self):
+        T = TypeVar('T')
+        with self.assertRaises(TypeError):
+            List[Generic]
+        with self.assertRaises(TypeError):
+            Tuple[Generic[T]]
+        with self.assertRaises(TypeError):
+            List[typing._Protocol]
+
+    def test_type_erasure_special(self):
+        T = TypeVar('T')
+        # this is the only test that checks type caching
+        self.clear_caches()
+        class MyTup(Tuple[T, T]): ...
+        self.assertIs(MyTup[int]().__class__, MyTup)
+        self.assertIs(MyTup[int]().__orig_class__, MyTup[int])
+        class MyCall(Callable[..., T]):
+            def __call__(self): return None
+        self.assertIs(MyCall[T]().__class__, MyCall)
+        self.assertIs(MyCall[T]().__orig_class__, MyCall[T])
+        class MyDict(typing.Dict[T, T]): ...
+        self.assertIs(MyDict[int]().__class__, MyDict)
+        self.assertIs(MyDict[int]().__orig_class__, MyDict[int])
+        class MyDef(typing.DefaultDict[str, T]): ...
+        self.assertIs(MyDef[int]().__class__, MyDef)
+        self.assertIs(MyDef[int]().__orig_class__, MyDef[int])
+
+    def test_all_repr_eq_any(self):
+        objs = (getattr(typing, el) for el in typing.__all__)
+        for obj in objs:
+            self.assertNotEqual(repr(obj), '')
+            self.assertEqual(obj, obj)
+            if getattr(obj, '__parameters__', None) and len(obj.__parameters__) == 1:
+                self.assertEqual(obj[Any].__args__, (Any,))
+            if isinstance(obj, type):
+                for base in obj.__mro__:
+                    self.assertNotEqual(repr(base), '')
+                    self.assertEqual(base, base)
+
+    def test_substitution_helper(self):
+        T = TypeVar('T')
+        KT = TypeVar('KT')
+        VT = TypeVar('VT')
+        class Map(Generic[KT, VT]):
+            def meth(self, k: KT, v: VT): ...
+        StrMap = Map[str, T]
+        obj = StrMap[int]()
+
+        new_args = typing._subs_tree(obj.__orig_class__)
+        new_annots = {k: typing._replace_arg(v, type(obj).__parameters__, new_args)
+                      for k, v in obj.meth.__annotations__.items()}
+
+        self.assertEqual(new_annots, {'k': str, 'v': int})
+
     def test_pickle(self):
         global C  # pickle wants to reference the class by name
         T = TypeVar('T')
@@ -686,6 +877,62 @@ class GenericTests(BaseTestCase):
             self.assertEqual(x.foo, 42)
             self.assertEqual(x.bar, 'abc')
             self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
+        simples = [Any, Union, Tuple, Callable, ClassVar, List, typing.Iterable]
+        for s in simples:
+            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+                z = pickle.dumps(s, proto)
+                x = pickle.loads(z)
+                self.assertEqual(s, x)
+
+    def test_copy_and_deepcopy(self):
+        T = TypeVar('T')
+        class Node(Generic[T]): ...
+        things = [Union[T, int], Tuple[T, int], Callable[..., T], Callable[[int], int],
+                  Tuple[Any, Any], Node[T], Node[int], Node[Any], typing.Iterable[T],
+                  typing.Iterable[Any], typing.Iterable[int], typing.Dict[int, str],
+                  typing.Dict[T, Any], ClassVar[int], ClassVar[List[T]], Tuple['T', 'T'],
+                  Union['T', int], List['T'], typing.Mapping['T', int]]
+        for t in things + [Any]:
+            self.assertEqual(t, copy(t))
+            self.assertEqual(t, deepcopy(t))
+
+    def test_parameterized_slots(self):
+        T = TypeVar('T')
+        class C(Generic[T]):
+            __slots__ = ('potato',)
+
+        c = C()
+        c_int = C[int]()
+        self.assertEqual(C.__slots__, C[str].__slots__)
+
+        c.potato = 0
+        c_int.potato = 0
+        with self.assertRaises(AttributeError):
+            c.tomato = 0
+        with self.assertRaises(AttributeError):
+            c_int.tomato = 0
+
+        def foo(x: C['C']): ...
+        self.assertEqual(get_type_hints(foo, globals(), locals())['x'], C[C])
+        self.assertEqual(get_type_hints(foo, globals(), locals())['x'].__slots__,
+                         C.__slots__)
+        self.assertEqual(copy(C[int]), deepcopy(C[int]))
+
+    def test_parameterized_slots_dict(self):
+        T = TypeVar('T')
+        class D(Generic[T]):
+            __slots__ = {'banana': 42}
+
+        d = D()
+        d_int = D[int]()
+        self.assertEqual(D.__slots__, D[str].__slots__)
+
+        d.banana = 'yes'
+        d_int.banana = 'yes'
+        with self.assertRaises(AttributeError):
+            d.foobar = 'no'
+        with self.assertRaises(AttributeError):
+            d_int.foobar = 'no'
 
     def test_errors(self):
         with self.assertRaises(TypeError):
@@ -704,12 +951,12 @@ class GenericTests(BaseTestCase):
         if not PY32:
             self.assertEqual(C.__qualname__,
                              'GenericTests.test_repr_2.<locals>.C')
-        self.assertEqual(repr(C).split('.')[-1], 'C<~T>')
+        self.assertEqual(repr(C).split('.')[-1], 'C')
         X = C[int]
         self.assertEqual(X.__module__, __name__)
         if not PY32:
-            self.assertEqual(X.__qualname__, 'C')
-        self.assertEqual(repr(X).split('.')[-1], 'C<~T>[int]')
+            self.assertTrue(X.__qualname__.endswith('.<locals>.C'))
+        self.assertEqual(repr(X).split('.')[-1], 'C[int]')
 
         class Y(C[int]):
             pass
@@ -823,51 +1070,44 @@ class GenericTests(BaseTestCase):
         with self.assertRaises(Exception):
             D[T]
 
+class ClassVarTests(BaseTestCase):
+
+    def test_basics(self):
+        with self.assertRaises(TypeError):
+            ClassVar[1]
+        with self.assertRaises(TypeError):
+            ClassVar[int, str]
+        with self.assertRaises(TypeError):
+            ClassVar[int][str]
+
+    def test_repr(self):
+        self.assertEqual(repr(ClassVar), 'typing.ClassVar')
+        cv = ClassVar[int]
+        self.assertEqual(repr(cv), 'typing.ClassVar[int]')
+        cv = ClassVar[Employee]
+        self.assertEqual(repr(cv), 'typing.ClassVar[%s.Employee]' % __name__)
+
+    def test_cannot_subclass(self):
+        with self.assertRaises(TypeError):
+            class C(type(ClassVar)):
+                pass
+        with self.assertRaises(TypeError):
+            class C(type(ClassVar[int])):
+                pass
 
-class VarianceTests(BaseTestCase):
-
-    def test_invariance(self):
-        # Because of invariance, List[subclass of X] is not a subclass
-        # of List[X], and ditto for MutableSequence.
-        self.assertNotIsSubclass(typing.List[Manager], typing.List[Employee])
-        self.assertNotIsSubclass(typing.MutableSequence[Manager],
-                              typing.MutableSequence[Employee])
-        # It's still reflexive.
-        self.assertIsSubclass(typing.List[Employee], typing.List[Employee])
-        self.assertIsSubclass(typing.MutableSequence[Employee],
-                          typing.MutableSequence[Employee])
-
-    def test_covariance_tuple(self):
-        # Check covariace for Tuple (which are really special cases).
-        self.assertIsSubclass(Tuple[Manager], Tuple[Employee])
-        self.assertNotIsSubclass(Tuple[Employee], Tuple[Manager])
-        # And pairwise.
-        self.assertIsSubclass(Tuple[Manager, Manager],
-                              Tuple[Employee, Employee])
-        self.assertNotIsSubclass(Tuple[Employee, Employee],
-                              Tuple[Manager, Employee])
-        # And using ellipsis.
-        self.assertIsSubclass(Tuple[Manager, ...], Tuple[Employee, ...])
-        self.assertNotIsSubclass(Tuple[Employee, ...], Tuple[Manager, ...])
-
-    def test_covariance_sequence(self):
-        # Check covariance for Sequence (which is just a generic class
-        # for this purpose, but using a covariant type variable).
-        self.assertIsSubclass(typing.Sequence[Manager],
-                              typing.Sequence[Employee])
-        self.assertNotIsSubclass(typing.Sequence[Employee],
-                              typing.Sequence[Manager])
-
-    def test_covariance_mapping(self):
-        # Ditto for Mapping (covariant in the value, invariant in the key).
-        self.assertIsSubclass(typing.Mapping[Employee, Manager],
-                          typing.Mapping[Employee, Employee])
-        self.assertNotIsSubclass(typing.Mapping[Manager, Employee],
-                              typing.Mapping[Employee, Employee])
-        self.assertNotIsSubclass(typing.Mapping[Employee, Manager],
-                              typing.Mapping[Manager, Manager])
-        self.assertNotIsSubclass(typing.Mapping[Manager, Employee],
-                              typing.Mapping[Manager, Manager])
+    def test_cannot_init(self):
+        with self.assertRaises(TypeError):
+            ClassVar()
+        with self.assertRaises(TypeError):
+            type(ClassVar)()
+        with self.assertRaises(TypeError):
+            type(ClassVar[Optional[int]])()
+
+    def test_no_isinstance(self):
+        with self.assertRaises(TypeError):
+            isinstance(1, ClassVar[int])
+        with self.assertRaises(TypeError):
+            issubclass(int, ClassVar)
 
 
 class CastTests(BaseTestCase):
@@ -1079,12 +1319,12 @@ class OverloadTests(BaseTestCase):
         blah()
 
 
-PY35 = sys.version_info[:2] >= (3, 5)
+ASYNCIO = sys.version_info[:2] >= (3, 5)
 
-PY35_TESTS = """
+ASYNCIO_TESTS = """
 import asyncio
 
-T_a = TypeVar('T')
+T_a = TypeVar('T_a')
 
 class AwaitableWrapper(typing.Awaitable[T_a]):
 
@@ -1112,8 +1352,110 @@ class AsyncIteratorWrapper(typing.AsyncIterator[T_a]):
             raise StopAsyncIteration
 """
 
-if PY35:
-    exec(PY35_TESTS)
+if ASYNCIO:
+    try:
+        exec(ASYNCIO_TESTS)
+    except ImportError:
+        ASYNCIO = False
+
+PY36 = sys.version_info[:2] >= (3, 6)
+
+PY36_TESTS = """
+from test import ann_module, ann_module2, ann_module3
+
+class A:
+    y: float
+class B(A):
+    x: ClassVar[Optional['B']] = None
+    y: int
+class CSub(B):
+    z: ClassVar['CSub'] = B()
+class G(Generic[T]):
+    lst: ClassVar[List[T]] = []
+
+class CoolEmployee(NamedTuple):
+    name: str
+    cool: int
+"""
+
+if PY36:
+    exec(PY36_TESTS)
+
+gth = get_type_hints
+
+class GetTypeHintTests(BaseTestCase):
+    def test_get_type_hints_from_various_objects(self):
+        # For invalid objects should fail with TypeError (not AttributeError etc).
+        with self.assertRaises(TypeError):
+            gth(123)
+        with self.assertRaises(TypeError):
+            gth('abc')
+        with self.assertRaises(TypeError):
+            gth(None)
+
+    @skipUnless(PY36, 'Python 3.6 required')
+    def test_get_type_hints_modules(self):
+        self.assertEqual(gth(ann_module), {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str})
+        self.assertEqual(gth(ann_module2), {})
+        self.assertEqual(gth(ann_module3), {})
+
+    @skipUnless(PY36, 'Python 3.6 required')
+    def test_get_type_hints_classes(self):
+        self.assertEqual(gth(ann_module.C, ann_module.__dict__),
+                         {'y': Optional[ann_module.C]})
+        self.assertIsInstance(gth(ann_module.j_class), dict)
+        self.assertEqual(gth(ann_module.M), {'123': 123, 'o': type})
+        self.assertEqual(gth(ann_module.D),
+                         {'j': str, 'k': str, 'y': Optional[ann_module.C]})
+        self.assertEqual(gth(ann_module.Y), {'z': int})
+        self.assertEqual(gth(ann_module.h_class),
+                         {'y': Optional[ann_module.C]})
+        self.assertEqual(gth(ann_module.S), {'x': str, 'y': str})
+        self.assertEqual(gth(ann_module.foo), {'x': int})
+
+    @skipUnless(PY36, 'Python 3.6 required')
+    def test_respect_no_type_check(self):
+        @no_type_check
+        class NoTpCheck:
+            class Inn:
+                def __init__(self, x: 'not a type'): ...
+        self.assertTrue(NoTpCheck.__no_type_check__)
+        self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__)
+        self.assertEqual(gth(ann_module2.NTC.meth), {})
+        class ABase(Generic[T]):
+            def meth(x: int): ...
+        @no_type_check
+        class Der(ABase): ...
+        self.assertEqual(gth(ABase.meth), {'x': int})
+
+    def test_get_type_hints_for_builins(self):
+        # Should not fail for built-in classes and functions.
+        self.assertEqual(gth(int), {})
+        self.assertEqual(gth(type), {})
+        self.assertEqual(gth(dir), {})
+        self.assertEqual(gth(len), {})
+
+    def test_previous_behavior(self):
+        def testf(x, y): ...
+        testf.__annotations__['x'] = 'int'
+        self.assertEqual(gth(testf), {'x': int})
+
+    def test_get_type_hints_for_object_with_annotations(self):
+        class A: ...
+        class B: ...
+        b = B()
+        b.__annotations__ = {'x': 'A'}
+        self.assertEqual(gth(b, locals()), {'x': A})
+
+    @skipUnless(PY36, 'Python 3.6 required')
+    def test_get_type_hints_ClassVar(self):
+        self.assertEqual(gth(ann_module2.CV, ann_module2.__dict__),
+                         {'var': typing.ClassVar[ann_module2.CV]})
+        self.assertEqual(gth(B, globals()),
+                         {'y': int, 'x': ClassVar[Optional[B]]})
+        self.assertEqual(gth(CSub, globals()),
+                         {'z': ClassVar[CSub], 'y': int, 'x': ClassVar[Optional[B]]})
+        self.assertEqual(gth(G), {'lst': ClassVar[List[T]]})
 
 
 class CollectionsAbcTests(BaseTestCase):
@@ -1128,7 +1470,6 @@ class CollectionsAbcTests(BaseTestCase):
         # path and could fail.  So call this a few times.
         self.assertIsInstance([], typing.Iterable)
         self.assertIsInstance([], typing.Iterable)
-        self.assertIsInstance([], typing.Iterable[int])
         self.assertNotIsInstance(42, typing.Iterable)
         # Just in case, also test issubclass() a few times.
         self.assertIsSubclass(list, typing.Iterable)
@@ -1137,10 +1478,9 @@ class CollectionsAbcTests(BaseTestCase):
     def test_iterator(self):
         it = iter([])
         self.assertIsInstance(it, typing.Iterator)
-        self.assertIsInstance(it, typing.Iterator[int])
         self.assertNotIsInstance(42, typing.Iterator)
 
-    @skipUnless(PY35, 'Python 3.5 required')
+    @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required')
     def test_awaitable(self):
         ns = {}
         exec(
@@ -1149,32 +1489,41 @@ class CollectionsAbcTests(BaseTestCase):
             globals(), ns)
         foo = ns['foo']
         g = foo()
-        self.assertIsSubclass(type(g), typing.Awaitable[int])
         self.assertIsInstance(g, typing.Awaitable)
         self.assertNotIsInstance(foo, typing.Awaitable)
-        self.assertIsSubclass(typing.Awaitable[Manager],
-                          typing.Awaitable[Employee])
-        self.assertNotIsSubclass(typing.Awaitable[Employee],
-                              typing.Awaitable[Manager])
         g.send(None)  # Run foo() till completion, to avoid warning.
 
-    @skipUnless(PY35, 'Python 3.5 required')
+    @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required')
+    def test_coroutine(self):
+        ns = {}
+        exec(
+            "async def foo():\n"
+            "    return\n",
+            globals(), ns)
+        foo = ns['foo']
+        g = foo()
+        self.assertIsInstance(g, typing.Coroutine)
+        with self.assertRaises(TypeError):
+            isinstance(g, typing.Coroutine[int])
+        self.assertNotIsInstance(foo, typing.Coroutine)
+        try:
+            g.send(None)
+        except StopIteration:
+            pass
+
+    @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required')
     def test_async_iterable(self):
         base_it = range(10)  # type: Iterator[int]
         it = AsyncIteratorWrapper(base_it)
         self.assertIsInstance(it, typing.AsyncIterable)
         self.assertIsInstance(it, typing.AsyncIterable)
-        self.assertIsSubclass(typing.AsyncIterable[Manager],
-                          typing.AsyncIterable[Employee])
         self.assertNotIsInstance(42, typing.AsyncIterable)
 
-    @skipUnless(PY35, 'Python 3.5 required')
+    @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required')
     def test_async_iterator(self):
         base_it = range(10)  # type: Iterator[int]
         it = AsyncIteratorWrapper(base_it)
         self.assertIsInstance(it, typing.AsyncIterator)
-        self.assertIsSubclass(typing.AsyncIterator[Manager],
-                          typing.AsyncIterator[Employee])
         self.assertNotIsInstance(42, typing.AsyncIterator)
 
     def test_sized(self):
@@ -1185,6 +1534,13 @@ class CollectionsAbcTests(BaseTestCase):
         self.assertIsInstance([], typing.Container)
         self.assertNotIsInstance(42, typing.Container)
 
+    def test_collection(self):
+        if hasattr(typing, 'Collection'):
+            self.assertIsInstance(tuple(), typing.Collection)
+            self.assertIsInstance(frozenset(), typing.Collection)
+            self.assertIsSubclass(dict, typing.Collection)
+            self.assertNotIsInstance(42, typing.Collection)
+
     def test_abstractset(self):
         self.assertIsInstance(set(), typing.AbstractSet)
         self.assertNotIsInstance(42, typing.AbstractSet)
@@ -1331,10 +1687,6 @@ class CollectionsAbcTests(BaseTestCase):
             yield 42
         g = foo()
         self.assertIsSubclass(type(g), typing.Generator)
-        self.assertIsSubclass(typing.Generator[Manager, Employee, Manager],
-                          typing.Generator[Employee, Manager, Employee])
-        self.assertNotIsSubclass(typing.Generator[Manager, Manager, Manager],
-                              typing.Generator[Employee, Employee, Employee])
 
     def test_no_generator_instantiation(self):
         with self.assertRaises(TypeError):
@@ -1353,12 +1705,30 @@ class CollectionsAbcTests(BaseTestCase):
             MMA()
 
         class MMC(MMA):
+            def __getitem__(self, k):
+                return None
+            def __setitem__(self, k, v):
+                pass
+            def __delitem__(self, k):
+                pass
+            def __iter__(self):
+                return iter(())
             def __len__(self):
                 return 0
 
         self.assertEqual(len(MMC()), 0)
+        assert callable(MMC.update)
+        self.assertIsInstance(MMC(), typing.Mapping)
 
         class MMB(typing.MutableMapping[KT, VT]):
+            def __getitem__(self, k):
+                return None
+            def __setitem__(self, k, v):
+                pass
+            def __delitem__(self, k):
+                pass
+            def __iter__(self):
+                return iter(())
             def __len__(self):
                 return 0
 
@@ -1373,6 +1743,82 @@ class CollectionsAbcTests(BaseTestCase):
         self.assertIsSubclass(MMB, typing.Mapping)
         self.assertIsSubclass(MMC, typing.Mapping)
 
+        self.assertIsInstance(MMB[KT, VT](), typing.Mapping)
+        self.assertIsInstance(MMB[KT, VT](), collections.Mapping)
+
+        self.assertIsSubclass(MMA, collections.Mapping)
+        self.assertIsSubclass(MMB, collections.Mapping)
+        self.assertIsSubclass(MMC, collections.Mapping)
+
+        self.assertIsSubclass(MMB[str, str], typing.Mapping)
+        self.assertIsSubclass(MMC, MMA)
+
+        class I(typing.Iterable): ...
+        self.assertNotIsSubclass(list, I)
+
+        class G(typing.Generator[int, int, int]): ...
+        def g(): yield 0
+        self.assertIsSubclass(G, typing.Generator)
+        self.assertIsSubclass(G, typing.Iterable)
+        if hasattr(collections, 'Generator'):
+            self.assertIsSubclass(G, collections.Generator)
+        self.assertIsSubclass(G, collections.Iterable)
+        self.assertNotIsSubclass(type(g), G)
+
+    def test_subclassing_subclasshook(self):
+
+        class Base(typing.Iterable):
+            @classmethod
+            def __subclasshook__(cls, other):
+                if other.__name__ == 'Foo':
+                    return True
+                else:
+                    return False
+
+        class C(Base): ...
+        class Foo: ...
+        class Bar: ...
+        self.assertIsSubclass(Foo, Base)
+        self.assertIsSubclass(Foo, C)
+        self.assertNotIsSubclass(Bar, C)
+
+    def test_subclassing_register(self):
+
+        class A(typing.Container): ...
+        class B(A): ...
+
+        class C: ...
+        A.register(C)
+        self.assertIsSubclass(C, A)
+        self.assertNotIsSubclass(C, B)
+
+        class D: ...
+        B.register(D)
+        self.assertIsSubclass(D, A)
+        self.assertIsSubclass(D, B)
+
+        class M(): ...
+        collections.MutableMapping.register(M)
+        self.assertIsSubclass(M, typing.Mapping)
+
+    def test_collections_as_base(self):
+
+        class M(collections.Mapping): ...
+        self.assertIsSubclass(M, typing.Mapping)
+        self.assertIsSubclass(M, typing.Iterable)
+
+        class S(collections.MutableSequence): ...
+        self.assertIsSubclass(S, typing.MutableSequence)
+        self.assertIsSubclass(S, typing.Iterable)
+
+        class I(collections.Iterable): ...
+        self.assertIsSubclass(I, typing.Iterable)
+
+        class A(collections.Mapping, metaclass=abc.ABCMeta): ...
+        class B: ...
+        A.register(B)
+        self.assertIsSubclass(B, typing.Mapping)
+
 
 class OtherABCTests(BaseTestCase):
 
@@ -1385,7 +1831,6 @@ class OtherABCTests(BaseTestCase):
 
         cm = manager()
         self.assertIsInstance(cm, typing.ContextManager)
-        self.assertIsInstance(cm, typing.ContextManager[int])
         self.assertNotIsInstance(42, typing.ContextManager)
 
 
@@ -1415,6 +1860,18 @@ class TypeTests(BaseTestCase):
 
         joe = new_user(BasicUser)
 
+    def test_type_optional(self):
+        A = Optional[Type[BaseException]]
+
+        def foo(a: A) -> Optional[BaseException]:
+            if a is None:
+                return None
+            else:
+                return a()
+
+        assert isinstance(foo(KeyboardInterrupt), KeyboardInterrupt)
+        assert foo(None) is None
+
 
 class NewTypeTests(BaseTestCase):
 
@@ -1452,6 +1909,31 @@ class NamedTupleTests(BaseTestCase):
         self.assertEqual(Emp._fields, ('name', 'id'))
         self.assertEqual(Emp._field_types, dict(name=str, id=int))
 
+    @skipUnless(PY36, 'Python 3.6 required')
+    def test_annotation_usage(self):
+        tim = CoolEmployee('Tim', 9000)
+        self.assertIsInstance(tim, CoolEmployee)
+        self.assertIsInstance(tim, tuple)
+        self.assertEqual(tim.name, 'Tim')
+        self.assertEqual(tim.cool, 9000)
+        self.assertEqual(CoolEmployee.__name__, 'CoolEmployee')
+        self.assertEqual(CoolEmployee._fields, ('name', 'cool'))
+        self.assertEqual(CoolEmployee._field_types, dict(name=str, cool=int))
+
+    @skipUnless(PY36, 'Python 3.6 required')
+    def test_namedtuple_keyword_usage(self):
+        LocalEmployee = NamedTuple("LocalEmployee", name=str, age=int)
+        nick = LocalEmployee('Nick', 25)
+        self.assertIsInstance(nick, tuple)
+        self.assertEqual(nick.name, 'Nick')
+        self.assertEqual(LocalEmployee.__name__, 'LocalEmployee')
+        self.assertEqual(LocalEmployee._fields, ('name', 'age'))
+        self.assertEqual(LocalEmployee._field_types, dict(name=str, age=int))
+        with self.assertRaises(TypeError):
+            NamedTuple('Name', [('x', int)], y=str)
+        with self.assertRaises(TypeError):
+            NamedTuple('Name', x=1, y='a')
+
     def test_pickle(self):
         global Emp  # pickle wants to reference the class by name
         Emp = NamedTuple('Emp', [('name', str), ('id', int)])
@@ -1504,22 +1986,16 @@ class RETests(BaseTestCase):
         pat = re.compile('[a-z]+', re.I)
         self.assertIsSubclass(pat.__class__, Pattern)
         self.assertIsSubclass(type(pat), Pattern)
-        self.assertIsSubclass(type(pat), Pattern[str])
+        self.assertIsInstance(pat, Pattern)
 
         mat = pat.search('12345abcde.....')
         self.assertIsSubclass(mat.__class__, Match)
-        self.assertIsSubclass(mat.__class__, Match[str])
-        self.assertIsSubclass(mat.__class__, Match[bytes])  # Sad but true.
         self.assertIsSubclass(type(mat), Match)
-        self.assertIsSubclass(type(mat), Match[str])
+        self.assertIsInstance(mat, Match)
 
+        # these should just work
         p = Pattern[Union[str, bytes]]
-        self.assertIsSubclass(Pattern[str], Pattern)
-        self.assertIsSubclass(Pattern[str], p)
-
         m = Match[Union[bytes, str]]
-        self.assertIsSubclass(Match[bytes], Match)
-        self.assertIsSubclass(Match[bytes], m)
 
     def test_errors(self):
         with self.assertRaises(TypeError):
@@ -1534,9 +2010,6 @@ class RETests(BaseTestCase):
             m[str]
         with self.assertRaises(TypeError):
             # We don't support isinstance().
-            isinstance(42, Pattern)
-        with self.assertRaises(TypeError):
-            # We don't support isinstance().
             isinstance(42, Pattern[str])
 
     def test_repr(self):
@@ -1561,7 +2034,7 @@ class RETests(BaseTestCase):
                 pass
 
         self.assertEqual(str(ex.exception),
-                         "A type alias cannot be subclassed")
+                         "Cannot subclass typing._TypeAlias")
 
 
 class AllTests(BaseTestCase):
index a38e7b1..f696a5b 100644 (file)
@@ -4,7 +4,7 @@ Written by Marc-Andre Lemburg (mal@lemburg.com).
 
 (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
 
-"""#"
+"""
 import _string
 import codecs
 import itertools
@@ -2275,6 +2275,123 @@ class UnicodeTest(string_tests.CommonTest,
         self.assertEqual("%s" % s, '__str__ overridden')
         self.assertEqual("{}".format(s), '__str__ overridden')
 
+    def test_subclass_add(self):
+        class S(str):
+            def __add__(self, o):
+                return "3"
+        self.assertEqual(S("4") + S("5"), "3")
+        class S(str):
+            def __iadd__(self, o):
+                return "3"
+        s = S("1")
+        s += "4"
+        self.assertEqual(s, "3")
+
+    def test_getnewargs(self):
+        text = 'abc'
+        args = text.__getnewargs__()
+        self.assertIsNot(args[0], text)
+        self.assertEqual(args[0], text)
+        self.assertEqual(len(args), 1)
+
+    def test_resize(self):
+        for length in range(1, 100, 7):
+            # generate a fresh string (refcount=1)
+            text = 'a' * length + 'b'
+
+            with support.check_warnings(('unicode_internal codec has been '
+                                         'deprecated', DeprecationWarning)):
+                # fill wstr internal field
+                abc = text.encode('unicode_internal')
+                self.assertEqual(abc.decode('unicode_internal'), text)
+
+                # resize text: wstr field must be cleared and then recomputed
+                text += 'c'
+                abcdef = text.encode('unicode_internal')
+                self.assertNotEqual(abc, abcdef)
+                self.assertEqual(abcdef.decode('unicode_internal'), text)
+
+    def test_compare(self):
+        # Issue #17615
+        N = 10
+        ascii = 'a' * N
+        ascii2 = 'z' * N
+        latin = '\x80' * N
+        latin2 = '\xff' * N
+        bmp = '\u0100' * N
+        bmp2 = '\uffff' * N
+        astral = '\U00100000' * N
+        astral2 = '\U0010ffff' * N
+        strings = (
+            ascii, ascii2,
+            latin, latin2,
+            bmp, bmp2,
+            astral, astral2)
+        for text1, text2 in itertools.combinations(strings, 2):
+            equal = (text1 is text2)
+            self.assertEqual(text1 == text2, equal)
+            self.assertEqual(text1 != text2, not equal)
+
+            if equal:
+                self.assertTrue(text1 <= text2)
+                self.assertTrue(text1 >= text2)
+
+                # text1 is text2: duplicate strings to skip the "str1 == str2"
+                # optimization in unicode_compare_eq() and really compare
+                # character per character
+                copy1 = duplicate_string(text1)
+                copy2 = duplicate_string(text2)
+                self.assertIsNot(copy1, copy2)
+
+                self.assertTrue(copy1 == copy2)
+                self.assertFalse(copy1 != copy2)
+
+                self.assertTrue(copy1 <= copy2)
+                self.assertTrue(copy2 >= copy2)
+
+        self.assertTrue(ascii < ascii2)
+        self.assertTrue(ascii < latin)
+        self.assertTrue(ascii < bmp)
+        self.assertTrue(ascii < astral)
+        self.assertFalse(ascii >= ascii2)
+        self.assertFalse(ascii >= latin)
+        self.assertFalse(ascii >= bmp)
+        self.assertFalse(ascii >= astral)
+
+        self.assertFalse(latin < ascii)
+        self.assertTrue(latin < latin2)
+        self.assertTrue(latin < bmp)
+        self.assertTrue(latin < astral)
+        self.assertTrue(latin >= ascii)
+        self.assertFalse(latin >= latin2)
+        self.assertFalse(latin >= bmp)
+        self.assertFalse(latin >= astral)
+
+        self.assertFalse(bmp < ascii)
+        self.assertFalse(bmp < latin)
+        self.assertTrue(bmp < bmp2)
+        self.assertTrue(bmp < astral)
+        self.assertTrue(bmp >= ascii)
+        self.assertTrue(bmp >= latin)
+        self.assertFalse(bmp >= bmp2)
+        self.assertFalse(bmp >= astral)
+
+        self.assertFalse(astral < ascii)
+        self.assertFalse(astral < latin)
+        self.assertFalse(astral < bmp2)
+        self.assertTrue(astral < astral2)
+        self.assertTrue(astral >= ascii)
+        self.assertTrue(astral >= latin)
+        self.assertTrue(astral >= bmp2)
+        self.assertFalse(astral >= astral2)
+
+    def test_free_after_iterating(self):
+        support.check_free_after_iterating(self, iter, str)
+        support.check_free_after_iterating(self, reversed, str)
+
+
+class CAPITest(unittest.TestCase):
+
     # Test PyUnicode_FromFormat()
     def test_from_format(self):
         support.import_module('ctypes')
@@ -2498,7 +2615,7 @@ class UnicodeTest(string_tests.CommonTest,
                      b'repr=%V', None, b'abc\xff')
 
         # not supported: copy the raw format string. these tests are just here
-        # to check for crashs and should not be considered as specifications
+        # to check for crashes and should not be considered as specifications
         check_format('%s',
                      b'%1%s', b'abc')
         check_format('%1abc',
@@ -2570,17 +2687,65 @@ class UnicodeTest(string_tests.CommonTest,
         self.assertEqual(size, nchar)
         self.assertEqual(wchar, nonbmp + '\0')
 
-    def test_subclass_add(self):
-        class S(str):
-            def __add__(self, o):
-                return "3"
-        self.assertEqual(S("4") + S("5"), "3")
-        class S(str):
-            def __iadd__(self, o):
-                return "3"
-        s = S("1")
-        s += "4"
-        self.assertEqual(s, "3")
+    # Test PyUnicode_AsUCS4()
+    @support.cpython_only
+    def test_asucs4(self):
+        from _testcapi import unicode_asucs4
+        for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
+                  'a\ud800b\udfffc', '\ud834\udd1e']:
+            l = len(s)
+            self.assertEqual(unicode_asucs4(s, l, 1), s+'\0')
+            self.assertEqual(unicode_asucs4(s, l, 0), s+'\uffff')
+            self.assertEqual(unicode_asucs4(s, l+1, 1), s+'\0\uffff')
+            self.assertEqual(unicode_asucs4(s, l+1, 0), s+'\0\uffff')
+            self.assertRaises(SystemError, unicode_asucs4, s, l-1, 1)
+            self.assertRaises(SystemError, unicode_asucs4, s, l-2, 0)
+            s = '\0'.join([s, s])
+            self.assertEqual(unicode_asucs4(s, len(s), 1), s+'\0')
+            self.assertEqual(unicode_asucs4(s, len(s), 0), s+'\uffff')
+
+    # Test PyUnicode_CopyCharacters()
+    @support.cpython_only
+    def test_copycharacters(self):
+        from _testcapi import unicode_copycharacters
+
+        strings = [
+            'abcde', '\xa1\xa2\xa3\xa4\xa5',
+            '\u4f60\u597d\u4e16\u754c\uff01',
+            '\U0001f600\U0001f601\U0001f602\U0001f603\U0001f604'
+        ]
+
+        for idx, from_ in enumerate(strings):
+            # wide -> narrow: exceed maxchar limitation
+            for to in strings[:idx]:
+                self.assertRaises(
+                    SystemError,
+                    unicode_copycharacters, to, 0, from_, 0, 5
+                )
+            # same kind
+            for from_start in range(5):
+                self.assertEqual(
+                    unicode_copycharacters(from_, 0, from_, from_start, 5),
+                    (from_[from_start:from_start+5].ljust(5, '\0'),
+                     5-from_start)
+                )
+            for to_start in range(5):
+                self.assertEqual(
+                    unicode_copycharacters(from_, to_start, from_, to_start, 5),
+                    (from_[to_start:to_start+5].rjust(5, '\0'),
+                     5-to_start)
+                )
+            # narrow -> wide
+            # Tests omitted since this creates invalid strings.
+
+        s = strings[0]
+        self.assertRaises(IndexError, unicode_copycharacters, s, 6, s, 0, 5)
+        self.assertRaises(IndexError, unicode_copycharacters, s, -1, s, 0, 5)
+        self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, 6, 5)
+        self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, -1, 5)
+        self.assertRaises(SystemError, unicode_copycharacters, s, 1, s, 0, 5)
+        self.assertRaises(SystemError, unicode_copycharacters, s, 0, s, 0, -1)
+        self.assertRaises(SystemError, unicode_copycharacters, s, 0, b'', 0, 0)
 
     @support.cpython_only
     def test_encode_decimal(self):
@@ -2610,104 +2775,6 @@ class UnicodeTest(string_tests.CommonTest,
         self.assertEqual(transform_decimal('123\u20ac'),
                          '123\u20ac')
 
-    def test_getnewargs(self):
-        text = 'abc'
-        args = text.__getnewargs__()
-        self.assertIsNot(args[0], text)
-        self.assertEqual(args[0], text)
-        self.assertEqual(len(args), 1)
-
-    def test_resize(self):
-        for length in range(1, 100, 7):
-            # generate a fresh string (refcount=1)
-            text = 'a' * length + 'b'
-
-            with support.check_warnings(('unicode_internal codec has been '
-                                         'deprecated', DeprecationWarning)):
-                # fill wstr internal field
-                abc = text.encode('unicode_internal')
-                self.assertEqual(abc.decode('unicode_internal'), text)
-
-                # resize text: wstr field must be cleared and then recomputed
-                text += 'c'
-                abcdef = text.encode('unicode_internal')
-                self.assertNotEqual(abc, abcdef)
-                self.assertEqual(abcdef.decode('unicode_internal'), text)
-
-    def test_compare(self):
-        # Issue #17615
-        N = 10
-        ascii = 'a' * N
-        ascii2 = 'z' * N
-        latin = '\x80' * N
-        latin2 = '\xff' * N
-        bmp = '\u0100' * N
-        bmp2 = '\uffff' * N
-        astral = '\U00100000' * N
-        astral2 = '\U0010ffff' * N
-        strings = (
-            ascii, ascii2,
-            latin, latin2,
-            bmp, bmp2,
-            astral, astral2)
-        for text1, text2 in itertools.combinations(strings, 2):
-            equal = (text1 is text2)
-            self.assertEqual(text1 == text2, equal)
-            self.assertEqual(text1 != text2, not equal)
-
-            if equal:
-                self.assertTrue(text1 <= text2)
-                self.assertTrue(text1 >= text2)
-
-                # text1 is text2: duplicate strings to skip the "str1 == str2"
-                # optimization in unicode_compare_eq() and really compare
-                # character per character
-                copy1 = duplicate_string(text1)
-                copy2 = duplicate_string(text2)
-                self.assertIsNot(copy1, copy2)
-
-                self.assertTrue(copy1 == copy2)
-                self.assertFalse(copy1 != copy2)
-
-                self.assertTrue(copy1 <= copy2)
-                self.assertTrue(copy2 >= copy2)
-
-        self.assertTrue(ascii < ascii2)
-        self.assertTrue(ascii < latin)
-        self.assertTrue(ascii < bmp)
-        self.assertTrue(ascii < astral)
-        self.assertFalse(ascii >= ascii2)
-        self.assertFalse(ascii >= latin)
-        self.assertFalse(ascii >= bmp)
-        self.assertFalse(ascii >= astral)
-
-        self.assertFalse(latin < ascii)
-        self.assertTrue(latin < latin2)
-        self.assertTrue(latin < bmp)
-        self.assertTrue(latin < astral)
-        self.assertTrue(latin >= ascii)
-        self.assertFalse(latin >= latin2)
-        self.assertFalse(latin >= bmp)
-        self.assertFalse(latin >= astral)
-
-        self.assertFalse(bmp < ascii)
-        self.assertFalse(bmp < latin)
-        self.assertTrue(bmp < bmp2)
-        self.assertTrue(bmp < astral)
-        self.assertTrue(bmp >= ascii)
-        self.assertTrue(bmp >= latin)
-        self.assertFalse(bmp >= bmp2)
-        self.assertFalse(bmp >= astral)
-
-        self.assertFalse(astral < ascii)
-        self.assertFalse(astral < latin)
-        self.assertFalse(astral < bmp2)
-        self.assertTrue(astral < astral2)
-        self.assertTrue(astral >= ascii)
-        self.assertTrue(astral >= latin)
-        self.assertTrue(astral >= bmp2)
-        self.assertFalse(astral >= astral2)
-
     @support.cpython_only
     def test_pep393_utf8_caching_bug(self):
         # Issue #25709: Problem with string concatenation and utf-8 cache
@@ -2725,10 +2792,6 @@ class UnicodeTest(string_tests.CommonTest,
                 # Check that the second call returns the same result
                 self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
 
-    def test_free_after_iterating(self):
-        support.check_free_after_iterating(self, iter, str)
-        support.check_free_after_iterating(self, reversed, str)
-
 
 class StringModuleTest(unittest.TestCase):
     def test_formatter_parser(self):
index d27eef0..74346b4 100644 (file)
@@ -248,6 +248,11 @@ Overridden parameters
       ...
     TypeError: f() got multiple values for keyword argument 'x'
 
+    >>> f(x=5, **{'x': 3}, **{'x': 2})
+    Traceback (most recent call last):
+      ...
+    TypeError: f() got multiple values for keyword argument 'x'
+
     >>> f(**{1: 3}, **{1: 5})
     Traceback (most recent call last):
       ...
index 5d05f8d..247598a 100644 (file)
@@ -1,4 +1,4 @@
-"""Regresssion tests for what was in Python 2's "urllib" module"""
+"""Regression tests for what was in Python 2's "urllib" module"""
 
 import urllib.parse
 import urllib.request
@@ -232,6 +232,18 @@ class ProxyTests(unittest.TestCase):
         self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888'))
         self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234'))
 
+    def test_proxy_cgi_ignore(self):
+        try:
+            self.env.set('HTTP_PROXY', 'http://somewhere:3128')
+            proxies = urllib.request.getproxies_environment()
+            self.assertEqual('http://somewhere:3128', proxies['http'])
+            self.env.set('REQUEST_METHOD', 'GET')
+            proxies = urllib.request.getproxies_environment()
+            self.assertNotIn('http', proxies)
+        finally:
+            self.env.unset('REQUEST_METHOD')
+            self.env.unset('HTTP_PROXY')
+
     def test_proxy_bypass_environment_host_match(self):
         bypass = urllib.request.proxy_bypass_environment
         self.env.set('NO_PROXY',
index c8b37ee..68c523a 100644 (file)
@@ -289,12 +289,12 @@ class BasicAuthTests(unittest.TestCase):
         def http_server_with_basic_auth_handler(*args, **kwargs):
             return BasicAuthHandler(*args, **kwargs)
         self.server = LoopbackHttpServerThread(http_server_with_basic_auth_handler)
+        self.addCleanup(self.server.stop)
         self.server_url = 'http://127.0.0.1:%s' % self.server.port
         self.server.start()
         self.server.ready.wait()
 
     def tearDown(self):
-        self.server.stop()
         super(BasicAuthTests, self).tearDown()
 
     def test_basic_auth_success(self):
@@ -323,6 +323,14 @@ class ProxyAuthTests(unittest.TestCase):
 
     def setUp(self):
         super(ProxyAuthTests, self).setUp()
+        # Ignore proxy bypass settings in the environment.
+        def restore_environ(old_environ):
+            os.environ.clear()
+            os.environ.update(old_environ)
+        self.addCleanup(restore_environ, os.environ.copy())
+        os.environ['NO_PROXY'] = ''
+        os.environ['no_proxy'] = ''
+
         self.digest_auth_handler = DigestAuthHandler()
         self.digest_auth_handler.set_users({self.USER: self.PASSWD})
         self.digest_auth_handler.set_realm(self.REALM)
@@ -438,17 +446,14 @@ class TestUrlopen(unittest.TestCase):
 
     def setUp(self):
         super(TestUrlopen, self).setUp()
+
         # Ignore proxies for localhost tests.
-        self.old_environ = os.environ.copy()
+        def restore_environ(old_environ):
+            os.environ.clear()
+            os.environ.update(old_environ)
+        self.addCleanup(restore_environ, os.environ.copy())
         os.environ['NO_PROXY'] = '*'
-        self.server = None
-
-    def tearDown(self):
-        if self.server is not None:
-            self.server.stop()
-        os.environ.clear()
-        os.environ.update(self.old_environ)
-        super(TestUrlopen, self).tearDown()
+        os.environ['no_proxy'] = '*'
 
     def urlopen(self, url, data=None, **kwargs):
         l = []
@@ -469,6 +474,7 @@ class TestUrlopen(unittest.TestCase):
         handler = GetRequestHandler(responses)
 
         self.server = LoopbackHttpServerThread(handler)
+        self.addCleanup(self.server.stop)
         self.server.start()
         self.server.ready.wait()
         port = self.server.port
@@ -592,7 +598,8 @@ class TestUrlopen(unittest.TestCase):
         handler = self.start_server()
         req = urllib.request.Request("http://localhost:%s/" % handler.port,
                                      headers={"Range": "bytes=20-39"})
-        urllib.request.urlopen(req)
+        with urllib.request.urlopen(req):
+            pass
         self.assertEqual(handler.headers_received["Range"], "bytes=20-39")
 
     def test_basic(self):
@@ -608,22 +615,21 @@ class TestUrlopen(unittest.TestCase):
 
     def test_info(self):
         handler = self.start_server()
-        try:
-            open_url = urllib.request.urlopen(
-                "http://localhost:%s" % handler.port)
+        open_url = urllib.request.urlopen(
+            "http://localhost:%s" % handler.port)
+        with open_url:
             info_obj = open_url.info()
-            self.assertIsInstance(info_obj, email.message.Message,
-                                  "object returned by 'info' is not an "
-                                  "instance of email.message.Message")
-            self.assertEqual(info_obj.get_content_subtype(), "plain")
-        finally:
-            self.server.stop()
+        self.assertIsInstance(info_obj, email.message.Message,
+                              "object returned by 'info' is not an "
+                              "instance of email.message.Message")
+        self.assertEqual(info_obj.get_content_subtype(), "plain")
 
     def test_geturl(self):
         # Make sure same URL as opened is returned by geturl.
         handler = self.start_server()
         open_url = urllib.request.urlopen("http://localhost:%s" % handler.port)
-        url = open_url.geturl()
+        with open_url:
+            url = open_url.geturl()
         self.assertEqual(url, "http://localhost:%s" % handler.port)
 
     def test_iteration(self):
index 829997f..71abc14 100644 (file)
@@ -425,6 +425,8 @@ class UrlParseTestCase(unittest.TestCase):
         self.checkJoin('', 'http://a/./g', 'http://a/./g')
         self.checkJoin('svn://pathtorepo/dir1', 'dir2', 'svn://pathtorepo/dir2')
         self.checkJoin('svn+ssh://pathtorepo/dir1', 'dir2', 'svn+ssh://pathtorepo/dir2')
+        self.checkJoin('ws://a/b','g','ws://a/g')
+        self.checkJoin('wss://a/b','g','wss://a/g')
 
         # XXX: The following tests are no longer compatible with RFC3986
         # self.checkJoin(SIMPLE_BASE, '../../../g','http://a/../g')
index e34d8e6..47248f9 100644 (file)
@@ -292,6 +292,10 @@ class TestUUID(unittest.TestCase):
         badtype(lambda: setattr(u, 'clock_seq_low', 0))
         badtype(lambda: setattr(u, 'node', 0))
 
+        # Comparison with a non-UUID object
+        badtype(lambda: u < object())
+        badtype(lambda: u > object())
+
     def test_getnode(self):
         node1 = uuid.getnode()
         self.assertTrue(0 < node1 < (1 << 48), '%012x' % node1)
index d2c986e..3999d1f 100644 (file)
@@ -31,6 +31,11 @@ try:
 except ImportError:
     threading = None
 
+try:
+    import ctypes
+except ImportError:
+    ctypes = None
+
 skipInVenv = unittest.skipIf(sys.prefix != sys.base_prefix,
                              'Test not appropriate in a venv')
 
@@ -327,6 +332,8 @@ class EnsurePipTest(BaseTest):
     @unittest.skipIf(ssl is None, ensurepip._MISSING_SSL_MESSAGE)
     @unittest.skipUnless(threading, 'some dependencies of pip import threading'
                                     ' module unconditionally')
+    # Issue #26610: pip/pep425tags.py requires ctypes
+    @unittest.skipUnless(ctypes, 'pip requires ctypes')
     def test_with_pip(self):
         rmtree(self.env_dir)
         with EnvironmentVarGuard() as envvars:
index 72fcc73..84a6fb5 100644 (file)
@@ -261,6 +261,18 @@ class FilterTests(BaseTest):
             self.assertEqual(str(w[-1].message), text)
             self.assertTrue(w[-1].category is UserWarning)
 
+    def test_message_matching(self):
+        with original_warnings.catch_warnings(record=True,
+                module=self.module) as w:
+            self.module.simplefilter("ignore", UserWarning)
+            self.module.filterwarnings("error", "match", UserWarning)
+            self.assertRaises(UserWarning, self.module.warn, "match")
+            self.assertRaises(UserWarning, self.module.warn, "match prefix")
+            self.module.warn("suffix match")
+            self.assertEqual(w, [])
+            self.module.warn("something completely different")
+            self.assertEqual(w, [])
+
     def test_mutate_filter_list(self):
         class X:
             def match(self, a):
@@ -990,6 +1002,7 @@ class BootstrapTest(unittest.TestCase):
 
 
 class FinalizationTest(unittest.TestCase):
+    @support.requires_type_collecting
     def test_finalization(self):
         # Issue #19421: warnings.warn() should not crash
         # during Python finalization
index f49cb7e..1aa3540 100644 (file)
@@ -6,6 +6,7 @@ import weakref
 import operator
 import contextlib
 import copy
+import time
 
 from test import support
 from test.support import script_helper
@@ -72,6 +73,29 @@ class TestBase(unittest.TestCase):
         self.cbcalled += 1
 
 
+@contextlib.contextmanager
+def collect_in_thread(period=0.0001):
+    """
+    Ensure GC collections happen in a different thread, at a high frequency.
+    """
+    threading = support.import_module('threading')
+    please_stop = False
+
+    def collect():
+        while not please_stop:
+            time.sleep(period)
+            gc.collect()
+
+    with support.disable_gc():
+        t = threading.Thread(target=collect)
+        t.start()
+        try:
+            yield
+        finally:
+            please_stop = True
+            t.join()
+
+
 class ReferencesTestCase(TestBase):
 
     def test_basic_ref(self):
@@ -589,6 +613,7 @@ class ReferencesTestCase(TestBase):
         del c1, c2, C, D
         gc.collect()
 
+    @support.requires_type_collecting
     def test_callback_in_cycle_resurrection(self):
         import gc
 
@@ -844,6 +869,14 @@ class ReferencesTestCase(TestBase):
         with self.assertRaises(AttributeError):
             ref1.__callback__ = lambda ref: None
 
+    def test_callback_gcs(self):
+        class ObjectWithDel(Object):
+            def __del__(self): pass
+        x = ObjectWithDel(1)
+        ref1 = weakref.ref(x, lambda ref: support.gc_collect())
+        del x
+        support.gc_collect()
+
 
 class SubclassableWeakrefTestCase(TestBase):
 
@@ -1624,6 +1657,35 @@ class MappingTestCase(TestBase):
         dict = weakref.WeakKeyDictionary()
         self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
 
+    def test_threaded_weak_valued_setdefault(self):
+        d = weakref.WeakValueDictionary()
+        with collect_in_thread():
+            for i in range(100000):
+                x = d.setdefault(10, RefCycle())
+                self.assertIsNot(x, None)  # we never put None in there!
+                del x
+
+    def test_threaded_weak_valued_pop(self):
+        d = weakref.WeakValueDictionary()
+        with collect_in_thread():
+            for i in range(100000):
+                d[10] = RefCycle()
+                x = d.pop(10, 10)
+                self.assertIsNot(x, None)  # we never put None in there!
+
+    def test_threaded_weak_valued_consistency(self):
+        # Issue #28427: old keys should not remove new values from
+        # WeakValueDictionary when collecting from another thread.
+        d = weakref.WeakValueDictionary()
+        with collect_in_thread():
+            for i in range(200000):
+                o = RefCycle()
+                d[10] = o
+                # o is still alive, so the dict can't be empty
+                self.assertEqual(len(d), 1)
+                o = None  # lose ref
+
+
 from test import mapping_tests
 
 class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
index c3292c4..e46b6fb 100644 (file)
@@ -95,6 +95,31 @@ class MozillaCommandTest(CommandTestMixin, unittest.TestCase):
 
     def test_open(self):
         self._test('open',
+                   options=[],
+                   arguments=[URL])
+
+    def test_open_with_autoraise_false(self):
+        self._test('open', kw=dict(autoraise=False),
+                   options=[],
+                   arguments=[URL])
+
+    def test_open_new(self):
+        self._test('open_new',
+                   options=[],
+                   arguments=['-new-window', URL])
+
+    def test_open_new_tab(self):
+        self._test('open_new_tab',
+                   options=[],
+                   arguments=['-new-tab', URL])
+
+
+class NetscapeCommandTest(CommandTestMixin, unittest.TestCase):
+
+    browser_class = webbrowser.Netscape
+
+    def test_open(self):
+        self._test('open',
                    options=['-raise', '-remote'],
                    arguments=['openURL({})'.format(URL)])
 
index 2c4ac08..60207fb 100644 (file)
@@ -168,7 +168,7 @@ class BaseWinregTests(unittest.TestCase):
         DeleteKey(key, subkeystr)
 
         try:
-            # Shouldnt be able to delete it twice!
+            # Shouldn't be able to delete it twice!
             DeleteKey(key, subkeystr)
             self.fail("Deleting the key twice succeeded")
         except OSError:
index 2a78388..4a8ab7d 100644 (file)
@@ -1,38 +1,42 @@
 # Ridiculously simple test of the winsound module for Windows.
 
-import unittest
-from test import support
-support.requires('audio')
-import time
+import functools
 import os
 import subprocess
+import time
+import unittest
+
+from test import support
 
+support.requires('audio')
 winsound = support.import_module('winsound')
-ctypes = support.import_module('ctypes')
-import winreg
-
-def has_sound(sound):
-    """Find out if a particular event is configured with a default sound"""
-    try:
-        # Ask the mixer API for the number of devices it knows about.
-        # When there are no devices, PlaySound will fail.
-        if ctypes.windll.winmm.mixerGetNumDevs() == 0:
-            return False
-
-        key = winreg.OpenKeyEx(winreg.HKEY_CURRENT_USER,
-                "AppEvents\Schemes\Apps\.Default\{0}\.Default".format(sound))
-        return winreg.EnumValue(key, 0)[1] != ""
-    except OSError:
-        return False
+
+
+# Unless we actually have an ear in the room, we have no idea whether a sound
+# actually plays, and it's incredibly flaky trying to figure out if a sound
+# even *should* play.  Instead of guessing, just call the function and assume
+# it either passed or raised the RuntimeError we expect in case of failure.
+def sound_func(func):
+    @functools.wraps(func)
+    def wrapper(*args, **kwargs):
+        try:
+            ret = func(*args, **kwargs)
+        except RuntimeError as e:
+            if support.verbose:
+                print(func.__name__, 'failed:', e)
+        else:
+            if support.verbose:
+                print(func.__name__, 'returned')
+            return ret
+    return wrapper
+
+
+safe_Beep = sound_func(winsound.Beep)
+safe_MessageBeep = sound_func(winsound.MessageBeep)
+safe_PlaySound = sound_func(winsound.PlaySound)
+
 
 class BeepTest(unittest.TestCase):
-    # As with PlaySoundTest, incorporate the _have_soundcard() check
-    # into our test methods.  If there's no audio device present,
-    # winsound.Beep returns 0 and GetLastError() returns 127, which
-    # is: ERROR_PROC_NOT_FOUND ("The specified procedure could not
-    # be found").  (FWIW, virtual/Hyper-V systems fall under this
-    # scenario as they have no sound devices whatsoever  (not even
-    # a legacy Beep device).)
 
     def test_errors(self):
         self.assertRaises(TypeError, winsound.Beep)
@@ -40,27 +44,12 @@ class BeepTest(unittest.TestCase):
         self.assertRaises(ValueError, winsound.Beep, 32768, 75)
 
     def test_extremes(self):
-        self._beep(37, 75)
-        self._beep(32767, 75)
+        safe_Beep(37, 75)
+        safe_Beep(32767, 75)
 
     def test_increasingfrequency(self):
         for i in range(100, 2000, 100):
-            self._beep(i, 75)
-
-    def _beep(self, *args):
-        # these tests used to use _have_soundcard(), but it's quite
-        # possible to have a soundcard, and yet have the beep driver
-        # disabled. So basically, we have no way of knowing whether
-        # a beep should be produced or not, so currently if these
-        # tests fail we're ignoring them
-        #
-        # XXX the right fix for this is to define something like
-        # _have_enabled_beep_driver() and use that instead of the
-        # try/except below
-        try:
-            winsound.Beep(*args)
-        except RuntimeError:
-            pass
+            safe_Beep(i, 75)
 
 class MessageBeepTest(unittest.TestCase):
 
@@ -70,22 +59,22 @@ class MessageBeepTest(unittest.TestCase):
     def test_default(self):
         self.assertRaises(TypeError, winsound.MessageBeep, "bad")
         self.assertRaises(TypeError, winsound.MessageBeep, 42, 42)
-        winsound.MessageBeep()
+        safe_MessageBeep()
 
     def test_ok(self):
-        winsound.MessageBeep(winsound.MB_OK)
+        safe_MessageBeep(winsound.MB_OK)
 
     def test_asterisk(self):
-        winsound.MessageBeep(winsound.MB_ICONASTERISK)
+        safe_MessageBeep(winsound.MB_ICONASTERISK)
 
     def test_exclamation(self):
-        winsound.MessageBeep(winsound.MB_ICONEXCLAMATION)
+        safe_MessageBeep(winsound.MB_ICONEXCLAMATION)
 
     def test_hand(self):
-        winsound.MessageBeep(winsound.MB_ICONHAND)
+        safe_MessageBeep(winsound.MB_ICONHAND)
 
     def test_question(self):
-        winsound.MessageBeep(winsound.MB_ICONQUESTION)
+        safe_MessageBeep(winsound.MB_ICONQUESTION)
 
 
 class PlaySoundTest(unittest.TestCase):
@@ -99,151 +88,34 @@ class PlaySoundTest(unittest.TestCase):
             "none", winsound.SND_ASYNC | winsound.SND_MEMORY
         )
 
-    @unittest.skipUnless(has_sound("SystemAsterisk"),
-                         "No default SystemAsterisk")
-    def test_alias_asterisk(self):
-        if _have_soundcard():
-            winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)
-        else:
-            self.assertRaises(
-                RuntimeError,
-                winsound.PlaySound,
-                'SystemAsterisk', winsound.SND_ALIAS
-            )
-
-    @unittest.skipUnless(has_sound("SystemExclamation"),
-                         "No default SystemExclamation")
-    def test_alias_exclamation(self):
-        if _have_soundcard():
-            winsound.PlaySound('SystemExclamation', winsound.SND_ALIAS)
-        else:
-            self.assertRaises(
-                RuntimeError,
-                winsound.PlaySound,
-                'SystemExclamation', winsound.SND_ALIAS
-            )
-
-    @unittest.skipUnless(has_sound("SystemExit"), "No default SystemExit")
-    def test_alias_exit(self):
-        if _have_soundcard():
-            winsound.PlaySound('SystemExit', winsound.SND_ALIAS)
-        else:
-            self.assertRaises(
-                RuntimeError,
-                winsound.PlaySound,
-                'SystemExit', winsound.SND_ALIAS
-            )
-
-    @unittest.skipUnless(has_sound("SystemHand"), "No default SystemHand")
-    def test_alias_hand(self):
-        if _have_soundcard():
-            winsound.PlaySound('SystemHand', winsound.SND_ALIAS)
-        else:
-            self.assertRaises(
-                RuntimeError,
-                winsound.PlaySound,
-                'SystemHand', winsound.SND_ALIAS
-            )
-
-    @unittest.skipUnless(has_sound("SystemQuestion"),
-                         "No default SystemQuestion")
-    def test_alias_question(self):
-        if _have_soundcard():
-            winsound.PlaySound('SystemQuestion', winsound.SND_ALIAS)
-        else:
-            self.assertRaises(
-                RuntimeError,
-                winsound.PlaySound,
-                'SystemQuestion', winsound.SND_ALIAS
-            )
+    def test_aliases(self):
+        aliases = [
+            "SystemAsterisk",
+            "SystemExclamation",
+            "SystemExit",
+            "SystemHand",
+            "SystemQuestion",
+        ]
+        for alias in aliases:
+            with self.subTest(alias=alias):
+                safe_PlaySound(alias, winsound.SND_ALIAS)
 
     def test_alias_fallback(self):
-        # In the absence of the ability to tell if a sound was actually
-        # played, this test has two acceptable outcomes: success (no error,
-        # sound was theoretically played; although as issue #19987 shows
-        # a box without a soundcard can "succeed") or RuntimeError.  Any
-        # other error is a failure.
-        try:
-            winsound.PlaySound('!"$%&/(#+*', winsound.SND_ALIAS)
-        except RuntimeError:
-            pass
+        safe_PlaySound('!"$%&/(#+*', winsound.SND_ALIAS)
 
     def test_alias_nofallback(self):
-        if _have_soundcard():
-            # Note that this is not the same as asserting RuntimeError
-            # will get raised:  you cannot convert this to
-            # self.assertRaises(...) form.  The attempt may or may not
-            # raise RuntimeError, but it shouldn't raise anything other
-            # than RuntimeError, and that's all we're trying to test
-            # here.  The MS docs aren't clear about whether the SDK
-            # PlaySound() with SND_ALIAS and SND_NODEFAULT will return
-            # True or False when the alias is unknown.  On Tim's WinXP
-            # box today, it returns True (no exception is raised).  What
-            # we'd really like to test is that no sound is played, but
-            # that requires first wiring an eardrum class into unittest
-            # <wink>.
-            try:
-                winsound.PlaySound(
-                    '!"$%&/(#+*',
-                    winsound.SND_ALIAS | winsound.SND_NODEFAULT
-                )
-            except RuntimeError:
-                pass
-        else:
-            self.assertRaises(
-                RuntimeError,
-                winsound.PlaySound,
-                '!"$%&/(#+*', winsound.SND_ALIAS | winsound.SND_NODEFAULT
-            )
+        safe_PlaySound('!"$%&/(#+*', winsound.SND_ALIAS | winsound.SND_NODEFAULT)
 
     def test_stopasync(self):
-        if _have_soundcard():
-            winsound.PlaySound(
-                'SystemQuestion',
-                winsound.SND_ALIAS | winsound.SND_ASYNC | winsound.SND_LOOP
-            )
-            time.sleep(0.5)
-            try:
-                winsound.PlaySound(
-                    'SystemQuestion',
-                    winsound.SND_ALIAS | winsound.SND_NOSTOP
-                )
-            except RuntimeError:
-                pass
-            else: # the first sound might already be finished
-                pass
-            winsound.PlaySound(None, winsound.SND_PURGE)
-        else:
-            # Issue 8367: PlaySound(None, winsound.SND_PURGE)
-            # does not raise on systems without a sound card.
-            pass
-
-
-def _get_cscript_path():
-    """Return the full path to cscript.exe or None."""
-    for dir in os.environ.get("PATH", "").split(os.pathsep):
-        cscript_path = os.path.join(dir, "cscript.exe")
-        if os.path.exists(cscript_path):
-            return cscript_path
-
-__have_soundcard_cache = None
-def _have_soundcard():
-    """Return True iff this computer has a soundcard."""
-    global __have_soundcard_cache
-    if __have_soundcard_cache is None:
-        cscript_path = _get_cscript_path()
-        if cscript_path is None:
-            # Could not find cscript.exe to run our VBScript helper. Default
-            # to True: most computers these days *do* have a soundcard.
-            return True
-
-        check_script = os.path.join(os.path.dirname(__file__),
-                                    "check_soundcard.vbs")
-        p = subprocess.Popen([cscript_path, check_script],
-                             stdout=subprocess.PIPE)
-        __have_soundcard_cache = not p.wait()
-        p.stdout.close()
-    return __have_soundcard_cache
+        safe_PlaySound(
+            'SystemQuestion',
+            winsound.SND_ALIAS | winsound.SND_ASYNC | winsound.SND_LOOP
+        )
+        time.sleep(0.5)
+        safe_PlaySound('SystemQuestion', winsound.SND_ALIAS | winsound.SND_NOSTOP)
+        # Issue 8367: PlaySound(None, winsound.SND_PURGE)
+        # does not raise on systems without a sound card.
+        winsound.PlaySound(None, winsound.SND_PURGE)
 
 
 if __name__ == "__main__":
index 44e3142..6c7616b 100644 (file)
@@ -18,7 +18,7 @@ import weakref
 
 from itertools import product
 from test import support
-from test.support import TESTFN, findfile, import_fresh_module, gc_collect
+from test.support import TESTFN, findfile, import_fresh_module, gc_collect, swap_attr
 
 # pyET is the pure-Python implementation.
 #
@@ -405,6 +405,14 @@ class ElementTreeTest(unittest.TestCase):
         self.assertEqual(ET.tostring(elem),
                 b'<test testa="testval" testb="test1" testc="test2">aa</test>')
 
+        elem = ET.Element('test')
+        elem.set('a', '\r')
+        elem.set('b', '\r\n')
+        elem.set('c', '\t\n\r ')
+        elem.set('d', '\n\n')
+        self.assertEqual(ET.tostring(elem),
+                b'<test a="&#10;" b="&#10;" c="&#09;&#10;&#10; " d="&#10;&#10;" />')
+
     def test_makeelement(self):
         # Test makeelement handling.
 
@@ -1860,6 +1868,12 @@ class BadElementTest(ElementTestCase, unittest.TestCase):
         e.extend([ET.Element('bar')])
         self.assertRaises(ValueError, e.remove, X('baz'))
 
+    def test_recursive_repr(self):
+        # Issue #25455
+        e = ET.Element('foo')
+        with swap_attr(e, 'tag', e):
+            with self.assertRaises(RuntimeError):
+                repr(e)  # Should not crash
 
 class MutatingElementPath(str):
     def __new__(cls, elem, *args):
@@ -2177,9 +2191,41 @@ class ElementIterTest(unittest.TestCase):
         # make sure both tag=None and tag='*' return all tags
         all_tags = ['document', 'house', 'room', 'room',
                     'shed', 'house', 'room']
+        self.assertEqual(summarize_list(doc.iter()), all_tags)
         self.assertEqual(self._ilist(doc), all_tags)
         self.assertEqual(self._ilist(doc, '*'), all_tags)
 
+    def test_getiterator(self):
+        doc = ET.XML('''
+            <document>
+                <house>
+                    <room>bedroom1</room>
+                    <room>bedroom2</room>
+                </house>
+                <shed>nothing here
+                </shed>
+                <house>
+                    <room>bedroom8</room>
+                </house>
+            </document>''')
+
+        self.assertEqual(summarize_list(doc.getiterator('room')),
+                         ['room'] * 3)
+        self.assertEqual(summarize_list(doc.getiterator('house')),
+                         ['house'] * 2)
+
+        # test that getiterator also accepts 'tag' as a keyword arg
+        self.assertEqual(
+            summarize_list(doc.getiterator(tag='room')),
+            ['room'] * 3)
+
+        # make sure both tag=None and tag='*' return all tags
+        all_tags = ['document', 'house', 'room', 'room',
+                    'shed', 'house', 'room']
+        self.assertEqual(summarize_list(doc.getiterator()), all_tags)
+        self.assertEqual(summarize_list(doc.getiterator(None)), all_tags)
+        self.assertEqual(summarize_list(doc.getiterator('*')), all_tags)
+
     def test_copy(self):
         a = ET.Element('a')
         it = a.iter()
index 96b446e..bfced12 100644 (file)
@@ -11,6 +11,7 @@ cET_alias = import_fresh_module('xml.etree.cElementTree',
                                 fresh=['_elementtree', 'xml.etree'])
 
 
+@unittest.skipUnless(cET, 'requires _elementtree')
 class MiscTests(unittest.TestCase):
     # Issue #8651.
     @support.bigmemtest(size=support._2G + 100, memuse=1, dry_run=False)
@@ -54,6 +55,15 @@ class MiscTests(unittest.TestCase):
             del element.attrib
         self.assertEqual(element.attrib, {'A': 'B', 'C': 'D'})
 
+    def test_trashcan(self):
+        # If this test fails, it will most likely die via segfault.
+        e = root = cET.Element('root')
+        for i in range(200000):
+            e = cET.SubElement(e, 'x')
+        del e
+        del root
+        support.gc_collect()
+
 
 @unittest.skipUnless(cET, 'requires _elementtree')
 class TestAliasWorking(unittest.TestCase):
index d278e06..0dd4bca 100644 (file)
@@ -12,7 +12,8 @@ import unittest
 from tempfile import TemporaryFile
 from random import randint, random, getrandbits
 
-from test.support import (TESTFN, findfile, unlink, rmtree,
+from test.support import script_helper
+from test.support import (TESTFN, findfile, unlink, rmtree, temp_dir,
                           requires_zlib, requires_bz2, requires_lzma,
                           captured_stdout, check_warnings)
 
@@ -415,6 +416,49 @@ class StoredTestsWithSourceFile(AbstractTestsWithSourceFile,
             f.seek(len(data))
             with zipfile.ZipFile(f, "r") as zipfp:
                 self.assertEqual(zipfp.namelist(), [TESTFN])
+                self.assertEqual(zipfp.read(TESTFN), self.data)
+        with open(TESTFN2, 'rb') as f:
+            self.assertEqual(f.read(len(data)), data)
+            zipfiledata = f.read()
+        with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
+            self.assertEqual(zipfp.namelist(), [TESTFN])
+            self.assertEqual(zipfp.read(TESTFN), self.data)
+
+    def test_read_concatenated_zip_file(self):
+        with io.BytesIO() as bio:
+            with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
+                zipfp.write(TESTFN, TESTFN)
+            zipfiledata = bio.getvalue()
+        data = b'I am not a ZipFile!'*10
+        with open(TESTFN2, 'wb') as f:
+            f.write(data)
+            f.write(zipfiledata)
+
+        with zipfile.ZipFile(TESTFN2) as zipfp:
+            self.assertEqual(zipfp.namelist(), [TESTFN])
+            self.assertEqual(zipfp.read(TESTFN), self.data)
+
+    def test_append_to_concatenated_zip_file(self):
+        with io.BytesIO() as bio:
+            with zipfile.ZipFile(bio, 'w', zipfile.ZIP_STORED) as zipfp:
+                zipfp.write(TESTFN, TESTFN)
+            zipfiledata = bio.getvalue()
+        data = b'I am not a ZipFile!'*1000000
+        with open(TESTFN2, 'wb') as f:
+            f.write(data)
+            f.write(zipfiledata)
+
+        with zipfile.ZipFile(TESTFN2, 'a') as zipfp:
+            self.assertEqual(zipfp.namelist(), [TESTFN])
+            zipfp.writestr('strfile', self.data)
+
+        with open(TESTFN2, 'rb') as f:
+            self.assertEqual(f.read(len(data)), data)
+            zipfiledata = f.read()
+        with io.BytesIO(zipfiledata) as bio, zipfile.ZipFile(bio) as zipfp:
+            self.assertEqual(zipfp.namelist(), [TESTFN, 'strfile'])
+            self.assertEqual(zipfp.read(TESTFN), self.data)
+            self.assertEqual(zipfp.read('strfile'), self.data)
 
     def test_ignores_newline_at_end(self):
         with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
@@ -2072,5 +2116,71 @@ class LzmaUniversalNewlineTests(AbstractUniversalNewlineTests,
                                 unittest.TestCase):
     compression = zipfile.ZIP_LZMA
 
+
+class CommandLineTest(unittest.TestCase):
+
+    def zipfilecmd(self, *args, **kwargs):
+        rc, out, err = script_helper.assert_python_ok('-m', 'zipfile', *args,
+                                                      **kwargs)
+        return out.replace(os.linesep.encode(), b'\n')
+
+    def zipfilecmd_failure(self, *args):
+        return script_helper.assert_python_failure('-m', 'zipfile', *args)
+
+    def test_test_command(self):
+        zip_name = findfile('zipdir.zip')
+        out = self.zipfilecmd('-t', zip_name)
+        self.assertEqual(out.rstrip(), b'Done testing')
+        zip_name = findfile('testtar.tar')
+        rc, out, err = self.zipfilecmd_failure('-t', zip_name)
+        self.assertEqual(out, b'')
+
+    def test_list_command(self):
+        zip_name = findfile('zipdir.zip')
+        t = io.StringIO()
+        with zipfile.ZipFile(zip_name, 'r') as tf:
+            tf.printdir(t)
+        expected = t.getvalue().encode('ascii', 'backslashreplace')
+        out = self.zipfilecmd('-l', zip_name,
+                              PYTHONIOENCODING='ascii:backslashreplace')
+        self.assertEqual(out, expected)
+
+    @requires_zlib
+    def test_create_command(self):
+        self.addCleanup(unlink, TESTFN)
+        with open(TESTFN, 'w') as f:
+            f.write('test 1')
+        os.mkdir(TESTFNDIR)
+        self.addCleanup(rmtree, TESTFNDIR)
+        with open(os.path.join(TESTFNDIR, 'file.txt'), 'w') as f:
+            f.write('test 2')
+        files = [TESTFN, TESTFNDIR]
+        namelist = [TESTFN, TESTFNDIR + '/', TESTFNDIR + '/file.txt']
+        try:
+            out = self.zipfilecmd('-c', TESTFN2, *files)
+            self.assertEqual(out, b'')
+            with zipfile.ZipFile(TESTFN2) as zf:
+                self.assertEqual(zf.namelist(), namelist)
+                self.assertEqual(zf.read(namelist[0]), b'test 1')
+                self.assertEqual(zf.read(namelist[2]), b'test 2')
+        finally:
+            unlink(TESTFN2)
+
+    def test_extract_command(self):
+        zip_name = findfile('zipdir.zip')
+        with temp_dir() as extdir:
+            out = self.zipfilecmd('-e', zip_name, extdir)
+            self.assertEqual(out, b'')
+            with zipfile.ZipFile(zip_name) as zf:
+                for zi in zf.infolist():
+                    path = os.path.join(extdir,
+                                zi.filename.replace('/', os.sep))
+                    if zi.filename.endswith('/'):
+                        self.assertTrue(os.path.isdir(path))
+                    else:
+                        self.assertTrue(os.path.isfile(path))
+                        with open(path, 'rb') as f:
+                            self.assertEqual(f.read(), zf.read(zi))
+
 if __name__ == "__main__":
     unittest.main()
index 0da5906..d5b3b22 100644 (file)
@@ -513,6 +513,19 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
                  "some.data": (NOW, "some data")}
         self.doTest(pyc_ext, files, TESTMOD)
 
+    def testDefaultOptimizationLevel(self):
+        # zipimport should use the default optimization level (#28131)
+        src = """if 1:  # indent hack
+        def test(val):
+            assert(val)
+            return val\n"""
+        files = {TESTMOD + '.py': (NOW, src)}
+        self.makeZip(files)
+        sys.path.insert(0, TEMP_ZIP)
+        mod = importlib.import_module(TESTMOD)
+        self.assertEqual(mod.test(1), 1)
+        self.assertRaises(AssertionError, mod.test, False)
+
     def testImport_WithStuff(self):
         # try importing from a zipfile which contains additional
         # stuff at the beginning of the file
@@ -596,10 +609,23 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
         z.writestr(zinfo, test_src)
         z.close()
         try:
-            zipimport.zipimporter(filename)
+            zipimport.zipimporter(filename).load_module(TESTMOD)
         finally:
             os.remove(filename)
 
+    def testBytesPath(self):
+        filename = support.TESTFN + ".zip"
+        self.addCleanup(support.unlink, filename)
+        with ZipFile(filename, "w") as z:
+            zinfo = ZipInfo(TESTMOD + ".py", time.localtime(NOW))
+            zinfo.compress_type = self.compression
+            z.writestr(zinfo, test_src)
+
+        zipimport.zipimporter(filename)
+        zipimport.zipimporter(os.fsencode(filename))
+        zipimport.zipimporter(bytearray(os.fsencode(filename)))
+        zipimport.zipimporter(memoryview(os.fsencode(filename)))
+
 
 @support.requires_zlib
 class CompressedZipImportTestCase(UncompressedZipImportTestCase):
@@ -620,6 +646,8 @@ class BadFileZipImportTestCase(unittest.TestCase):
     def testBadArgs(self):
         self.assertRaises(TypeError, zipimport.zipimporter, None)
         self.assertRaises(TypeError, zipimport.zipimporter, TESTMOD, kwd=None)
+        self.assertRaises(TypeError, zipimport.zipimporter,
+                          list(os.fsencode(TESTMOD)))
 
     def testFilenameTooLong(self):
         self.assertZipFailure('A' * 33000)
index 78ecade..6fea893 100644 (file)
@@ -122,6 +122,8 @@ class ExceptionTestCase(unittest.TestCase):
         with self.assertRaisesRegex(OverflowError, 'int too large'):
             zlib.decompress(b'', 15, sys.maxsize + 1)
         with self.assertRaisesRegex(OverflowError, 'int too large'):
+            zlib.decompressobj().decompress(b'', sys.maxsize + 1)
+        with self.assertRaisesRegex(OverflowError, 'int too large'):
             zlib.decompressobj().flush(sys.maxsize + 1)
 
 
@@ -188,15 +190,6 @@ class CompressTestCase(BaseCompressTestCase, unittest.TestCase):
     def test_big_decompress_buffer(self, size):
         self.check_big_decompress_buffer(size, zlib.decompress)
 
-    @bigmemtest(size=_4G + 100, memuse=1, dry_run=False)
-    def test_length_overflow(self, size):
-        data = b'x' * size
-        try:
-            self.assertRaises(OverflowError, zlib.compress, data, 1)
-            self.assertRaises(OverflowError, zlib.decompress, data)
-        finally:
-            data = None
-
     @bigmemtest(size=_4G, memuse=1)
     def test_large_bufsize(self, size):
         # Test decompress(bufsize) parameter greater than the internal limit
@@ -209,6 +202,16 @@ class CompressTestCase(BaseCompressTestCase, unittest.TestCase):
         compressed = zlib.compress(data, 1)
         self.assertEqual(zlib.decompress(compressed, 15, CustomInt()), data)
 
+    @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
+    @bigmemtest(size=_4G + 100, memuse=4)
+    def test_64bit_compress(self, size):
+        data = b'x' * size
+        try:
+            comp = zlib.compress(data, 0)
+            self.assertEqual(zlib.decompress(comp), data)
+        finally:
+            comp = data = None
+
 
 class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase):
     # Test compression object
@@ -678,16 +681,45 @@ class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase):
         decompress = lambda s: d.decompress(s) + d.flush()
         self.check_big_decompress_buffer(size, decompress)
 
-    @bigmemtest(size=_4G + 100, memuse=1, dry_run=False)
-    def test_length_overflow(self, size):
+    @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
+    @bigmemtest(size=_4G + 100, memuse=4)
+    def test_64bit_compress(self, size):
         data = b'x' * size
-        c = zlib.compressobj(1)
-        d = zlib.decompressobj()
+        co = zlib.compressobj(0)
+        do = zlib.decompressobj()
         try:
-            self.assertRaises(OverflowError, c.compress, data)
-            self.assertRaises(OverflowError, d.decompress, data)
+            comp = co.compress(data) + co.flush()
+            uncomp = do.decompress(comp) + do.flush()
+            self.assertEqual(uncomp, data)
         finally:
-            data = None
+            comp = uncomp = data = None
+
+    @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
+    @bigmemtest(size=_4G + 100, memuse=3)
+    def test_large_unused_data(self, size):
+        data = b'abcdefghijklmnop'
+        unused = b'x' * size
+        comp = zlib.compress(data) + unused
+        do = zlib.decompressobj()
+        try:
+            uncomp = do.decompress(comp) + do.flush()
+            self.assertEqual(unused, do.unused_data)
+            self.assertEqual(uncomp, data)
+        finally:
+            unused = comp = do = None
+
+    @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform')
+    @bigmemtest(size=_4G + 100, memuse=5)
+    def test_large_unconsumed_tail(self, size):
+        data = b'x' * size
+        do = zlib.decompressobj()
+        try:
+            comp = zlib.compress(data, 0)
+            uncomp = do.decompress(comp, 1) + do.flush()
+            self.assertEqual(uncomp, data)
+            self.assertEqual(do.unconsumed_tail, b'')
+        finally:
+            comp = uncomp = data = None
 
     def test_wbits(self):
         # wbits=0 only supported since zlib v1.2.3.5
index 05e0306..0c18dc5 100644 (file)
@@ -10,13 +10,8 @@ import re
 __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent', 'shorten']
 
 # Hardcode the recognized whitespace characters to the US-ASCII
-# whitespace characters.  The main reason for doing this is that in
-# ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales
-# that character winds up in string.whitespace.  Respecting
-# string.whitespace in those cases would 1) make textwrap treat 0xa0 the
-# same as any other whitespace char, which is clearly wrong (it's a
-# *non-breaking* space), 2) possibly cause problems with Unicode,
-# since 0xa0 is not in range(128).
+# whitespace characters.  The main reason for doing this is that
+# some Unicode spaces (like \u00a0) are non-breaking whitespaces.
 _whitespace = '\t\n\x0b\x0c\r '
 
 class TextWrapper:
@@ -81,29 +76,34 @@ class TextWrapper:
     # (after stripping out empty strings).
     word_punct = r'[\w!"\'&.,?]'
     letter = r'[^\d\W]'
+    whitespace = r'[%s]' % re.escape(_whitespace)
+    nowhitespace = '[^' + whitespace[1:]
     wordsep_re = re.compile(r'''
         ( # any whitespace
-          \s+
+          %(ws)s+
         | # em-dash between words
           (?<=%(wp)s) -{2,} (?=\w)
         | # word, possibly hyphenated
-          \S+? (?:
+          %(nws)s+? (?:
             # hyphenated word
               -(?: (?<=%(lt)s{2}-) | (?<=%(lt)s-%(lt)s-))
               (?= %(lt)s -? %(lt)s)
             | # end of word
-              (?=\s|\Z)
+              (?=%(ws)s|\Z)
             | # em-dash
               (?<=%(wp)s) (?=-{2,}\w)
             )
-        )''' % {'wp': word_punct, 'lt': letter}, re.VERBOSE)
-    del word_punct, letter
+        )''' % {'wp': word_punct, 'lt': letter,
+                'ws': whitespace, 'nws': nowhitespace},
+        re.VERBOSE)
+    del word_punct, letter, nowhitespace
 
     # This less funky little regex just split on recognized spaces. E.g.
     #   "Hello there -- you goof-ball, use the -b option!"
     # splits into
     #   Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/
-    wordsep_simple_re = re.compile(r'(\s+)')
+    wordsep_simple_re = re.compile(r'(%s+)' % whitespace)
+    del whitespace
 
     # XXX this is not locale- or charset-aware -- string.lowercase
     # is US-ASCII only (and therefore English-only)
@@ -112,7 +112,6 @@ class TextWrapper:
                                  r'[\"\']?'           # optional end-of-quote
                                  r'\Z')               # end of chunk
 
-
     def __init__(self,
                  width=70,
                  initial_indent="",
index c9f8cb6..06b7b9b 100644 (file)
@@ -639,7 +639,7 @@ class Barrier:
             self._break()
             raise
 
-    # Wait in the barrier until we are relased.  Raise an exception
+    # Wait in the barrier until we are released.  Raise an exception
     # if the barrier is reset or broken.
     def _wait(self, timeout):
         if not self._cond.wait_for(lambda : self._state != 0, timeout):
index aa646dc..1eaab44 100644 (file)
@@ -271,7 +271,7 @@ class Variable:
 
         Return the name of the callback.
         """
-        f = CallWrapper(callback, None, self).__call__
+        f = CallWrapper(callback, None, self._root).__call__
         cbname = repr(id(f))
         try:
             callback = callback.__func__
@@ -295,14 +295,19 @@ class Variable:
         CBNAME is the name of the callback returned from trace_variable or trace.
         """
         self._tk.call("trace", "vdelete", self._name, mode, cbname)
-        self._tk.deletecommand(cbname)
-        try:
-            self._tclCommands.remove(cbname)
-        except ValueError:
-            pass
+        cbname = self._tk.splitlist(cbname)[0]
+        for m, ca in self.trace_vinfo():
+            if self._tk.splitlist(ca)[0] == cbname:
+                break
+        else:
+            self._tk.deletecommand(cbname)
+            try:
+                self._tclCommands.remove(cbname)
+            except ValueError:
+                pass
     def trace_vinfo(self):
         """Return all trace callback information."""
-        return [self._tk.split(x) for x in self._tk.splitlist(
+        return [self._tk.splitlist(x) for x in self._tk.splitlist(
             self._tk.call("trace", "vinfo", self._name))]
     def __eq__(self, other):
         """Comparison for equality (==).
@@ -352,7 +357,11 @@ class IntVar(Variable):
 
     def get(self):
         """Return the value of the variable as an integer."""
-        return self._tk.getint(self._tk.globalgetvar(self._name))
+        value = self._tk.globalgetvar(self._name)
+        try:
+            return self._tk.getint(value)
+        except (TypeError, TclError):
+            return int(self._tk.getdouble(value))
 
 class DoubleVar(Variable):
     """Value holder for float variables."""
@@ -2859,7 +2868,7 @@ class Scale(Widget):
         value = self.tk.call(self._w, 'get')
         try:
             return self.tk.getint(value)
-        except (ValueError, TclError):
+        except (ValueError, TypeError, TclError):
             return self.tk.getdouble(value)
     def set(self, value):
         """Set the value to VALUE."""
index abdce96..d8ba9ce 100644 (file)
@@ -1,5 +1,5 @@
 import unittest
-
+import gc
 from tkinter import (Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tcl,
                      TclError)
 
@@ -87,6 +87,55 @@ class TestVariable(TestBase):
         v.set("value")
         self.assertTrue(v.side_effect)
 
+    def test_trace(self):
+        v = Variable(self.root)
+        vname = str(v)
+        trace = []
+        def read_tracer(*args):
+            trace.append(('read',) + args)
+        def write_tracer(*args):
+            trace.append(('write',) + args)
+        cb1 = v.trace_variable('r', read_tracer)
+        cb2 = v.trace_variable('wu', write_tracer)
+        self.assertEqual(sorted(v.trace_vinfo()), [('r', cb1), ('wu', cb2)])
+        self.assertEqual(trace, [])
+
+        v.set('spam')
+        self.assertEqual(trace, [('write', vname, '', 'w')])
+
+        trace = []
+        v.get()
+        self.assertEqual(trace, [('read', vname, '', 'r')])
+
+        trace = []
+        info = sorted(v.trace_vinfo())
+        v.trace_vdelete('w', cb1)  # Wrong mode
+        self.assertEqual(sorted(v.trace_vinfo()), info)
+        with self.assertRaises(TclError):
+            v.trace_vdelete('r', 'spam')  # Wrong command name
+        self.assertEqual(sorted(v.trace_vinfo()), info)
+        v.trace_vdelete('r', (cb1, 43)) # Wrong arguments
+        self.assertEqual(sorted(v.trace_vinfo()), info)
+        v.get()
+        self.assertEqual(trace, [('read', vname, '', 'r')])
+
+        trace = []
+        v.trace_vdelete('r', cb1)
+        self.assertEqual(v.trace_vinfo(), [('wu', cb2)])
+        v.get()
+        self.assertEqual(trace, [])
+
+        trace = []
+        del write_tracer
+        gc.collect()
+        v.set('eggs')
+        self.assertEqual(trace, [('write', vname, '', 'w')])
+
+        trace = []
+        del v
+        gc.collect()
+        self.assertEqual(trace, [('write', vname, '', 'u')])
+
 
 class TestStringVar(TestBase):
 
@@ -118,15 +167,14 @@ class TestIntVar(TestBase):
         self.assertEqual(123, v.get())
         self.root.globalsetvar("name", "345")
         self.assertEqual(345, v.get())
+        self.root.globalsetvar("name", "876.5")
+        self.assertEqual(876, v.get())
 
     def test_invalid_value(self):
         v = IntVar(self.root, name="name")
         self.root.globalsetvar("name", "value")
         with self.assertRaises((ValueError, TclError)):
             v.get()
-        self.root.globalsetvar("name", "345.0")
-        with self.assertRaises((ValueError, TclError)):
-            v.get()
 
 
 class TestDoubleVar(TestBase):
index f33945c..218b27f 100644 (file)
@@ -69,14 +69,12 @@ class LabeledScaleTest(AbstractTkTest, unittest.TestCase):
 
         # variable initialization/passing
         passed_expected = (('0', 0), (0, 0), (10, 10),
-            (-1, -1), (sys.maxsize + 1, sys.maxsize + 1))
+            (-1, -1), (sys.maxsize + 1, sys.maxsize + 1),
+            (2.5, 2), ('2.5', 2))
         for pair in passed_expected:
             x = ttk.LabeledScale(self.root, from_=pair[0])
             self.assertEqual(x.value, pair[1])
             x.destroy()
-        x = ttk.LabeledScale(self.root, from_='2.5')
-        self.assertRaises((ValueError, tkinter.TclError), x._variable.get)
-        x.destroy()
         x = ttk.LabeledScale(self.root, from_=None)
         self.assertRaises((ValueError, tkinter.TclError), x._variable.get)
         x.destroy()
@@ -155,8 +153,10 @@ class LabeledScaleTest(AbstractTkTest, unittest.TestCase):
         # The following update is needed since the test doesn't use mainloop,
         # at the same time this shouldn't affect test outcome
         x.update()
+        self.assertEqual(x.value, newval)
         self.assertEqual(x.label['text'],
                          newval if self.wantobjects else str(newval))
+        self.assertEqual(float(x.scale.get()), newval)
         self.assertGreater(x.scale.coords()[0], curr_xcoord)
         self.assertEqual(x.scale.coords()[0],
             int(x.label.place_info()['x']))
@@ -168,10 +168,19 @@ class LabeledScaleTest(AbstractTkTest, unittest.TestCase):
             conv = int
         x.value = conv(x.scale['to']) + 1 # no changes shouldn't happen
         x.update()
+        self.assertEqual(x.value, newval)
         self.assertEqual(conv(x.label['text']), newval)
+        self.assertEqual(float(x.scale.get()), newval)
         self.assertEqual(x.scale.coords()[0],
             int(x.label.place_info()['x']))
 
+        # non-integer value
+        x.value = newval = newval + 1.5
+        x.update()
+        self.assertEqual(x.value, int(newval))
+        self.assertEqual(conv(x.label['text']), int(newval))
+        self.assertEqual(float(x.scale.get()), newval)
+
         x.destroy()
 
 
index c031351..8bd22d0 100644 (file)
@@ -1486,6 +1486,57 @@ class TreeviewTest(AbstractWidgetTest, unittest.TestCase):
             value)
 
 
+    def test_selection(self):
+        # item 'none' doesn't exist
+        self.assertRaises(tkinter.TclError, self.tv.selection_set, 'none')
+        self.assertRaises(tkinter.TclError, self.tv.selection_add, 'none')
+        self.assertRaises(tkinter.TclError, self.tv.selection_remove, 'none')
+        self.assertRaises(tkinter.TclError, self.tv.selection_toggle, 'none')
+
+        item1 = self.tv.insert('', 'end')
+        item2 = self.tv.insert('', 'end')
+        c1 = self.tv.insert(item1, 'end')
+        c2 = self.tv.insert(item1, 'end')
+        c3 = self.tv.insert(item1, 'end')
+        self.assertEqual(self.tv.selection(), ())
+
+        self.tv.selection_set((c1, item2))
+        self.assertEqual(self.tv.selection(), (c1, item2))
+        self.tv.selection_set(c2)
+        self.assertEqual(self.tv.selection(), (c2,))
+
+        self.tv.selection_add((c1, item2))
+        self.assertEqual(self.tv.selection(), (c1, c2, item2))
+        self.tv.selection_add(item1)
+        self.assertEqual(self.tv.selection(), (item1, c1, c2, item2))
+
+        self.tv.selection_remove((item1, c3))
+        self.assertEqual(self.tv.selection(), (c1, c2, item2))
+        self.tv.selection_remove(c2)
+        self.assertEqual(self.tv.selection(), (c1, item2))
+
+        self.tv.selection_toggle((c1, c3))
+        self.assertEqual(self.tv.selection(), (c3, item2))
+        self.tv.selection_toggle(item2)
+        self.assertEqual(self.tv.selection(), (c3,))
+
+        self.tv.insert('', 'end', id='with spaces')
+        self.tv.selection_set('with spaces')
+        self.assertEqual(self.tv.selection(), ('with spaces',))
+
+        self.tv.insert('', 'end', id='{brace')
+        self.tv.selection_set('{brace')
+        self.assertEqual(self.tv.selection(), ('{brace',))
+
+        self.tv.insert('', 'end', id='unicode\u20ac')
+        self.tv.selection_set('unicode\u20ac')
+        self.assertEqual(self.tv.selection(), ('unicode\u20ac',))
+
+        self.tv.insert('', 'end', id=b'bytes\xe2\x82\xac')
+        self.tv.selection_set(b'bytes\xe2\x82\xac')
+        self.assertEqual(self.tv.selection(), ('bytes\xe2\x82\xac',))
+
+
     def test_set(self):
         self.tv['columns'] = ['A', 'B']
         item = self.tv.insert('', 'end', values=['a', 'b'])
index f667933..a1006bd 100644 (file)
@@ -1,7 +1,3 @@
-# -*-mode: python; fill-column: 75; tab-width: 8 -*-
-#
-# $Id$
-#
 # Tix.py -- Tix widget wrappers.
 #
 #       For Tix, see http://tix.sourceforge.net
 # appreciate the advantages.
 #
 
+import os
+import tkinter
 from tkinter import *
-from tkinter import _cnfmerge, _default_root
+from tkinter import _cnfmerge
 
 # WARNING - TkVersion is a limited precision floating point number
 if TkVersion < 3.999:
@@ -72,7 +70,6 @@ TCL_ALL_EVENTS    = 0
 # BEWARE - this is implemented by copying some code from the Widget class
 #          in Tkinter (to override Widget initialization) and is therefore
 #          liable to break.
-import tkinter, os
 
 # Could probably add this to Tkinter.Misc
 class tixCommand:
@@ -476,10 +473,15 @@ class DisplayStyle:
     (multiple) Display Items"""
 
     def __init__(self, itemtype, cnf={}, **kw):
-        master = _default_root              # global from Tkinter
-        if not master and 'refwindow' in cnf: master=cnf['refwindow']
-        elif not master and 'refwindow' in kw:  master= kw['refwindow']
-        elif not master: raise RuntimeError("Too early to create display style: no root window")
+        if 'refwindow' in kw:
+            master = kw['refwindow']
+        elif 'refwindow' in cnf:
+            master = cnf['refwindow']
+        else:
+            master = tkinter._default_root
+            if not master:
+                raise RuntimeError("Too early to create display style: "
+                                   "no root window")
         self.tk = master.tk
         self.stylename = self.tk.call('tixDisplayStyle', itemtype,
                             *self._options(cnf,kw) )
@@ -923,7 +925,11 @@ class HList(TixWidget, XView, YView):
         return self.tk.call(self._w, 'header', 'cget', col, opt)
 
     def header_exists(self,  col):
-        return self.tk.call(self._w, 'header', 'exists', col)
+        # A workaround to Tix library bug (issue #25464).
+        # The documented command is "exists", but only erroneous "exist" is
+        # accepted.
+        return self.tk.getboolean(self.tk.call(self._w, 'header', 'exist', col))
+    header_exist = header_exists
 
     def header_delete(self, col):
         self.tk.call(self._w, 'header', 'delete', col)
index 8f9369b..f4a6d8c 100644 (file)
@@ -151,7 +151,7 @@ def _format_elemcreate(etype, script=False, *args, **kw):
 
 def _format_layoutlist(layout, indent=0, indent_size=2):
     """Formats a layout list so we can pass the result to ttk::style
-    layout and ttk::style settings. Note that the layout doesn't has to
+    layout and ttk::style settings. Note that the layout doesn't have to
     be a list necessarily.
 
     E.g.:
@@ -1392,7 +1392,9 @@ class Treeview(Widget, tkinter.XView, tkinter.YView):
 
     def selection(self, selop=None, items=None):
         """If selop is not specified, returns selected items."""
-        return self.tk.call(self._w, "selection", selop, items)
+        if isinstance(items, (str, bytes)):
+            items = (items,)
+        return self.tk.splitlist(self.tk.call(self._w, "selection", selop, items))
 
 
     def selection_set(self, items):
index a2eb539..c5fd617 100644 (file)
@@ -140,7 +140,7 @@ def format_exception_only(etype, value):
 
 def _format_final_exc_line(etype, value):
     valuestr = _some_str(value)
-    if value == 'None' or value is None or not valuestr:
+    if value is None or not valuestr:
         line = "%s\n" % etype
     else:
         line = "%s: %s\n" % (etype, valuestr)
index cbd4f47..8036b7f 100644 (file)
@@ -179,7 +179,7 @@ def config_dict(filename):
             continue
         try:
             key, value = line.split("=")
-        except:
+        except ValueError:
             print("Bad line in config-file %s:\n%s" % (filename,line))
             continue
         key = key.strip()
@@ -192,7 +192,7 @@ def config_dict(filename):
                     value = float(value)
                 else:
                     value = int(value)
-            except:
+            except ValueError:
                 pass # value need not be converted
         cfgdict[key] = value
     return cfgdict
@@ -220,7 +220,7 @@ def readconfig(cfgdict):
     try:
         head, tail = split(__file__)
         cfg_file2 = join(head, default_cfg)
-    except:
+    except Exception:
         cfg_file2 = ""
     if isfile(cfg_file2):
         cfgdict2 = config_dict(cfg_file2)
@@ -229,7 +229,7 @@ def readconfig(cfgdict):
 
 try:
     readconfig(_CFG)
-except:
+except Exception:
     print ("No configfile read, reason unknown")
 
 
@@ -653,7 +653,7 @@ class TurtleScreenBase(object):
                     x, y = (self.cv.canvasx(event.x)/self.xscale,
                            -self.cv.canvasy(event.y)/self.yscale)
                     fun(x, y)
-                except:
+                except Exception:
                     pass
             self.cv.tag_bind(item, "<Button%s-Motion>" % num, eventfun, add)
 
@@ -1035,7 +1035,7 @@ class TurtleScreen(TurtleScreenBase):
         """Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
 
         Optional argument:
-        mode -- on of the strings 'standard', 'logo' or 'world'
+        mode -- one of the strings 'standard', 'logo' or 'world'
 
         Mode 'standard' is compatible with turtle.py.
         Mode 'logo' is compatible with most Logo-Turtle-Graphics.
@@ -1158,7 +1158,7 @@ class TurtleScreen(TurtleScreenBase):
                 raise TurtleGraphicsError("bad color string: %s" % str(color))
         try:
             r, g, b = color
-        except:
+        except (TypeError, ValueError):
             raise TurtleGraphicsError("bad color arguments: %s" % str(color))
         if self._colormode == 1.0:
             r, g, b = [round(255.0*x) for x in (r, g, b)]
@@ -2702,7 +2702,7 @@ class RawTurtle(TPen, TNavigator):
             return args
         try:
             r, g, b = args
-        except:
+        except (TypeError, ValueError):
             raise TurtleGraphicsError("bad color arguments: %s" % str(args))
         if self.screen._colormode == 1.0:
             r, g, b = [round(255.0*x) for x in (r, g, b)]
@@ -3865,7 +3865,7 @@ def read_docstrings(lang):
         try:
 #            eval(key).im_func.__doc__ = docsdict[key]
             eval(key).__doc__ = docsdict[key]
-        except:
+        except Exception:
             print("Bad docstring-entry: %s" % key)
 
 _LANGUAGE = _CFG["language"]
@@ -3875,7 +3875,7 @@ try:
         read_docstrings(_LANGUAGE)
 except ImportError:
     print("Cannot find docsdict for", _LANGUAGE)
-except:
+except Exception:
     print ("Unknown Error when trying to import %s-docstring-dictionary" %
                                                                   _LANGUAGE)
 
index 4cac66c..34845b7 100644 (file)
@@ -17,6 +17,7 @@ __all__ = [
     # Super-special typing primitives.
     'Any',
     'Callable',
+    'ClassVar',
     'Generic',
     'Optional',
     'Tuple',
@@ -26,9 +27,6 @@ __all__ = [
 
     # ABCs (from collections.abc).
     'AbstractSet',  # collections.abc.Set.
-    'Awaitable',
-    'AsyncIterator',
-    'AsyncIterable',
     'ByteString',
     'Container',
     'Hashable',
@@ -44,6 +42,14 @@ __all__ = [
     'Sequence',
     'Sized',
     'ValuesView',
+    # The following are added depending on presence
+    # of their non-generic counterparts in stdlib:
+    # Awaitable,
+    # AsyncIterator,
+    # AsyncIterable,
+    # Coroutine,
+    # Collection,
+    # ContextManager
 
     # Structural checks, a.k.a. protocols.
     'Reversible',
@@ -57,6 +63,7 @@ __all__ = [
     'DefaultDict',
     'List',
     'Set',
+    'FrozenSet',
     'NamedTuple',  # Not really a type.
     'Generator',
 
@@ -85,17 +92,24 @@ def _qualname(x):
         return x.__name__
 
 
+def _trim_name(nm):
+    if nm.startswith('_') and nm not in ('_TypeAlias',
+                    '_ForwardRef', '_TypingBase', '_FinalTypingBase'):
+        nm = nm[1:]
+    return nm
+
+
 class TypingMeta(type):
-    """Metaclass for every type defined below.
+    """Metaclass for most types defined in typing module
+    (not a part of public API).
 
     This overrides __new__() to require an extra keyword parameter
     '_root', which serves as a guard against naive subclassing of the
     typing classes.  Any legitimate class defined using a metaclass
-    derived from TypingMeta (including internal subclasses created by
-    e.g.  Union[X, Y]) must pass _root=True.
+    derived from TypingMeta must pass _root=True.
 
-    This also defines a dummy constructor (all the work is done in
-    __new__) and a nicer repr().
+    This also defines a dummy constructor (all the work for most typing
+    constructs is done in __new__) and a nicer repr().
     """
 
     _is_protocol = False
@@ -112,8 +126,8 @@ class TypingMeta(type):
     def _eval_type(self, globalns, localns):
         """Override this in subclasses to interpret forward references.
 
-        For example, Union['C'] is internally stored as
-        Union[_ForwardRef('C')], which should evaluate to _Union[C],
+        For example, List['C'] is internally stored as
+        List[_ForwardRef('C')], which should evaluate to List[C],
         where C is an object found in globalns or localns (searching
         localns first, of course).
         """
@@ -123,50 +137,88 @@ class TypingMeta(type):
         pass
 
     def __repr__(self):
-        return '%s.%s' % (self.__module__, _qualname(self))
+        qname = _trim_name(_qualname(self))
+        return '%s.%s' % (self.__module__, qname)
+
+
+class _TypingBase(metaclass=TypingMeta, _root=True):
+    """Internal indicator of special typing constructs."""
+
+    __slots__ = ()
+
+    def __init__(self, *args, **kwds):
+        pass
+
+    def __new__(cls, *args, **kwds):
+        """Constructor.
+
+        This only exists to give a better error message in case
+        someone tries to subclass a special typing object (not a good idea).
+        """
+        if (len(args) == 3 and
+                isinstance(args[0], str) and
+                isinstance(args[1], tuple)):
+            # Close enough.
+            raise TypeError("Cannot subclass %r" % cls)
+        return super().__new__(cls)
+
+    # Things that are not classes also need these.
+    def _eval_type(self, globalns, localns):
+        return self
+
+    def _get_type_vars(self, tvars):
+        pass
+
+    def __repr__(self):
+        cls = type(self)
+        qname = _trim_name(_qualname(cls))
+        return '%s.%s' % (cls.__module__, qname)
+
+    def __call__(self, *args, **kwds):
+        raise TypeError("Cannot instantiate %r" % type(self))
 
 
-class Final:
-    """Mix-in class to prevent instantiation."""
+class _FinalTypingBase(_TypingBase, _root=True):
+    """Internal mix-in class to prevent instantiation.
+
+    Prevents instantiation unless _root=True is given in class call.
+    It is used to create pseudo-singleton instances Any, Union, Optional, etc.
+    """
 
     __slots__ = ()
 
-    def __new__(self, *args, **kwds):
-        raise TypeError("Cannot instantiate %r" % self.__class__)
+    def __new__(cls, *args, _root=False, **kwds):
+        self = super().__new__(cls, *args, **kwds)
+        if _root is True:
+            return self
+        raise TypeError("Cannot instantiate %r" % cls)
+
+    def __reduce__(self):
+        return _trim_name(type(self).__name__)
+
 
+class _ForwardRef(_TypingBase, _root=True):
+    """Internal wrapper to hold a forward reference."""
 
-class _ForwardRef(TypingMeta):
-    """Wrapper to hold a forward reference."""
+    __slots__ = ('__forward_arg__', '__forward_code__',
+                 '__forward_evaluated__', '__forward_value__')
 
-    def __new__(cls, arg):
+    def __init__(self, arg):
+        super().__init__(arg)
         if not isinstance(arg, str):
-            raise TypeError('ForwardRef must be a string -- got %r' % (arg,))
+            raise TypeError('Forward reference must be a string -- got %r' % (arg,))
         try:
             code = compile(arg, '<string>', 'eval')
         except SyntaxError:
-            raise SyntaxError('ForwardRef must be an expression -- got %r' %
+            raise SyntaxError('Forward reference must be an expression -- got %r' %
                               (arg,))
-        self = super().__new__(cls, arg, (), {}, _root=True)
         self.__forward_arg__ = arg
         self.__forward_code__ = code
         self.__forward_evaluated__ = False
         self.__forward_value__ = None
-        typing_globals = globals()
-        frame = sys._getframe(1)
-        while frame is not None and frame.f_globals is typing_globals:
-            frame = frame.f_back
-        assert frame is not None
-        self.__forward_frame__ = frame
-        return self
 
     def _eval_type(self, globalns, localns):
-        if not isinstance(localns, dict):
-            raise TypeError('ForwardRef localns must be a dict -- got %r' %
-                            (localns,))
-        if not isinstance(globalns, dict):
-            raise TypeError('ForwardRef globalns must be a dict -- got %r' %
-                            (globalns,))
-        if not self.__forward_evaluated__:
+        if not self.__forward_evaluated__ or localns is not globalns:
             if globalns is None and localns is None:
                 globalns = localns = {}
             elif globalns is None:
@@ -179,49 +231,36 @@ class _ForwardRef(TypingMeta):
             self.__forward_evaluated__ = True
         return self.__forward_value__
 
+    def __eq__(self, other):
+        if not isinstance(other, _ForwardRef):
+            return NotImplemented
+        return (self.__forward_arg__ == other.__forward_arg__ and
+                self.__forward_value__ == other.__forward_value__)
+
+    def __hash__(self):
+        return hash((self.__forward_arg__, self.__forward_value__))
+
     def __instancecheck__(self, obj):
         raise TypeError("Forward references cannot be used with isinstance().")
 
     def __subclasscheck__(self, cls):
-        if not self.__forward_evaluated__:
-            globalns = self.__forward_frame__.f_globals
-            localns = self.__forward_frame__.f_locals
-            try:
-                self._eval_type(globalns, localns)
-            except NameError:
-                return False  # Too early.
-        return issubclass(cls, self.__forward_value__)
+        raise TypeError("Forward references cannot be used with issubclass().")
 
     def __repr__(self):
         return '_ForwardRef(%r)' % (self.__forward_arg__,)
 
 
-class _TypeAlias:
+class _TypeAlias(_TypingBase, _root=True):
     """Internal helper class for defining generic variants of concrete types.
 
-    Note that this is not a type; let's call it a pseudo-type.  It can
-    be used in instance and subclass checks, e.g. isinstance(m, Match)
-    or issubclass(type(m), Match).  However, it cannot be itself the
-    target of an issubclass() call; e.g. issubclass(Match, C) (for
-    some arbitrary class C) raises TypeError rather than returning
-    False.
+    Note that this is not a type; let's call it a pseudo-type.  It cannot
+    be used in instance and subclass checks in parameterized form, i.e.
+    ``isinstance(42, Match[str])`` raises ``TypeError`` instead of returning
+    ``False``.
     """
 
     __slots__ = ('name', 'type_var', 'impl_type', 'type_checker')
 
-    def __new__(cls, *args, **kwds):
-        """Constructor.
-
-        This only exists to give a better error message in case
-        someone tries to subclass a type alias (not a good idea).
-        """
-        if (len(args) == 3 and
-                isinstance(args[0], str) and
-                isinstance(args[1], tuple)):
-            # Close enough.
-            raise TypeError("A type alias cannot be subclassed")
-        return object.__new__(cls)
-
     def __init__(self, name, type_var, impl_type, type_checker):
         """Initializer.
 
@@ -234,9 +273,9 @@ class _TypeAlias:
                 and returns a value that should be a type_var instance.
         """
         assert isinstance(name, str), repr(name)
-        assert isinstance(type_var, type), repr(type_var)
         assert isinstance(impl_type, type), repr(impl_type)
         assert not isinstance(impl_type, TypingMeta), repr(impl_type)
+        assert isinstance(type_var, (type, _TypingBase)), repr(type_var)
         self.name = name
         self.type_var = type_var
         self.impl_type = impl_type
@@ -246,36 +285,41 @@ class _TypeAlias:
         return "%s[%s]" % (self.name, _type_repr(self.type_var))
 
     def __getitem__(self, parameter):
-        assert isinstance(parameter, type), repr(parameter)
         if not isinstance(self.type_var, TypeVar):
             raise TypeError("%s cannot be further parameterized." % self)
-        if self.type_var.__constraints__:
-            if not issubclass(parameter, Union[self.type_var.__constraints__]):
+        if self.type_var.__constraints__ and isinstance(parameter, type):
+            if not issubclass(parameter, self.type_var.__constraints__):
                 raise TypeError("%s is not a valid substitution for %s." %
                                 (parameter, self.type_var))
+        if isinstance(parameter, TypeVar) and parameter is not self.type_var:
+            raise TypeError("%s cannot be re-parameterized." % self)
         return self.__class__(self.name, parameter,
                               self.impl_type, self.type_checker)
 
+    def __eq__(self, other):
+        if not isinstance(other, _TypeAlias):
+            return NotImplemented
+        return self.name == other.name and self.type_var == other.type_var
+
+    def __hash__(self):
+        return hash((self.name, self.type_var))
+
     def __instancecheck__(self, obj):
-        raise TypeError("Type aliases cannot be used with isinstance().")
+        if not isinstance(self.type_var, TypeVar):
+            raise TypeError("Parameterized type aliases cannot be used "
+                            "with isinstance().")
+        return isinstance(obj, self.impl_type)
 
     def __subclasscheck__(self, cls):
-        if cls is Any:
-            return True
-        if isinstance(cls, _TypeAlias):
-            # Covariance.  For now, we compare by name.
-            return (cls.name == self.name and
-                    issubclass(cls.type_var, self.type_var))
-        else:
-            # Note that this is too lenient, because the
-            # implementation type doesn't carry information about
-            # whether it is about bytes or str (for example).
-            return issubclass(cls, self.impl_type)
+        if not isinstance(self.type_var, TypeVar):
+            raise TypeError("Parameterized type aliases cannot be used "
+                            "with issubclass().")
+        return issubclass(cls, self.impl_type)
 
 
 def _get_type_vars(types, tvars):
     for t in types:
-        if isinstance(t, TypingMeta):
+        if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
             t._get_type_vars(tvars)
 
 
@@ -286,14 +330,13 @@ def _type_vars(types):
 
 
 def _eval_type(t, globalns, localns):
-    if isinstance(t, TypingMeta):
+    if isinstance(t, TypingMeta) or isinstance(t, _TypingBase):
         return t._eval_type(globalns, localns)
-    else:
-        return t
+    return t
 
 
 def _type_check(arg, msg):
-    """Check that the argument is a type, and return it.
+    """Check that the argument is a type, and return it (internal helper).
 
     As a special case, accept None and return type(None) instead.
     Also, _TypeAlias instances (e.g. Match, Pattern) are acceptable.
@@ -308,13 +351,19 @@ def _type_check(arg, msg):
         return type(None)
     if isinstance(arg, str):
         arg = _ForwardRef(arg)
-    if not isinstance(arg, (type, _TypeAlias)) and not callable(arg):
+    if (isinstance(arg, _TypingBase) and type(arg).__name__ == '_ClassVar' or
+        not isinstance(arg, (type, _TypingBase)) and not callable(arg)):
         raise TypeError(msg + " Got %.100r." % (arg,))
+    # Bare Union etc. are not valid as type arguments
+    if (type(arg).__name__ in ('_Union', '_Optional')
+        and not getattr(arg, '__origin__', None)
+        or isinstance(arg, TypingMeta) and _gorg(arg) in (Generic, _Protocol)):
+        raise TypeError("Plain %s is not valid as type argument" % arg)
     return arg
 
 
 def _type_repr(obj):
-    """Return the repr() of an object, special-casing types.
+    """Return the repr() of an object, special-casing types (internal helper).
 
     If obj is a type, we return a shorter version than the default
     type.__repr__, based on the module and qualified name, which is
@@ -324,40 +373,39 @@ def _type_repr(obj):
     if isinstance(obj, type) and not isinstance(obj, TypingMeta):
         if obj.__module__ == 'builtins':
             return _qualname(obj)
-        else:
-            return '%s.%s' % (obj.__module__, _qualname(obj))
-    else:
-        return repr(obj)
+        return '%s.%s' % (obj.__module__, _qualname(obj))
+    if obj is ...:
+        return('...')
+    if isinstance(obj, types.FunctionType):
+        return obj.__name__
+    return repr(obj)
+
 
+class _Any(_FinalTypingBase, _root=True):
+    """Special type indicating an unconstrained type.
 
-class AnyMeta(TypingMeta):
-    """Metaclass for Any."""
+    - Any is compatible with every type.
+    - Any assumed to have all methods.
+    - All values assumed to be instances of Any.
 
-    def __new__(cls, name, bases, namespace, _root=False):
-        self = super().__new__(cls, name, bases, namespace, _root=_root)
-        return self
+    Note that all the above statements are true from the point of view of
+    static type checkers. At runtime, Any should not be used with instance
+    or class checks.
+    """
+
+    __slots__ = ()
 
     def __instancecheck__(self, obj):
         raise TypeError("Any cannot be used with isinstance().")
 
     def __subclasscheck__(self, cls):
-        if not isinstance(cls, type):
-            return super().__subclasscheck__(cls)  # To TypeError.
-        return True
+        raise TypeError("Any cannot be used with issubclass().")
 
 
-class Any(Final, metaclass=AnyMeta, _root=True):
-    """Special type indicating an unconstrained type.
+Any = _Any(_root=True)
 
-    - Any object is an instance of Any.
-    - Any class is a subclass of Any.
-    - As a special case, Any and object are subclasses of each other.
-    """
-
-    __slots__ = ()
 
-
-class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
+class TypeVar(_TypingBase, _root=True):
     """Type variable.
 
     Usage::
@@ -370,7 +418,7 @@ class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
     as for generic function definitions.  See class Generic for more
     information on generic types.  Generic functions work as follows:
 
-      def repeat(x: T, n: int) -> Sequence[T]:
+      def repeat(x: T, n: int) -> List[T]:
           '''Return a list containing n references to x.'''
           return [x]*n
 
@@ -383,14 +431,12 @@ class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
     that if the arguments are instances of some subclass of str,
     the return type is still plain str.
 
-    At runtime, isinstance(x, T) will raise TypeError.  However,
-    issubclass(C, T) is true for any class C, and issubclass(str, A)
-    and issubclass(bytes, A) are true, and issubclass(int, A) is
-    false.  (TODO: Why is this needed?  This may change.  See #136.)
+    At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
 
-    Type variables may be marked covariant or contravariant by passing
-    covariant=True or contravariant=True.  See PEP 484 for more
-    details.  By default type variables are invariant.
+    Type variables defined with covariant=True or contravariant=True
+    can be used do declare covariant or contravariant generic types.
+    See PEP 484 for more details. By default generic types are invariant
+    in all type variables.
 
     Type variables can be introspected. e.g.:
 
@@ -401,11 +447,16 @@ class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
       A.__constraints__ == (str, bytes)
     """
 
-    def __new__(cls, name, *constraints, bound=None,
+    __slots__ = ('__name__', '__bound__', '__constraints__',
+                 '__covariant__', '__contravariant__')
+
+    def __init__(self, name, *constraints, bound=None,
                 covariant=False, contravariant=False):
-        self = super().__new__(cls, name, (Final,), {}, _root=True)
+        super().__init__(name, *constraints, bound=bound,
+                         covariant=covariant, contravariant=contravariant)
+        self.__name__ = name
         if covariant and contravariant:
-            raise ValueError("Bivariant type variables are not supported.")
+            raise ValueError("Bivariant types are not supported.")
         self.__covariant__ = bool(covariant)
         self.__contravariant__ = bool(contravariant)
         if constraints and bound is not None:
@@ -418,7 +469,6 @@ class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
             self.__bound__ = _type_check(bound, "Bound must be a type.")
         else:
             self.__bound__ = None
-        return self
 
     def _get_type_vars(self, tvars):
         if self not in tvars:
@@ -437,16 +487,7 @@ class TypeVar(TypingMeta, metaclass=TypingMeta, _root=True):
         raise TypeError("Type variables cannot be used with isinstance().")
 
     def __subclasscheck__(self, cls):
-        # TODO: Make this raise TypeError too?
-        if cls is self:
-            return True
-        if cls is Any:
-            return True
-        if self.__bound__ is not None:
-            return issubclass(cls, self.__bound__)
-        if self.__constraints__:
-            return any(issubclass(cls, c) for c in self.__constraints__)
-        return True
+        raise TypeError("Type variables cannot be used with issubclass().")
 
 
 # Some unconstrained type variables.  These are used by the container types.
@@ -464,124 +505,129 @@ T_contra = TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
 AnyStr = TypeVar('AnyStr', bytes, str)
 
 
-class UnionMeta(TypingMeta):
-    """Metaclass for Union."""
-
-    def __new__(cls, name, bases, namespace, parameters=None, _root=False):
-        if parameters is None:
-            return super().__new__(cls, name, bases, namespace, _root=_root)
-        if not isinstance(parameters, tuple):
-            raise TypeError("Expected parameters=<tuple>")
-        # Flatten out Union[Union[...], ...] and type-check non-Union args.
-        params = []
-        msg = "Union[arg, ...]: each arg must be a type."
-        for p in parameters:
-            if isinstance(p, UnionMeta):
-                params.extend(p.__union_params__)
-            else:
-                params.append(_type_check(p, msg))
-        # Weed out strict duplicates, preserving the first of each occurrence.
-        all_params = set(params)
-        if len(all_params) < len(params):
-            new_params = []
-            for t in params:
-                if t in all_params:
-                    new_params.append(t)
-                    all_params.remove(t)
-            params = new_params
-            assert not all_params, all_params
-        # Weed out subclasses.
-        # E.g. Union[int, Employee, Manager] == Union[int, Employee].
-        # If Any or object is present it will be the sole survivor.
-        # If both Any and object are present, Any wins.
-        # Never discard type variables, except against Any.
-        # (In particular, Union[str, AnyStr] != AnyStr.)
-        all_params = set(params)
-        for t1 in params:
-            if t1 is Any:
-                return Any
-            if isinstance(t1, TypeVar):
-                continue
-            if isinstance(t1, _TypeAlias):
-                # _TypeAlias is not a real class.
-                continue
-            if not isinstance(t1, type):
-                assert callable(t1)  # A callable might sneak through.
-                continue
-            if any(isinstance(t2, type) and issubclass(t1, t2)
-                   for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
-                all_params.remove(t1)
-        # It's not a union if there's only one type left.
-        if len(all_params) == 1:
-            return all_params.pop()
-        # Create a new class with these params.
-        self = super().__new__(cls, name, bases, {}, _root=True)
-        self.__union_params__ = tuple(t for t in params if t in all_params)
-        self.__union_set_params__ = frozenset(self.__union_params__)
-        return self
-
-    def _eval_type(self, globalns, localns):
-        p = tuple(_eval_type(t, globalns, localns)
-                  for t in self.__union_params__)
-        if p == self.__union_params__:
-            return self
-        else:
-            return self.__class__(self.__name__, self.__bases__, {},
-                                  p, _root=True)
-
-    def _get_type_vars(self, tvars):
-        if self.__union_params__:
-            _get_type_vars(self.__union_params__, tvars)
+def _replace_arg(arg, tvars, args):
+    """An internal helper function: replace arg if it is a type variable
+    found in tvars with corresponding substitution from args or
+    with corresponding substitution sub-tree if arg is a generic type.
+    """
 
-    def __repr__(self):
-        r = super().__repr__()
-        if self.__union_params__:
-            r += '[%s]' % (', '.join(_type_repr(t)
-                                     for t in self.__union_params__))
-        return r
+    if tvars is None:
+        tvars = []
+    if hasattr(arg, '_subs_tree'):
+        return arg._subs_tree(tvars, args)
+    if isinstance(arg, TypeVar):
+        for i, tvar in enumerate(tvars):
+            if arg == tvar:
+                return args[i]
+    return arg
 
-    def __getitem__(self, parameters):
-        if self.__union_params__ is not None:
-            raise TypeError(
-                "Cannot subscript an existing Union. Use Union[u, t] instead.")
-        if parameters == ():
-            raise TypeError("Cannot take a Union of no types.")
-        if not isinstance(parameters, tuple):
-            parameters = (parameters,)
-        return self.__class__(self.__name__, self.__bases__,
-                              dict(self.__dict__), parameters, _root=True)
 
-    def __eq__(self, other):
-        if not isinstance(other, UnionMeta):
-            return NotImplemented
-        return self.__union_set_params__ == other.__union_set_params__
+def _subs_tree(cls, tvars=None, args=None):
+    """An internal helper function: calculate substitution tree
+    for generic cls after replacing its type parameters with
+    substitutions in tvars -> args (if any).
+    Repeat the same following __origin__'s.
 
-    def __hash__(self):
-        return hash(self.__union_set_params__)
+    Return a list of arguments with all possible substitutions
+    performed. Arguments that are generic classes themselves are represented
+    as tuples (so that no new classes are created by this function).
+    For example: _subs_tree(List[Tuple[int, T]][str]) == [(Tuple, int, str)]
+    """
 
-    def __instancecheck__(self, obj):
-        raise TypeError("Unions cannot be used with isinstance().")
+    if cls.__origin__ is None:
+        return cls
+    # Make of chain of origins (i.e. cls -> cls.__origin__)
+    current = cls.__origin__
+    orig_chain = []
+    while current.__origin__ is not None:
+        orig_chain.append(current)
+        current = current.__origin__
+    # Replace type variables in __args__ if asked ...
+    tree_args = []
+    for arg in cls.__args__:
+        tree_args.append(_replace_arg(arg, tvars, args))
+    # ... then continue replacing down the origin chain.
+    for ocls in orig_chain:
+        new_tree_args = []
+        for i, arg in enumerate(ocls.__args__):
+            new_tree_args.append(_replace_arg(arg, ocls.__parameters__, tree_args))
+        tree_args = new_tree_args
+    return tree_args
+
+
+def _remove_dups_flatten(parameters):
+    """An internal helper for Union creation and substitution: flatten Union's
+    among parameters, then remove duplicates and strict subclasses.
+    """
 
-    def __subclasscheck__(self, cls):
-        if cls is Any:
-            return True
-        if self.__union_params__ is None:
-            return isinstance(cls, UnionMeta)
-        elif isinstance(cls, UnionMeta):
-            if cls.__union_params__ is None:
-                return False
-            return all(issubclass(c, self) for c in (cls.__union_params__))
-        elif isinstance(cls, TypeVar):
-            if cls in self.__union_params__:
-                return True
-            if cls.__constraints__:
-                return issubclass(Union[cls.__constraints__], self)
-            return False
+    # Flatten out Union[Union[...], ...].
+    params = []
+    for p in parameters:
+        if isinstance(p, _Union) and p.__origin__ is Union:
+            params.extend(p.__args__)
+        elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
+            params.extend(p[1:])
         else:
-            return any(issubclass(cls, t) for t in self.__union_params__)
+            params.append(p)
+    # Weed out strict duplicates, preserving the first of each occurrence.
+    all_params = set(params)
+    if len(all_params) < len(params):
+        new_params = []
+        for t in params:
+            if t in all_params:
+                new_params.append(t)
+                all_params.remove(t)
+        params = new_params
+        assert not all_params, all_params
+    # Weed out subclasses.
+    # E.g. Union[int, Employee, Manager] == Union[int, Employee].
+    # If object is present it will be sole survivor among proper classes.
+    # Never discard type variables.
+    # (In particular, Union[str, AnyStr] != AnyStr.)
+    all_params = set(params)
+    for t1 in params:
+        if not isinstance(t1, type):
+            continue
+        if any(isinstance(t2, type) and issubclass(t1, t2)
+               for t2 in all_params - {t1}
+               if not (isinstance(t2, GenericMeta) and
+                       t2.__origin__ is not None)):
+            all_params.remove(t1)
+    return tuple(t for t in params if t in all_params)
+
+
+def _check_generic(cls, parameters):
+    # Check correct count for parameters of a generic cls (internal helper).
+    if not cls.__parameters__:
+        raise TypeError("%s is not a generic class" % repr(cls))
+    alen = len(parameters)
+    elen = len(cls.__parameters__)
+    if alen != elen:
+        raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
+                        ("many" if alen > elen else "few", repr(cls), alen, elen))
+
+
+_cleanups = []
+
+
+def _tp_cache(func):
+    """Internal wrapper caching __getitem__ of generic types with a fallback to
+    original function for non-hashable arguments.
+    """
+
+    cached = functools.lru_cache()(func)
+    _cleanups.append(cached.cache_clear)
+    @functools.wraps(func)
+    def inner(*args, **kwds):
+        try:
+            return cached(*args, **kwds)
+        except TypeError:
+            pass  # All real errors (not unhashable args) are raised below.
+        return func(*args, **kwds)
+    return inner
 
 
-class Union(Final, metaclass=UnionMeta, _root=True):
+class _Union(_FinalTypingBase, _root=True):
     """Union type; Union[X, Y] means either X or Y.
 
     To define a union, use e.g. Union[int, str].  Details:
@@ -616,256 +662,136 @@ class Union(Final, metaclass=UnionMeta, _root=True):
         Union[Manager, int, Employee] == Union[int, Employee]
         Union[Employee, Manager] == Employee
 
-    - Corollary: if Any is present it is the sole survivor, e.g.::
-
-        Union[int, Any] == Any
-
     - Similar for object::
 
         Union[int, object] == object
 
-    - To cut a tie: Union[object, Any] == Union[Any, object] == Any.
-
     - You cannot subclass or instantiate a union.
 
-    - You cannot write Union[X][Y] (what would it mean?).
-
     - You can use Optional[X] as a shorthand for Union[X, None].
     """
 
-    # Unsubscripted Union type has params set to None.
-    __union_params__ = None
-    __union_set_params__ = None
-
-
-class OptionalMeta(TypingMeta):
-    """Metaclass for Optional."""
-
-    def __new__(cls, name, bases, namespace, _root=False):
-        return super().__new__(cls, name, bases, namespace, _root=_root)
-
-    def __getitem__(self, arg):
-        arg = _type_check(arg, "Optional[t] requires a single type.")
-        return Union[arg, type(None)]
-
-
-class Optional(Final, metaclass=OptionalMeta, _root=True):
-    """Optional type.
-
-    Optional[X] is equivalent to Union[X, type(None)].
-    """
-
-    __slots__ = ()
-
+    __slots__ = ('__parameters__', '__args__', '__origin__', '__tree_hash__')
 
-class TupleMeta(TypingMeta):
-    """Metaclass for Tuple."""
-
-    def __new__(cls, name, bases, namespace, parameters=None,
-                use_ellipsis=False, _root=False):
-        self = super().__new__(cls, name, bases, namespace, _root=_root)
-        self.__tuple_params__ = parameters
-        self.__tuple_use_ellipsis__ = use_ellipsis
+    def __new__(cls, parameters=None, origin=None, *args, _root=False):
+        self = super().__new__(cls, parameters, origin, *args, _root=_root)
+        if origin is None:
+            self.__parameters__ = None
+            self.__args__ = None
+            self.__origin__ = None
+            self.__tree_hash__ = hash(frozenset(('Union',)))
+            return self
+        if not isinstance(parameters, tuple):
+            raise TypeError("Expected parameters=<tuple>")
+        if origin is Union:
+            parameters = _remove_dups_flatten(parameters)
+            # It's not a union if there's only one type left.
+            if len(parameters) == 1:
+                return parameters[0]
+        self.__parameters__ = _type_vars(parameters)
+        self.__args__ = parameters
+        self.__origin__ = origin
+        # Pre-calculate the __hash__ on instantiation.
+        # This improves speed for complex substitutions.
+        subs_tree = self._subs_tree()
+        if isinstance(subs_tree, tuple):
+            self.__tree_hash__ = hash(frozenset(subs_tree))
+        else:
+            self.__tree_hash__ = hash(subs_tree)
         return self
 
-    def _get_type_vars(self, tvars):
-        if self.__tuple_params__:
-            _get_type_vars(self.__tuple_params__, tvars)
-
     def _eval_type(self, globalns, localns):
-        tp = self.__tuple_params__
-        if tp is None:
+        if self.__args__ is None:
             return self
-        p = tuple(_eval_type(t, globalns, localns) for t in tp)
-        if p == self.__tuple_params__:
+        ev_args = tuple(_eval_type(t, globalns, localns) for t in self.__args__)
+        ev_origin = _eval_type(self.__origin__, globalns, localns)
+        if ev_args == self.__args__ and ev_origin == self.__origin__:
+            # Everything is already evaluated.
             return self
-        else:
-            return self.__class__(self.__name__, self.__bases__, {},
-                                  p, _root=True)
+        return self.__class__(ev_args, ev_origin, _root=True)
+
+    def _get_type_vars(self, tvars):
+        if self.__origin__ and self.__parameters__:
+            _get_type_vars(self.__parameters__, tvars)
 
     def __repr__(self):
-        r = super().__repr__()
-        if self.__tuple_params__ is not None:
-            params = [_type_repr(p) for p in self.__tuple_params__]
-            if self.__tuple_use_ellipsis__:
-                params.append('...')
-            if not params:
-                params.append('()')
-            r += '[%s]' % (
-                ', '.join(params))
-        return r
+        if self.__origin__ is None:
+            return super().__repr__()
+        tree = self._subs_tree()
+        if not isinstance(tree, tuple):
+            return repr(tree)
+        return tree[0]._tree_repr(tree)
+
+    def _tree_repr(self, tree):
+        arg_list = []
+        for arg in tree[1:]:
+            if not isinstance(arg, tuple):
+                arg_list.append(_type_repr(arg))
+            else:
+                arg_list.append(arg[0]._tree_repr(arg))
+        return super().__repr__() + '[%s]' % ', '.join(arg_list)
 
+    @_tp_cache
     def __getitem__(self, parameters):
-        if self.__tuple_params__ is not None:
-            raise TypeError("Cannot re-parameterize %r" % (self,))
+        if parameters == ():
+            raise TypeError("Cannot take a Union of no types.")
         if not isinstance(parameters, tuple):
             parameters = (parameters,)
-        if len(parameters) == 2 and parameters[1] == Ellipsis:
-            parameters = parameters[:1]
-            use_ellipsis = True
-            msg = "Tuple[t, ...]: t must be a type."
+        if self.__origin__ is None:
+            msg = "Union[arg, ...]: each arg must be a type."
         else:
-            use_ellipsis = False
-            msg = "Tuple[t0, t1, ...]: each t must be a type."
+            msg = "Parameters to generic types must be types."
         parameters = tuple(_type_check(p, msg) for p in parameters)
-        return self.__class__(self.__name__, self.__bases__,
-                              dict(self.__dict__), parameters,
-                              use_ellipsis=use_ellipsis, _root=True)
+        if self is not Union:
+            _check_generic(self, parameters)
+        return self.__class__(parameters, origin=self, _root=True)
+
+    def _subs_tree(self, tvars=None, args=None):
+        if self is Union:
+            return Union  # Nothing to substitute
+        tree_args = _subs_tree(self, tvars, args)
+        tree_args = _remove_dups_flatten(tree_args)
+        if len(tree_args) == 1:
+            return tree_args[0]  # Union of a single type is that type
+        return (Union,) + tree_args
 
     def __eq__(self, other):
-        if not isinstance(other, TupleMeta):
-            return NotImplemented
-        return (self.__tuple_params__ == other.__tuple_params__ and
-                self.__tuple_use_ellipsis__ == other.__tuple_use_ellipsis__)
+        if not isinstance(other, _Union):
+            return self._subs_tree() == other
+        return self.__tree_hash__ == other.__tree_hash__
 
     def __hash__(self):
-        return hash(self.__tuple_params__)
+        return self.__tree_hash__
 
     def __instancecheck__(self, obj):
-        raise TypeError("Tuples cannot be used with isinstance().")
+        raise TypeError("Unions cannot be used with isinstance().")
 
     def __subclasscheck__(self, cls):
-        if cls is Any:
-            return True
-        if not isinstance(cls, type):
-            return super().__subclasscheck__(cls)  # To TypeError.
-        if issubclass(cls, tuple):
-            return True  # Special case.
-        if not isinstance(cls, TupleMeta):
-            return super().__subclasscheck__(cls)  # False.
-        if self.__tuple_params__ is None:
-            return True
-        if cls.__tuple_params__ is None:
-            return False  # ???
-        if cls.__tuple_use_ellipsis__ != self.__tuple_use_ellipsis__:
-            return False
-        # Covariance.
-        return (len(self.__tuple_params__) == len(cls.__tuple_params__) and
-                all(issubclass(x, p)
-                    for x, p in zip(cls.__tuple_params__,
-                                    self.__tuple_params__)))
-
-
-class Tuple(Final, metaclass=TupleMeta, _root=True):
-    """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
-
-    Example: Tuple[T1, T2] is a tuple of two elements corresponding
-    to type variables T1 and T2.  Tuple[int, float, str] is a tuple
-    of an int, a float and a string.
-
-    To specify a variable-length tuple of homogeneous type, use Sequence[T].
-    """
-
-    __slots__ = ()
-
-
-class CallableMeta(TypingMeta):
-    """Metaclass for Callable."""
+        raise TypeError("Unions cannot be used with issubclass().")
 
-    def __new__(cls, name, bases, namespace, _root=False,
-                args=None, result=None):
-        if args is None and result is None:
-            pass  # Must be 'class Callable'.
-        else:
-            if args is not Ellipsis:
-                if not isinstance(args, list):
-                    raise TypeError("Callable[args, result]: "
-                                    "args must be a list."
-                                    " Got %.100r." % (args,))
-                msg = "Callable[[arg, ...], result]: each arg must be a type."
-                args = tuple(_type_check(arg, msg) for arg in args)
-            msg = "Callable[args, result]: result must be a type."
-            result = _type_check(result, msg)
-        self = super().__new__(cls, name, bases, namespace, _root=_root)
-        self.__args__ = args
-        self.__result__ = result
-        return self
 
-    def _get_type_vars(self, tvars):
-        if self.__args__:
-            _get_type_vars(self.__args__, tvars)
+Union = _Union(_root=True)
 
-    def _eval_type(self, globalns, localns):
-        if self.__args__ is None and self.__result__ is None:
-            return self
-        if self.__args__ is Ellipsis:
-            args = self.__args__
-        else:
-            args = [_eval_type(t, globalns, localns) for t in self.__args__]
-        result = _eval_type(self.__result__, globalns, localns)
-        if args == self.__args__ and result == self.__result__:
-            return self
-        else:
-            return self.__class__(self.__name__, self.__bases__, {},
-                                  args=args, result=result, _root=True)
-
-    def __repr__(self):
-        r = super().__repr__()
-        if self.__args__ is not None or self.__result__ is not None:
-            if self.__args__ is Ellipsis:
-                args_r = '...'
-            else:
-                args_r = '[%s]' % ', '.join(_type_repr(t)
-                                            for t in self.__args__)
-            r += '[%s, %s]' % (args_r, _type_repr(self.__result__))
-        return r
 
-    def __getitem__(self, parameters):
-        if self.__args__ is not None or self.__result__ is not None:
-            raise TypeError("This Callable type is already parameterized.")
-        if not isinstance(parameters, tuple) or len(parameters) != 2:
-            raise TypeError(
-                "Callable must be used as Callable[[arg, ...], result].")
-        args, result = parameters
-        return self.__class__(self.__name__, self.__bases__,
-                              dict(self.__dict__), _root=True,
-                              args=args, result=result)
-
-    def __eq__(self, other):
-        if not isinstance(other, CallableMeta):
-            return NotImplemented
-        return (self.__args__ == other.__args__ and
-                self.__result__ == other.__result__)
-
-    def __hash__(self):
-        return hash(self.__args__) ^ hash(self.__result__)
-
-    def __instancecheck__(self, obj):
-        # For unparametrized Callable we allow this, because
-        # typing.Callable should be equivalent to
-        # collections.abc.Callable.
-        if self.__args__ is None and self.__result__ is None:
-            return isinstance(obj, collections_abc.Callable)
-        else:
-            raise TypeError("Callable[] cannot be used with isinstance().")
-
-    def __subclasscheck__(self, cls):
-        if cls is Any:
-            return True
-        if not isinstance(cls, CallableMeta):
-            return super().__subclasscheck__(cls)
-        if self.__args__ is None and self.__result__ is None:
-            return True
-        # We're not doing covariance or contravariance -- this is *invariance*.
-        return self == cls
+class _Optional(_FinalTypingBase, _root=True):
+    """Optional type.
 
+    Optional[X] is equivalent to Union[X, None].
+    """
 
-class Callable(Final, metaclass=CallableMeta, _root=True):
-    """Callable type; Callable[[int], str] is a function of (int) -> str.
+    __slots__ = ()
 
-    The subscription syntax must always be used with exactly two
-    values: the argument list and the return type.  The argument list
-    must be a list of types; the return type must be a single type.
+    @_tp_cache
+    def __getitem__(self, arg):
+        arg = _type_check(arg, "Optional[t] requires a single type.")
+        return Union[arg, type(None)]
 
-    There is no syntax to indicate optional or keyword arguments,
-    such function types are rarely used as callback types.
-    """
 
-    __slots__ = ()
+Optional = _Optional(_root=True)
 
 
 def _gorg(a):
-    """Return the farthest origin of a generic class."""
+    """Return the farthest origin of a generic class (internal helper)."""
     assert isinstance(a, GenericMeta)
     while a.__origin__ is not None:
         a = a.__origin__
@@ -873,10 +799,10 @@ def _gorg(a):
 
 
 def _geqv(a, b):
-    """Return whether two generic classes are equivalent.
+    """Return whether two generic classes are equivalent (internal helper).
 
     The intention is to consider generic class X and any of its
-    parameterized forms (X[T], X[int], etc.)  as equivalent.
+    parameterized forms (X[T], X[int], etc.) as equivalent.
 
     However, X is not equivalent to a subclass of X.
 
@@ -901,13 +827,65 @@ def _next_in_mro(cls):
     return next_in_mro
 
 
+def _valid_for_check(cls):
+    """An internal helper to prohibit isinstance([1], List[str]) etc."""
+    if cls is Generic:
+        raise TypeError("Class %r cannot be used with class "
+                        "or instance checks" % cls)
+    if (cls.__origin__ is not None and
+        sys._getframe(3).f_globals['__name__'] not in ['abc', 'functools']):
+        raise TypeError("Parameterized generics cannot be used with class "
+                        "or instance checks")
+
+
+def _make_subclasshook(cls):
+    """Construct a __subclasshook__ callable that incorporates
+    the associated __extra__ class in subclass checks performed
+    against cls.
+    """
+    if isinstance(cls.__extra__, abc.ABCMeta):
+        # The logic mirrors that of ABCMeta.__subclasscheck__.
+        # Registered classes need not be checked here because
+        # cls and its extra share the same _abc_registry.
+        def __extrahook__(subclass):
+            _valid_for_check(cls)
+            res = cls.__extra__.__subclasshook__(subclass)
+            if res is not NotImplemented:
+                return res
+            if cls.__extra__ in subclass.__mro__:
+                return True
+            for scls in cls.__extra__.__subclasses__():
+                if isinstance(scls, GenericMeta):
+                    continue
+                if issubclass(subclass, scls):
+                    return True
+            return NotImplemented
+    else:
+        # For non-ABC extras we'll just call issubclass().
+        def __extrahook__(subclass):
+            _valid_for_check(cls)
+            if cls.__extra__ and issubclass(subclass, cls.__extra__):
+                return True
+            return NotImplemented
+    return __extrahook__
+
+
+def _no_slots_copy(dct):
+    """Internal helper: copy class __dict__ and clean slots class variables.
+    (They will be re-created if necessary by normal class machinery.)
+    """
+    dict_copy = dict(dct)
+    if '__slots__' in dict_copy:
+        for slot in dict_copy['__slots__']:
+            dict_copy.pop(slot, None)
+    return dict_copy
+
+
 class GenericMeta(TypingMeta, abc.ABCMeta):
     """Metaclass for generic types."""
 
     def __new__(cls, name, bases, namespace,
-                tvars=None, args=None, origin=None, extra=None):
-        self = super().__new__(cls, name, bases, namespace, _root=True)
-
+                tvars=None, args=None, origin=None, extra=None, orig_bases=None):
         if tvars is not None:
             # Called from __getitem__() below.
             assert origin is not None
@@ -948,48 +926,102 @@ class GenericMeta(TypingMeta, abc.ABCMeta):
                          ", ".join(str(g) for g in gvars)))
                 tvars = gvars
 
+        initial_bases = bases
+        if extra is not None and type(extra) is abc.ABCMeta and extra not in bases:
+            bases = (extra,) + bases
+        bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b for b in bases)
+
+        # remove bare Generic from bases if there are other generic bases
+        if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
+            bases = tuple(b for b in bases if b is not Generic)
+        self = super().__new__(cls, name, bases, namespace, _root=True)
+
         self.__parameters__ = tvars
-        self.__args__ = args
+        # Be prepared that GenericMeta will be subclassed by TupleMeta
+        # and CallableMeta, those two allow ..., (), or [] in __args___.
+        self.__args__ = tuple(... if a is _TypingEllipsis else
+                              () if a is _TypingEmpty else
+                              a for a in args) if args else None
         self.__origin__ = origin
         self.__extra__ = extra
         # Speed hack (https://github.com/python/typing/issues/196).
         self.__next_in_mro__ = _next_in_mro(self)
+        # Preserve base classes on subclassing (__bases__ are type erased now).
+        if orig_bases is None:
+            self.__orig_bases__ = initial_bases
+
+        # This allows unparameterized generic collections to be used
+        # with issubclass() and isinstance() in the same way as their
+        # collections.abc counterparts (e.g., isinstance([], Iterable)).
+        if ('__subclasshook__' not in namespace and extra  # allow overriding
+            or hasattr(self.__subclasshook__, '__name__') and
+            self.__subclasshook__.__name__ == '__extrahook__'):
+            self.__subclasshook__ = _make_subclasshook(self)
+        if isinstance(extra, abc.ABCMeta):
+            self._abc_registry = extra._abc_registry
+
+        if origin and hasattr(origin, '__qualname__'):  # Fix for Python 3.2.
+            self.__qualname__ = origin.__qualname__
+        self.__tree_hash__ = hash(self._subs_tree()) if origin else hash((self.__name__,))
         return self
 
     def _get_type_vars(self, tvars):
         if self.__origin__ and self.__parameters__:
             _get_type_vars(self.__parameters__, tvars)
 
+    def _eval_type(self, globalns, localns):
+        ev_origin = (self.__origin__._eval_type(globalns, localns)
+                     if self.__origin__ else None)
+        ev_args = tuple(_eval_type(a, globalns, localns) for a
+                        in self.__args__) if self.__args__ else None
+        if ev_origin == self.__origin__ and ev_args == self.__args__:
+            return self
+        return self.__class__(self.__name__,
+                              self.__bases__,
+                              _no_slots_copy(self.__dict__),
+                              tvars=_type_vars(ev_args) if ev_args else None,
+                              args=ev_args,
+                              origin=ev_origin,
+                              extra=self.__extra__,
+                              orig_bases=self.__orig_bases__)
+
     def __repr__(self):
-        if self.__origin__ is not None:
-            r = repr(self.__origin__)
-        else:
-            r = super().__repr__()
-        if self.__args__:
-            r += '[%s]' % (
-                ', '.join(_type_repr(p) for p in self.__args__))
-        if self.__parameters__:
-            r += '<%s>' % (
-                ', '.join(_type_repr(p) for p in self.__parameters__))
-        return r
+        if self.__origin__ is None:
+            return super().__repr__()
+        return self._tree_repr(self._subs_tree())
+
+    def _tree_repr(self, tree):
+        arg_list = []
+        for arg in tree[1:]:
+            if arg == ():
+                arg_list.append('()')
+            elif not isinstance(arg, tuple):
+                arg_list.append(_type_repr(arg))
+            else:
+                arg_list.append(arg[0]._tree_repr(arg))
+        return super().__repr__() + '[%s]' % ', '.join(arg_list)
+
+    def _subs_tree(self, tvars=None, args=None):
+        if self.__origin__ is None:
+            return self
+        tree_args = _subs_tree(self, tvars, args)
+        return (_gorg(self),) + tuple(tree_args)
 
     def __eq__(self, other):
         if not isinstance(other, GenericMeta):
             return NotImplemented
-        if self.__origin__ is not None:
-            return (self.__origin__ is other.__origin__ and
-                    self.__args__ == other.__args__ and
-                    self.__parameters__ == other.__parameters__)
-        else:
+        if self.__origin__ is None or other.__origin__ is None:
             return self is other
+        return self.__tree_hash__ == other.__tree_hash__
 
     def __hash__(self):
-        return hash((self.__name__, self.__parameters__))
+        return self.__tree_hash__
 
+    @_tp_cache
     def __getitem__(self, params):
         if not isinstance(params, tuple):
             params = (params,)
-        if not params:
+        if not params and not _gorg(self) is Tuple:
             raise TypeError(
                 "Parameter list to %s[...] cannot be empty" % _qualname(self))
         msg = "Parameters to generic types must be types."
@@ -1003,34 +1035,31 @@ class GenericMeta(TypingMeta, abc.ABCMeta):
                 raise TypeError(
                     "Parameters to Generic[...] must all be unique")
             tvars = params
-            args = None
+            args = params
+        elif self in (Tuple, Callable):
+            tvars = _type_vars(params)
+            args = params
         elif self is _Protocol:
             # _Protocol is internal, don't check anything.
             tvars = params
-            args = None
+            args = params
         elif self.__origin__ in (Generic, _Protocol):
             # Can't subscript Generic[...] or _Protocol[...].
             raise TypeError("Cannot subscript already-subscripted %s" %
                             repr(self))
         else:
             # Subscripting a regular Generic subclass.
-            if not self.__parameters__:
-                raise TypeError("%s is not a generic class" % repr(self))
-            alen = len(params)
-            elen = len(self.__parameters__)
-            if alen != elen:
-                raise TypeError(
-                    "Too %s parameters for %s; actual %s, expected %s" %
-                    ("many" if alen > elen else "few", repr(self), alen, elen))
+            _check_generic(self, params)
             tvars = _type_vars(params)
             args = params
         return self.__class__(self.__name__,
-                              (self,) + self.__bases__,
-                              dict(self.__dict__),
+                              self.__bases__,
+                              _no_slots_copy(self.__dict__),
                               tvars=tvars,
                               args=args,
                               origin=self,
-                              extra=self.__extra__)
+                              extra=self.__extra__,
+                              orig_bases=self.__orig_bases__)
 
     def __instancecheck__(self, instance):
         # Since we extend ABC.__subclasscheck__ and
@@ -1038,58 +1067,40 @@ class GenericMeta(TypingMeta, abc.ABCMeta):
         # latter, we must extend __instancecheck__ too. For simplicity
         # we just skip the cache check -- instance checks for generic
         # classes are supposed to be rare anyways.
-        return self.__subclasscheck__(instance.__class__)
+        return issubclass(instance.__class__, self)
 
-    def __subclasscheck__(self, cls):
-        if cls is Any:
-            return True
-        if isinstance(cls, GenericMeta):
-            # For a class C(Generic[T]) where T is co-variant,
-            # C[X] is a subclass of C[Y] iff X is a subclass of Y.
-            origin = self.__origin__
-            if origin is not None and origin is cls.__origin__:
-                assert len(self.__args__) == len(origin.__parameters__)
-                assert len(cls.__args__) == len(origin.__parameters__)
-                for p_self, p_cls, p_origin in zip(self.__args__,
-                                                   cls.__args__,
-                                                   origin.__parameters__):
-                    if isinstance(p_origin, TypeVar):
-                        if p_origin.__covariant__:
-                            # Covariant -- p_cls must be a subclass of p_self.
-                            if not issubclass(p_cls, p_self):
-                                break
-                        elif p_origin.__contravariant__:
-                            # Contravariant.  I think it's the opposite. :-)
-                            if not issubclass(p_self, p_cls):
-                                break
-                        else:
-                            # Invariant -- p_cls and p_self must equal.
-                            if p_self != p_cls:
-                                break
-                    else:
-                        # If the origin's parameter is not a typevar,
-                        # insist on invariance.
-                        if p_self != p_cls:
-                            break
-                else:
-                    return True
-                # If we break out of the loop, the superclass gets a chance.
-        if super().__subclasscheck__(cls):
-            return True
-        if self.__extra__ is None or isinstance(cls, GenericMeta):
-            return False
-        return issubclass(cls, self.__extra__)
+    def __copy__(self):
+        return self.__class__(self.__name__, self.__bases__,
+                              _no_slots_copy(self.__dict__),
+                              self.__parameters__, self.__args__, self.__origin__,
+                              self.__extra__, self.__orig_bases__)
 
 
 # Prevent checks for Generic to crash when defining Generic.
 Generic = None
 
 
+def _generic_new(base_cls, cls, *args, **kwds):
+    # Assure type is erased on instantiation,
+    # but attempt to store it in __orig_class__
+    if cls.__origin__ is None:
+        return base_cls.__new__(cls)
+    else:
+        origin = _gorg(cls)
+        obj = base_cls.__new__(origin)
+        try:
+            obj.__orig_class__ = cls
+        except AttributeError:
+            pass
+        obj.__init__(*args, **kwds)
+        return obj
+
+
 class Generic(metaclass=GenericMeta):
     """Abstract base class for generic types.
 
-    A generic type is typically declared by inheriting from an
-    instantiation of this class with one or more type variables.
+    A generic type is typically declared by inheriting from
+    this class parameterized with one or more type variables.
     For example, a generic mapping type might be defined as::
 
       class Mapping(Generic[KT, VT]):
@@ -1109,13 +1120,208 @@ class Generic(metaclass=GenericMeta):
     __slots__ = ()
 
     def __new__(cls, *args, **kwds):
-        if cls.__origin__ is None:
-            return cls.__next_in_mro__.__new__(cls)
+        if _geqv(cls, Generic):
+            raise TypeError("Type Generic cannot be instantiated; "
+                            "it can be used only as a base class")
+        return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
+
+
+class _TypingEmpty:
+    """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
+    to allow empty list/tuple in specific places, without allowing them
+    to sneak in where prohibited.
+    """
+
+
+class _TypingEllipsis:
+    """Internal placeholder for ... (ellipsis)."""
+
+
+class TupleMeta(GenericMeta):
+    """Metaclass for Tuple (internal)."""
+
+    @_tp_cache
+    def __getitem__(self, parameters):
+        if self.__origin__ is not None or not _geqv(self, Tuple):
+            # Normal generic rules apply if this is not the first subscription
+            # or a subscription of a subclass.
+            return super().__getitem__(parameters)
+        if parameters == ():
+            return super().__getitem__((_TypingEmpty,))
+        if not isinstance(parameters, tuple):
+            parameters = (parameters,)
+        if len(parameters) == 2 and parameters[1] is ...:
+            msg = "Tuple[t, ...]: t must be a type."
+            p = _type_check(parameters[0], msg)
+            return super().__getitem__((p, _TypingEllipsis))
+        msg = "Tuple[t0, t1, ...]: each t must be a type."
+        parameters = tuple(_type_check(p, msg) for p in parameters)
+        return super().__getitem__(parameters)
+
+    def __instancecheck__(self, obj):
+        if self.__args__ == None:
+            return isinstance(obj, tuple)
+        raise TypeError("Parameterized Tuple cannot be used "
+                        "with isinstance().")
+
+    def __subclasscheck__(self, cls):
+        if self.__args__ == None:
+            return issubclass(cls, tuple)
+        raise TypeError("Parameterized Tuple cannot be used "
+                        "with issubclass().")
+
+
+class Tuple(tuple, extra=tuple, metaclass=TupleMeta):
+    """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
+
+    Example: Tuple[T1, T2] is a tuple of two elements corresponding
+    to type variables T1 and T2.  Tuple[int, float, str] is a tuple
+    of an int, a float and a string.
+
+    To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
+    """
+
+    __slots__ = ()
+
+    def __new__(cls, *args, **kwds):
+        if _geqv(cls, Tuple):
+            raise TypeError("Type Tuple cannot be instantiated; "
+                            "use tuple() instead")
+        return _generic_new(tuple, cls, *args, **kwds)
+
+
+class CallableMeta(GenericMeta):
+    """Metaclass for Callable (internal)."""
+
+    def __repr__(self):
+        if self.__origin__ is None:
+            return super().__repr__()
+        return self._tree_repr(self._subs_tree())
+
+    def _tree_repr(self, tree):
+        if _gorg(self) is not Callable:
+            return super()._tree_repr(tree)
+        # For actual Callable (not its subclass) we override
+        # super()._tree_repr() for nice formatting.
+        arg_list = []
+        for arg in tree[1:]:
+            if not isinstance(arg, tuple):
+                arg_list.append(_type_repr(arg))
+            else:
+                arg_list.append(arg[0]._tree_repr(arg))
+        if arg_list[0] == '...':
+            return repr(tree[0]) + '[..., %s]' % arg_list[1]
+        return (repr(tree[0]) +
+                '[[%s], %s]' % (', '.join(arg_list[:-1]), arg_list[-1]))
+
+    def __getitem__(self, parameters):
+        """A thin wrapper around __getitem_inner__ to provide the latter
+        with hashable arguments to improve speed.
+        """
+
+        if  self.__origin__ is not None or not _geqv(self, Callable):
+            return super().__getitem__(parameters)
+        if not isinstance(parameters, tuple) or len(parameters) != 2:
+            raise TypeError("Callable must be used as "
+                            "Callable[[arg, ...], result].")
+        args, result = parameters
+        if args is Ellipsis:
+            parameters = (Ellipsis, result)
         else:
-            origin = _gorg(cls)
-            obj = cls.__next_in_mro__.__new__(origin)
-            obj.__init__(*args, **kwds)
-            return obj
+            if not isinstance(args, list):
+                raise TypeError("Callable[args, result]: args must be a list."
+                                " Got %.100r." % (args,))
+            parameters = (tuple(args), result)
+        return self.__getitem_inner__(parameters)
+
+    @_tp_cache
+    def __getitem_inner__(self, parameters):
+        args, result = parameters
+        msg = "Callable[args, result]: result must be a type."
+        result = _type_check(result, msg)
+        if args is Ellipsis:
+            return super().__getitem__((_TypingEllipsis, result))
+        msg = "Callable[[arg, ...], result]: each arg must be a type."
+        args = tuple(_type_check(arg, msg) for arg in args)
+        parameters = args + (result,)
+        return super().__getitem__(parameters)
+
+
+class Callable(extra=collections_abc.Callable, metaclass = CallableMeta):
+    """Callable type; Callable[[int], str] is a function of (int) -> str.
+
+    The subscription syntax must always be used with exactly two
+    values: the argument list and the return type.  The argument list
+    must be a list of types or ellipsis; the return type must be a single type.
+
+    There is no syntax to indicate optional or keyword arguments,
+    such function types are rarely used as callback types.
+    """
+
+    __slots__ = ()
+
+    def __new__(cls, *args, **kwds):
+        if _geqv(cls, Callable):
+            raise TypeError("Type Callable cannot be instantiated; "
+                            "use a non-abstract subclass instead")
+        return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
+
+
+class _ClassVar(_FinalTypingBase, _root=True):
+    """Special type construct to mark class variables.
+
+    An 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. Usage::
+
+      class Starship:
+          stats: ClassVar[Dict[str, int]] = {} # class variable
+          damage: int = 10                     # instance variable
+
+    ClassVar accepts only types and cannot be further subscribed.
+
+    Note that ClassVar is not a class itself, and should not
+    be used with isinstance() or issubclass().
+    """
+
+    __slots__ = ('__type__',)
+
+    def __init__(self, tp=None, **kwds):
+        self.__type__ = tp
+
+    def __getitem__(self, item):
+        cls = type(self)
+        if self.__type__ is None:
+            return cls(_type_check(item,
+                       '{} accepts only single type.'.format(cls.__name__[1:])),
+                       _root=True)
+        raise TypeError('{} cannot be further subscripted'
+                        .format(cls.__name__[1:]))
+
+    def _eval_type(self, globalns, localns):
+        new_tp = _eval_type(self.__type__, globalns, localns)
+        if new_tp == self.__type__:
+            return self
+        return type(self)(new_tp, _root=True)
+
+    def __repr__(self):
+        r = super().__repr__()
+        if self.__type__ is not None:
+            r += '[{}]'.format(_type_repr(self.__type__))
+        return r
+
+    def __hash__(self):
+        return hash((type(self).__name__, self.__type__))
+
+    def __eq__(self, other):
+        if not isinstance(other, _ClassVar):
+            return NotImplemented
+        if self.__type__ is not None:
+            return self.__type__ == other.__type__
+        return self is other
+
+
+ClassVar = _ClassVar(_root=True)
 
 
 def cast(typ, val):
@@ -1131,7 +1337,11 @@ def cast(typ, val):
 
 def _get_defaults(func):
     """Internal helper to extract the default arguments, by name."""
-    code = func.__code__
+    try:
+        code = func.__code__
+    except AttributeError:
+        # Some built-in functions don't have __code__, __defaults__, etc.
+        return {}
     pos_count = code.co_argcount
     arg_names = code.co_varnames
     arg_names = arg_names[:pos_count]
@@ -1146,12 +1356,20 @@ def _get_defaults(func):
 
 
 def get_type_hints(obj, globalns=None, localns=None):
-    """Return type hints for a function or method object.
+    """Return type hints for an object.
 
     This is often the same as obj.__annotations__, but it handles
     forward references encoded as string literals, and if necessary
     adds Optional[t] if a default value equal to None is set.
 
+    The argument may be a module, class, method, or function. The annotations
+    are returned as a dictionary. For classes, annotations include also
+    inherited members.
+
+    TypeError is raised if the argument is not of a type that can contain
+    annotations, and an empty dictionary is returned if no annotations are
+    present.
+
     BEWARE -- the behavior of globalns and localns is counterintuitive
     (unless you are familiar with how eval() and exec() work).  The
     search order is locals first, then globals.
@@ -1166,6 +1384,7 @@ def get_type_hints(obj, globalns=None, localns=None):
     - If two dict arguments are passed, they specify globals and
       locals, respectively.
     """
+
     if getattr(obj, '__no_type_check__', None):
         return {}
     if globalns is None:
@@ -1174,9 +1393,35 @@ def get_type_hints(obj, globalns=None, localns=None):
             localns = globalns
     elif localns is None:
         localns = globalns
+    # Classes require a special treatment.
+    if isinstance(obj, type):
+        hints = {}
+        for base in reversed(obj.__mro__):
+            ann = base.__dict__.get('__annotations__', {})
+            for name, value in ann.items():
+                if value is None:
+                    value = type(None)
+                if isinstance(value, str):
+                    value = _ForwardRef(value)
+                value = _eval_type(value, globalns, localns)
+                hints[name] = value
+        return hints
+    hints = getattr(obj, '__annotations__', None)
+    if hints is None:
+        # Return empty annotations for something that _could_ have them.
+        if (isinstance(obj, types.FunctionType) or
+            isinstance(obj, types.BuiltinFunctionType) or
+            isinstance(obj, types.MethodType) or
+            isinstance(obj, types.ModuleType)):
+            return {}
+        else:
+            raise TypeError('{!r} is not a module, class, method, '
+                            'or function.'.format(obj))
     defaults = _get_defaults(obj)
-    hints = dict(obj.__annotations__)
+    hints = dict(hints)
     for name, value in hints.items():
+        if value is None:
+            value = type(None)
         if isinstance(value, str):
             value = _ForwardRef(value)
         value = _eval_type(value, globalns, localns)
@@ -1190,17 +1435,25 @@ def no_type_check(arg):
     """Decorator to indicate that annotations are not type hints.
 
     The argument must be a class or function; if it is a class, it
-    applies recursively to all methods defined in that class (but not
-    to methods defined in its superclasses or subclasses).
+    applies recursively to all methods and classes defined in that class
+    (but not to methods defined in its superclasses or subclasses).
 
-    This mutates the function(s) in place.
+    This mutates the function(s) or class(es) in place.
     """
     if isinstance(arg, type):
-        for obj in arg.__dict__.values():
+        arg_attrs = arg.__dict__.copy()
+        for attr, val in arg.__dict__.items():
+            if val in arg.__bases__:
+                arg_attrs.pop(attr)
+        for obj in arg_attrs.values():
             if isinstance(obj, types.FunctionType):
                 obj.__no_type_check__ = True
-    else:
+            if isinstance(obj, type):
+                no_type_check(obj)
+    try:
         arg.__no_type_check__ = True
+    except TypeError: # built-in classes
+        pass
     return arg
 
 
@@ -1266,6 +1519,8 @@ class _ProtocolMeta(GenericMeta):
     """
 
     def __instancecheck__(self, obj):
+        if _Protocol not in self.__bases__:
+            return super().__instancecheck__(obj)
         raise TypeError("Protocols cannot be used with isinstance().")
 
     def __subclasscheck__(self, cls):
@@ -1304,6 +1559,8 @@ class _ProtocolMeta(GenericMeta):
                 else:
                     if (not attr.startswith('_abc_') and
                             attr != '__abstractmethods__' and
+                            attr != '__annotations__' and
+                            attr != '__weakref__' and
                             attr != '_is_protocol' and
                             attr != '__dict__' and
                             attr != '__args__' and
@@ -1312,7 +1569,9 @@ class _ProtocolMeta(GenericMeta):
                             attr != '__next_in_mro__' and
                             attr != '__parameters__' and
                             attr != '__origin__' and
+                            attr != '__orig_bases__' and
                             attr != '__extra__' and
+                            attr != '__tree_hash__' and
                             attr != '__module__'):
                         attrs.add(attr)
 
@@ -1322,7 +1581,7 @@ class _ProtocolMeta(GenericMeta):
 class _Protocol(metaclass=_ProtocolMeta):
     """Internal base class for protocol classes.
 
-    This implements a simple-minded structural isinstance check
+    This implements a simple-minded structural issubclass check
     (similar but more general than the one-offs in collections.abc
     such as Hashable).
     """
@@ -1341,8 +1600,16 @@ Hashable = collections_abc.Hashable  # Not generic.
 if hasattr(collections_abc, 'Awaitable'):
     class Awaitable(Generic[T_co], extra=collections_abc.Awaitable):
         __slots__ = ()
-else:
-    Awaitable = None
+
+    __all__.append('Awaitable')
+
+
+if hasattr(collections_abc, 'Coroutine'):
+    class Coroutine(Awaitable[V_co], Generic[T_co, T_contra, V_co],
+                    extra=collections_abc.Coroutine):
+        __slots__ = ()
+
+    __all__.append('Coroutine')
 
 
 if hasattr(collections_abc, 'AsyncIterable'):
@@ -1354,9 +1621,8 @@ if hasattr(collections_abc, 'AsyncIterable'):
                         extra=collections_abc.AsyncIterator):
         __slots__ = ()
 
-else:
-    AsyncIterable = None
-    AsyncIterator = None
+    __all__.append('AsyncIterable')
+    __all__.append('AsyncIterator')
 
 
 class Iterable(Generic[T_co], extra=collections_abc.Iterable):
@@ -1434,109 +1700,117 @@ class Container(Generic[T_co], extra=collections_abc.Container):
     __slots__ = ()
 
 
-# Callable was defined earlier.
+if hasattr(collections_abc, 'Collection'):
+    class Collection(Sized, Iterable[T_co], Container[T_co],
+                     extra=collections_abc.Collection):
+        __slots__ = ()
 
+    __all__.append('Collection')
 
-class AbstractSet(Sized, Iterable[T_co], Container[T_co],
-                  extra=collections_abc.Set):
-    pass
+
+# Callable was defined earlier.
+
+if hasattr(collections_abc, 'Collection'):
+    class AbstractSet(Collection[T_co],
+                      extra=collections_abc.Set):
+        __slots__ = ()
+else:
+    class AbstractSet(Sized, Iterable[T_co], Container[T_co],
+                      extra=collections_abc.Set):
+        __slots__ = ()
 
 
 class MutableSet(AbstractSet[T], extra=collections_abc.MutableSet):
-    pass
+    __slots__ = ()
 
 
-# NOTE: Only the value type is covariant.
-class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
-              extra=collections_abc.Mapping):
-    pass
+# NOTE: It is only covariant in the value type.
+if hasattr(collections_abc, 'Collection'):
+    class Mapping(Collection[KT], Generic[KT, VT_co],
+                  extra=collections_abc.Mapping):
+        __slots__ = ()
+else:
+    class Mapping(Sized, Iterable[KT], Container[KT], Generic[KT, VT_co],
+                  extra=collections_abc.Mapping):
+        __slots__ = ()
 
 
 class MutableMapping(Mapping[KT, VT], extra=collections_abc.MutableMapping):
-    pass
+    __slots__ = ()
 
 if hasattr(collections_abc, 'Reversible'):
-    class Sequence(Sized, Reversible[T_co], Container[T_co],
-               extra=collections_abc.Sequence):
-        pass
+    if hasattr(collections_abc, 'Collection'):
+        class Sequence(Reversible[T_co], Collection[T_co],
+                   extra=collections_abc.Sequence):
+            __slots__ = ()
+    else:
+        class Sequence(Sized, Reversible[T_co], Container[T_co],
+                   extra=collections_abc.Sequence):
+            __slots__ = ()
 else:
     class Sequence(Sized, Iterable[T_co], Container[T_co],
                    extra=collections_abc.Sequence):
-        pass
+        __slots__ = ()
 
 
 class MutableSequence(Sequence[T], extra=collections_abc.MutableSequence):
-    pass
+    __slots__ = ()
 
 
 class ByteString(Sequence[int], extra=collections_abc.ByteString):
-    pass
-
-
-ByteString.register(type(memoryview(b'')))
+    __slots__ = ()
 
 
 class List(list, MutableSequence[T], extra=list):
 
+    __slots__ = ()
+
     def __new__(cls, *args, **kwds):
         if _geqv(cls, List):
             raise TypeError("Type List cannot be instantiated; "
                             "use list() instead")
-        return list.__new__(cls, *args, **kwds)
+        return _generic_new(list, cls, *args, **kwds)
 
 
 class Set(set, MutableSet[T], extra=set):
 
+    __slots__ = ()
+
     def __new__(cls, *args, **kwds):
         if _geqv(cls, Set):
             raise TypeError("Type Set cannot be instantiated; "
                             "use set() instead")
-        return set.__new__(cls, *args, **kwds)
-
+        return _generic_new(set, cls, *args, **kwds)
 
-class _FrozenSetMeta(GenericMeta):
-    """This metaclass ensures set is not a subclass of FrozenSet.
 
-    Without this metaclass, set would be considered a subclass of
-    FrozenSet, because FrozenSet.__extra__ is collections.abc.Set, and
-    set is a subclass of that.
-    """
-
-    def __subclasscheck__(self, cls):
-        if issubclass(cls, Set):
-            return False
-        return super().__subclasscheck__(cls)
-
-
-class FrozenSet(frozenset, AbstractSet[T_co], metaclass=_FrozenSetMeta,
-                extra=frozenset):
+class FrozenSet(frozenset, AbstractSet[T_co], extra=frozenset):
     __slots__ = ()
 
     def __new__(cls, *args, **kwds):
         if _geqv(cls, FrozenSet):
             raise TypeError("Type FrozenSet cannot be instantiated; "
                             "use frozenset() instead")
-        return frozenset.__new__(cls, *args, **kwds)
+        return _generic_new(frozenset, cls, *args, **kwds)
 
 
 class MappingView(Sized, Iterable[T_co], extra=collections_abc.MappingView):
-    pass
+    __slots__ = ()
 
 
 class KeysView(MappingView[KT], AbstractSet[KT],
                extra=collections_abc.KeysView):
-    pass
+    __slots__ = ()
 
 
 class ItemsView(MappingView[Tuple[KT, VT_co]],
                 AbstractSet[Tuple[KT, VT_co]],
                 Generic[KT, VT_co],
                 extra=collections_abc.ItemsView):
-    pass
+    __slots__ = ()
 
 
 class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
-    pass
+    __slots__ = ()
 
 
 if hasattr(contextlib, 'AbstractContextManager'):
@@ -1547,20 +1821,24 @@ if hasattr(contextlib, 'AbstractContextManager'):
 
 class Dict(dict, MutableMapping[KT, VT], extra=dict):
 
+    __slots__ = ()
+
     def __new__(cls, *args, **kwds):
         if _geqv(cls, Dict):
             raise TypeError("Type Dict cannot be instantiated; "
                             "use dict() instead")
-        return dict.__new__(cls, *args, **kwds)
+        return _generic_new(dict, cls, *args, **kwds)
 
 class DefaultDict(collections.defaultdict, MutableMapping[KT, VT],
                   extra=collections.defaultdict):
 
+    __slots__ = ()
+
     def __new__(cls, *args, **kwds):
         if _geqv(cls, DefaultDict):
             raise TypeError("Type DefaultDict cannot be instantiated; "
                             "use collections.defaultdict() instead")
-        return collections.defaultdict.__new__(cls, *args, **kwds)
+        return _generic_new(collections.defaultdict, cls, *args, **kwds)
 
 # Determine what base class to use for Generator.
 if hasattr(collections_abc, 'Generator'):
@@ -1579,15 +1857,15 @@ class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co],
         if _geqv(cls, Generator):
             raise TypeError("Type Generator cannot be instantiated; "
                             "create a subclass instead")
-        return super().__new__(cls, *args, **kwds)
+        return _generic_new(_G_base, cls, *args, **kwds)
 
 
 # Internal type variable used for Type[].
-CT = TypeVar('CT', covariant=True, bound=type)
+CT_co = TypeVar('CT_co', covariant=True, bound=type)
 
 
 # This is not a real generic class.  Don't use outside annotations.
-class Type(type, Generic[CT], extra=type):
+class Type(Generic[CT_co], extra=type):
     """A special construct usable to annotate class objects.
 
     For example, suppose we have the following classes::
@@ -1611,13 +1889,43 @@ class Type(type, Generic[CT], extra=type):
     At this point the type checker knows that joe has type BasicUser.
     """
 
+    __slots__ = ()
+
+
+def _make_nmtuple(name, types):
+    msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
+    types = [(n, _type_check(t, msg)) for n, t in types]
+    nm_tpl = collections.namedtuple(name, [n for n, t in types])
+    nm_tpl._field_types = dict(types)
+    try:
+        nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
+    except (AttributeError, ValueError):
+        pass
+    return nm_tpl
+
 
-def NamedTuple(typename, fields):
+_PY36 = sys.version_info[:2] >= (3, 6)
+
+
+class NamedTupleMeta(type):
+
+    def __new__(cls, typename, bases, ns):
+        if ns.get('_root', False):
+            return super().__new__(cls, typename, bases, ns)
+        if not _PY36:
+            raise TypeError("Class syntax for NamedTuple is only supported"
+                            " in Python 3.6+")
+        types = ns.get('__annotations__', {})
+        return _make_nmtuple(typename, types.items())
+
+class NamedTuple(metaclass=NamedTupleMeta):
     """Typed version of namedtuple.
 
-    Usage::
+    Usage in Python versions >= 3.6::
 
-        Employee = typing.NamedTuple('Employee', [('name', str), 'id', int)])
+        class Employee(NamedTuple):
+            name: str
+            id: int
 
     This is equivalent to::
 
@@ -1626,17 +1934,26 @@ def NamedTuple(typename, fields):
     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
-    API.)
+    API.) Alternative equivalent keyword syntax is also accepted::
+
+        Employee = NamedTuple('Employee', name=str, id=int)
+
+    In Python versions <= 3.5 use::
+
+        Employee = NamedTuple('Employee', [('name', str), ('id', int)])
     """
-    fields = [(n, t) for n, t in fields]
-    cls = collections.namedtuple(typename, [n for n, t in fields])
-    cls._field_types = dict(fields)
-    # Set the module to the caller's module (otherwise it'd be 'typing').
-    try:
-        cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
-    except (AttributeError, ValueError):
-        pass
-    return cls
+    _root = True
+
+    def __new__(self, typename, fields=None, **kwargs):
+        if kwargs and not _PY36:
+            raise TypeError("Keyword syntax for NamedTuple is only supported"
+                            " in Python 3.6+")
+        if fields is None:
+            fields = kwargs.items()
+        elif kwargs:
+            raise TypeError("Either list of fields or keywords"
+                            " can be provided to NamedTuple, not both")
+        return _make_nmtuple(typename, fields)
 
 
 def NewType(name, tp):
@@ -1798,7 +2115,7 @@ class TextIO(IO[str]):
         pass
 
     @abstractproperty
-    def errors(self) -> str:
+    def errors(self) -> Optional[str]:
         pass
 
     @abstractproperty
index 7f61a80..c55d563 100644 (file)
@@ -12,7 +12,7 @@ Simple usage:
     import unittest
 
     class IntegerArithmeticTestCase(unittest.TestCase):
-        def testAdd(self):  ## test method names begin 'test*'
+        def testAdd(self):  # test method names begin with 'test'
             self.assertEqual((1 + 2), 3)
             self.assertEqual(0 + 1, 1)
         def testMultiply(self):
index 524a7b1..b523f73 100644 (file)
@@ -17,6 +17,7 @@ from .util import (strclass, safe_repr, _count_diff_all_purpose,
 
 __unittest = True
 
+_subtest_msg_sentinel = object()
 
 DIFF_OMITTED = ('\nDiff is %s characters long. '
                  'Set self.maxDiff to None to see it.')
@@ -497,7 +498,7 @@ class TestCase(object):
             result.addSuccess(test_case)
 
     @contextlib.contextmanager
-    def subTest(self, msg=None, **params):
+    def subTest(self, msg=_subtest_msg_sentinel, **params):
         """Return a context manager that will return the enclosed block
         of code in a subtest identified by the optional message and
         keyword parameters.  A failure in the subtest marks the test
@@ -836,7 +837,7 @@ class TestCase(object):
            between the two objects is more than the given delta.
 
            Note that decimal places (from zero) are usually not the same
-           as significant digits (measured from the most signficant digit).
+           as significant digits (measured from the most significant digit).
 
            If the two objects compare equal then they will automatically
            compare almost equal.
@@ -875,7 +876,7 @@ class TestCase(object):
            between the two objects is less than the given delta.
 
            Note that decimal places (from zero) are usually not the same
-           as significant digits (measured from the most signficant digit).
+           as significant digits (measured from the most significant digit).
 
            Objects that are equal automatically fail.
         """
@@ -1397,7 +1398,7 @@ class _SubTest(TestCase):
 
     def _subDescription(self):
         parts = []
-        if self._message:
+        if self._message is not _subtest_msg_sentinel:
             parts.append("[{}]".format(self._message))
         if self.params:
             params_desc = ', '.join(
index 86a5a3d..669890a 100644 (file)
@@ -64,6 +64,8 @@ class _slotted(object):
     __slots__ = ['a']
 
 
+# Do not use this tuple.  It was never documented as a public API.
+# It will be removed.  It has no obvious signs of users on github.
 DescriptorTypes = (
     type(_slotted.a),
     property,
@@ -744,7 +746,7 @@ class NonCallableMock(Base):
 
     def _call_matcher(self, _call):
         """
-        Given a call (or simply a (args, kwargs) tuple), return a
+        Given a call (or simply an (args, kwargs) tuple), return a
         comparison key suitable for matching with other calls.
         This is a best effort method which relies on the spec's signature,
         if available, or falls back on the arguments themselves.
@@ -1694,6 +1696,7 @@ _non_defaults = {
     '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
     '__getstate__', '__setstate__', '__getformat__', '__setformat__',
     '__repr__', '__dir__', '__subclasses__', '__format__',
+    '__getnewargs_ex__',
 }
 
 
@@ -2129,7 +2132,7 @@ def create_autospec(spec, spec_set=False, instance=False, _parent=None,
     _kwargs.update(kwargs)
 
     Klass = MagicMock
-    if type(spec) in DescriptorTypes:
+    if inspect.isdatadescriptor(spec):
         # descriptors don't have a spec
         # because we don't know what type they return
         _kwargs = {}
index 1fb95dc..8f752b8 100644 (file)
@@ -339,7 +339,7 @@ class Test_TestCase(unittest.TestCase, TestEquality, TestHashing):
         self._check_call_order__subtests(result, events, expected)
 
     def test_run_call_order__subtests_legacy(self):
-        # With a legacy result object (without a addSubTest method),
+        # With a legacy result object (without an addSubTest method),
         # text execution stops after the first subtest failure.
         events = []
         result = LegacyLoggingResult(events)
index bb196e6..1996a8e 100644 (file)
@@ -275,7 +275,7 @@ class TestDiscovery(unittest.TestCase):
         self.assertEqual(Module.load_tests_args,
                          [(loader, [], 'test*.py')])
 
-    def test_find_tests_customise_via_package_pattern(self):
+    def test_find_tests_customize_via_package_pattern(self):
         # This test uses the example 'do-nothing' load_tests from
         # https://docs.python.org/3/library/unittest.html#load-tests-protocol
         # to make sure that that actually works.
@@ -349,7 +349,7 @@ class TestDiscovery(unittest.TestCase):
         suite = list(loader._find_tests(abspath('/foo'), 'test*.py'))
 
         # We should have loaded tests from both my_package and
-        # my_pacakge.test_module, and also run the load_tests hook in both.
+        # my_package.test_module, and also run the load_tests hook in both.
         # (normally this would be nested TestSuites.)
         self.assertEqual(suite,
                          [['my_package load_tests', [],
index e39e2ea..0a61553 100644 (file)
@@ -323,6 +323,16 @@ class Test_TestResult(unittest.TestCase):
                     'testGetSubTestDescriptionWithoutDocstringAndParams '
                     '(' + __name__ + '.Test_TestResult) (<subtest>)')
 
+    def testGetSubTestDescriptionForFalsyValues(self):
+        expected = 'testGetSubTestDescriptionForFalsyValues (%s.Test_TestResult) [%s]'
+        result = unittest.TextTestResult(None, True, 1)
+        for arg in [0, None, []]:
+            with self.subTest(arg):
+                self.assertEqual(
+                    result.getDescription(self._subtest),
+                    expected % (__name__, arg)
+                )
+
     def testGetNestedSubTestDescriptionWithoutDocstring(self):
         with self.subTest(foo=1):
             with self.subTest(bar=2):
index 5390a4e..af1ce7e 100644 (file)
@@ -27,7 +27,7 @@ class TestCallable(unittest.TestCase):
             self.assertIn(mock.__class__.__name__, repr(mock))
 
 
-    def test_heirarchy(self):
+    def test_hierarchy(self):
         self.assertTrue(issubclass(MagicMock, Mock))
         self.assertTrue(issubclass(NonCallableMagicMock, NonCallableMock))
 
index 1dbc0b6..3477634 100644 (file)
@@ -802,35 +802,53 @@ class SpecSignatureTest(unittest.TestCase):
         a.f.assert_called_with(self=10)
 
 
-    def test_autospec_property(self):
-        class Foo(object):
-            @property
-            def foo(self):
-                return 3
+    def test_autospec_data_descriptor(self):
+        class Descriptor(object):
+            def __init__(self, value):
+                self.value = value
 
-        foo = create_autospec(Foo)
-        mock_property = foo.foo
+            def __get__(self, obj, cls=None):
+                if obj is None:
+                    return self
+                return self.value
 
-        # no spec on properties
-        self.assertIsInstance(mock_property, MagicMock)
-        mock_property(1, 2, 3)
-        mock_property.abc(4, 5, 6)
-        mock_property.assert_called_once_with(1, 2, 3)
-        mock_property.abc.assert_called_once_with(4, 5, 6)
+            def __set__(self, obj, value):
+                pass
 
+        class MyProperty(property):
+            pass
 
-    def test_autospec_slots(self):
         class Foo(object):
-            __slots__ = ['a']
+            __slots__ = ['slot']
+
+            @property
+            def prop(self):
+                return 3
+
+            @MyProperty
+            def subprop(self):
+                return 4
+
+            desc = Descriptor(42)
 
         foo = create_autospec(Foo)
-        mock_slot = foo.a
 
-        # no spec on slots
-        mock_slot(1, 2, 3)
-        mock_slot.abc(4, 5, 6)
-        mock_slot.assert_called_once_with(1, 2, 3)
-        mock_slot.abc.assert_called_once_with(4, 5, 6)
+        def check_data_descriptor(mock_attr):
+            # Data descriptors don't have a spec.
+            self.assertIsInstance(mock_attr, MagicMock)
+            mock_attr(1, 2, 3)
+            mock_attr.abc(4, 5, 6)
+            mock_attr.assert_called_once_with(1, 2, 3)
+            mock_attr.abc.assert_called_once_with(4, 5, 6)
+
+        # property
+        check_data_descriptor(foo.prop)
+        # property subclass
+        check_data_descriptor(foo.subprop)
+        # class __slot__
+        check_data_descriptor(foo.slot)
+        # plain data descriptor
+        check_data_descriptor(foo.desc)
 
 
 class TestCallList(unittest.TestCase):
index 4d7fcec..566fbf7 100644 (file)
@@ -42,11 +42,12 @@ __all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag",
 uses_relative = ['ftp', 'http', 'gopher', 'nntp', 'imap',
                  'wais', 'file', 'https', 'shttp', 'mms',
                  'prospero', 'rtsp', 'rtspu', '', 'sftp',
-                 'svn', 'svn+ssh']
+                 'svn', 'svn+ssh', 'ws', 'wss']
 uses_netloc = ['ftp', 'http', 'gopher', 'nntp', 'telnet',
                'imap', 'wais', 'file', 'mms', 'https', 'shttp',
                'snews', 'prospero', 'rtsp', 'rtspu', 'rsync', '',
-               'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh']
+               'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh',
+               'ws', 'wss']
 uses_params = ['ftp', 'hdl', 'prospero', 'http', 'imap',
                'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
                'mms', '', 'sftp', 'tel']
index 1731fe3..a4bf97d 100644 (file)
@@ -1625,7 +1625,7 @@ class URLopener:
         self.proxies = proxies
         self.key_file = x509.get('key_file')
         self.cert_file = x509.get('cert_file')
-        self.addheaders = [('User-Agent', self.version)]
+        self.addheaders = [('User-Agent', self.version), ('Accept', '*/*')]
         self.__tempfiles = []
         self.__unlink = os.unlink # See cleanup()
         self.tempcache = None
@@ -2412,6 +2412,12 @@ def getproxies_environment():
         name = name.lower()
         if value and name[-6:] == '_proxy':
             proxies[name[:-6]] = value
+    # CVE-2016-1000110 - If we are running as CGI script, forget HTTP_PROXY
+    # (non-all-lowercase) as it may be set from the web server by a "Proxy:"
+    # header from the client
+    # If "proxy" is lowercase, it will still be used thanks to the next block
+    if 'REQUEST_METHOD' in os.environ:
+        proxies.pop('http', None)
     for name, value in os.environ.items():
         if name[-6:] == '_proxy':
             name = name.lower()
index 7bbffd9..c78a4ef 100644 (file)
@@ -34,7 +34,7 @@ deactivate () {
     fi
 }
 
-# unset irrelavent variables
+# unset irrelevant variables
 deactivate nondestructive
 
 VIRTUAL_ENV="__VENV_DIR__"
index 99d79e0..b0c7028 100644 (file)
@@ -5,7 +5,7 @@
 
 alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
 
-# Unset irrelavent variables.
+# Unset irrelevant variables.
 deactivate nondestructive
 
 setenv VIRTUAL_ENV "__VENV_DIR__"
index fb7f5c0..4d4f0bd 100644 (file)
@@ -15,10 +15,7 @@ function deactivate  -d "Exit virtualenv and return to normal shell environment"
     if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
         functions -e fish_prompt
         set -e _OLD_FISH_PROMPT_OVERRIDE
-        . ( begin
-                printf "function fish_prompt\n\t#"
-                functions _old_fish_prompt
-            end | psub )
+        functions -c _old_fish_prompt fish_prompt
         functions -e _old_fish_prompt
     end
 
@@ -29,7 +26,7 @@ function deactivate  -d "Exit virtualenv and return to normal shell environment"
     end
 end
 
-# unset irrelavent variables
+# unset irrelevant variables
 deactivate nondestructive
 
 set -gx VIRTUAL_ENV "__VENV_DIR__"
@@ -47,27 +44,31 @@ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
     # fish uses a function instead of an env var to generate the prompt.
 
     # save the current fish_prompt function as the function _old_fish_prompt
-    . ( begin
-            printf "function _old_fish_prompt\n\t#"
-            functions fish_prompt
-        end | psub )
+    functions -c fish_prompt _old_fish_prompt
 
     # with the original prompt function renamed, we can override with our own.
     function fish_prompt
+        # Save the return status of the last command
+        set -l old_status $status
+
         # Prompt override?
-        if test -n "$__VENV_PROMPT__"
-            printf "%s%s%s" "$__VENV_PROMPT__" (set_color normal) (_old_fish_prompt)
-            return
-        end
-        # ...Otherwise, prepend env
-        set -l _checkbase (basename "$VIRTUAL_ENV")
-        if test $_checkbase = "__"
-            # special case for Aspen magic directories
-            # see http://www.zetadev.com/software/aspen/
-            printf "%s[%s]%s %s" (set_color -b blue white) (basename (dirname "$VIRTUAL_ENV")) (set_color normal) (_old_fish_prompt)
+        if test -n "__VENV_PROMPT__"            
+            printf "%s%s" "__VENV_PROMPT__" (set_color normal)
         else
-            printf "%s(%s)%s%s" (set_color -b blue white) (basename "$VIRTUAL_ENV") (set_color normal) (_old_fish_prompt)
+            # ...Otherwise, prepend env
+            set -l _checkbase (basename "$VIRTUAL_ENV")
+            if test $_checkbase = "__"
+                # special case for Aspen magic directories
+                # see http://www.zetadev.com/software/aspen/
+                printf "%s[%s]%s " (set_color -b blue white) (basename (dirname "$VIRTUAL_ENV")) (set_color normal)
+            else
+                printf "%s(%s)%s" (set_color -b blue white) (basename "$VIRTUAL_ENV") (set_color normal)
+            end
         end
+
+        # Restore the return status of the previous command.
+        echo "exit $old_status" | .
+        _old_fish_prompt
     end
 
     set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
index 2968fb9..aaebd0c 100644 (file)
@@ -16,7 +16,8 @@ from _weakref import (
      proxy,
      CallableProxyType,
      ProxyType,
-     ReferenceType)
+     ReferenceType,
+     _remove_dead_weakref)
 
 from _weakrefset import WeakSet, _IterationGuard
 
@@ -111,7 +112,9 @@ class WeakValueDictionary(collections.MutableMapping):
                 if self._iterating:
                     self._pending_removals.append(wr.key)
                 else:
-                    del self.data[wr.key]
+                    # Atomic removal is necessary since this function
+                    # can be called asynchronously by the GC
+                    _remove_dead_weakref(d, wr.key)
         self._remove = remove
         # A list of keys to be removed
         self._pending_removals = []
@@ -125,9 +128,12 @@ class WeakValueDictionary(collections.MutableMapping):
         # We shouldn't encounter any KeyError, because this method should
         # always be called *before* mutating the dict.
         while l:
-            del d[l.pop()]
+            key = l.pop()
+            _remove_dead_weakref(d, key)
 
     def __getitem__(self, key):
+        if self._pending_removals:
+            self._commit_removals()
         o = self.data[key]()
         if o is None:
             raise KeyError(key)
@@ -140,9 +146,13 @@ class WeakValueDictionary(collections.MutableMapping):
         del self.data[key]
 
     def __len__(self):
-        return len(self.data) - len(self._pending_removals)
+        if self._pending_removals:
+            self._commit_removals()
+        return len(self.data)
 
     def __contains__(self, key):
+        if self._pending_removals:
+            self._commit_removals()
         try:
             o = self.data[key]()
         except KeyError:
@@ -158,6 +168,8 @@ class WeakValueDictionary(collections.MutableMapping):
         self.data[key] = KeyedRef(value, self._remove, key)
 
     def copy(self):
+        if self._pending_removals:
+            self._commit_removals()
         new = WeakValueDictionary()
         for key, wr in self.data.items():
             o = wr()
@@ -169,6 +181,8 @@ class WeakValueDictionary(collections.MutableMapping):
 
     def __deepcopy__(self, memo):
         from copy import deepcopy
+        if self._pending_removals:
+            self._commit_removals()
         new = self.__class__()
         for key, wr in self.data.items():
             o = wr()
@@ -177,6 +191,8 @@ class WeakValueDictionary(collections.MutableMapping):
         return new
 
     def get(self, key, default=None):
+        if self._pending_removals:
+            self._commit_removals()
         try:
             wr = self.data[key]
         except KeyError:
@@ -190,6 +206,8 @@ class WeakValueDictionary(collections.MutableMapping):
                 return o
 
     def items(self):
+        if self._pending_removals:
+            self._commit_removals()
         with _IterationGuard(self):
             for k, wr in self.data.items():
                 v = wr()
@@ -197,6 +215,8 @@ class WeakValueDictionary(collections.MutableMapping):
                     yield k, v
 
     def keys(self):
+        if self._pending_removals:
+            self._commit_removals()
         with _IterationGuard(self):
             for k, wr in self.data.items():
                 if wr() is not None:
@@ -214,10 +234,14 @@ class WeakValueDictionary(collections.MutableMapping):
         keep the values around longer than needed.
 
         """
+        if self._pending_removals:
+            self._commit_removals()
         with _IterationGuard(self):
             yield from self.data.values()
 
     def values(self):
+        if self._pending_removals:
+            self._commit_removals()
         with _IterationGuard(self):
             for wr in self.data.values():
                 obj = wr()
@@ -239,24 +263,27 @@ class WeakValueDictionary(collections.MutableMapping):
         try:
             o = self.data.pop(key)()
         except KeyError:
+            o = None
+        if o is None:
             if args:
                 return args[0]
-            raise
-        if o is None:
-            raise KeyError(key)
+            else:
+                raise KeyError(key)
         else:
             return o
 
     def setdefault(self, key, default=None):
         try:
-            wr = self.data[key]
+            o = self.data[key]()
         except KeyError:
+            o = None
+        if o is None:
             if self._pending_removals:
                 self._commit_removals()
             self.data[key] = KeyedRef(default, self._remove, key)
             return default
         else:
-            return wr()
+            return o
 
     def update(*args, **kwargs):
         if not args:
@@ -287,6 +314,8 @@ class WeakValueDictionary(collections.MutableMapping):
         keep the values around longer than needed.
 
         """
+        if self._pending_removals:
+            self._commit_removals()
         return list(self.data.values())
 
 
index 845f1d0..6f43b7f 100755 (executable)
@@ -245,7 +245,17 @@ class UnixBrowser(BaseBrowser):
 
 
 class Mozilla(UnixBrowser):
-    """Launcher class for Mozilla/Netscape browsers."""
+    """Launcher class for Mozilla browsers."""
+
+    remote_args = ['%action', '%s']
+    remote_action = ""
+    remote_action_newwin = "-new-window"
+    remote_action_newtab = "-new-tab"
+    background = True
+
+
+class Netscape(UnixBrowser):
+    """Launcher class for Netscape browser."""
 
     raise_opts = ["-noraise", "-raise"]
     remote_args = ['-remote', 'openURL(%s%action)']
@@ -254,8 +264,6 @@ class Mozilla(UnixBrowser):
     remote_action_newtab = ",new-tab"
     background = True
 
-Netscape = Mozilla
-
 
 class Galeon(UnixBrowser):
     """Launcher class for Galeon/Epiphany browsers."""
@@ -430,14 +438,18 @@ def register_X_browsers():
     if shutil.which("x-www-browser"):
         register("x-www-browser", None, BackgroundBrowser("x-www-browser"))
 
-    # The Mozilla/Netscape browsers
-    for browser in ("mozilla-firefox", "firefox",
-                    "mozilla-firebird", "firebird",
-                    "iceweasel", "iceape",
-                    "seamonkey", "mozilla", "netscape"):
+    # The Mozilla browsers
+    for browser in ("firefox", "iceweasel", "iceape", "seamonkey"):
         if shutil.which(browser):
             register(browser, None, Mozilla(browser))
 
+    # The Netscape and old Mozilla browsers
+    for browser in ("mozilla-firefox",
+                    "mozilla-firebird", "firebird",
+                    "mozilla", "netscape"):
+        if shutil.which(browser):
+            register(browser, None, Netscape(browser))
+
     # Konqueror/kfm, the KDE browser.
     if shutil.which("kfm"):
         register("kfm", Konqueror, Konqueror("kfm"))
@@ -600,6 +612,7 @@ if sys.platform == 'darwin':
     # (but we prefer using the OS X specific stuff)
     register("safari", None, MacOSXOSAScript('safari'), -1)
     register("firefox", None, MacOSXOSAScript('firefox'), -1)
+    register("chrome", None, MacOSXOSAScript('chrome'), -1)
     register("MacOSX", None, MacOSXOSAScript('default'), -1)
 
 
index 8976144..2bd835b 100644 (file)
@@ -10,7 +10,7 @@ This avoids all the overhead of SAX and pulldom to gain performance.
 # minidom DOM and can't be used with other DOM implementations.  This
 # is due, in part, to a lack of appropriate methods in the DOM (there is
 # no way to create Entity and Notation nodes via the DOM Level 2
-# interface), and for performance.  The later is the cause of some fairly
+# interface), and for performance.  The latter is the cause of some fairly
 # cryptic code.
 #
 # Performance hacks:
index 6d1b0ab..92821c5 100644 (file)
@@ -1083,8 +1083,19 @@ def _escape_attrib(text):
             text = text.replace(">", "&gt;")
         if "\"" in text:
             text = text.replace("\"", "&quot;")
+        # The following business with carriage returns is to satisfy
+        # Section 2.11 of the XML specification, stating that 
+        # CR or CR LN should be replaced with just LN
+        # http://www.w3.org/TR/REC-xml/#sec-line-ends
+        if "\r\n" in text:
+            text = text.replace("\r\n", "\n")
+        if "\r" in text:
+            text = text.replace("\r", "\n")
+        #The following four lines are issue 17582
         if "\n" in text:
             text = text.replace("\n", "&#10;")
+        if "\t" in text:
+            text = text.replace("\t", "&#09;")
         return text
     except (TypeError, AttributeError):
         _raise_serialization_error(text)
index 5b5bf7c..7817693 100644 (file)
@@ -184,7 +184,7 @@ class SimpleXMLRPCDispatcher:
         are considered private and will not be called by
         SimpleXMLRPCServer.
 
-        If a registered function matches a XML-RPC request, then it
+        If a registered function matches an XML-RPC request, then it
         will be called instead of the registered instance.
 
         If the optional allow_dotted_names argument is true and the
index 56a2479..048f60a 100644 (file)
@@ -1028,6 +1028,7 @@ class ZipFile:
                 # set the modified flag so central directory gets written
                 # even if no files are added to the archive
                 self._didModify = True
+                self._start_disk = 0
                 try:
                     self.start_dir = self.fp.tell()
                 except (AttributeError, OSError):
@@ -1053,7 +1054,7 @@ class ZipFile:
                     # set the modified flag so central directory gets written
                     # even if no files are added to the archive
                     self._didModify = True
-                    self.start_dir = self.fp.tell()
+                    self.start_dir = self._start_disk = self.fp.tell()
             else:
                 raise RuntimeError("Mode must be 'r', 'w', 'x', or 'a'")
         except:
@@ -1097,17 +1098,18 @@ class ZipFile:
         offset_cd = endrec[_ECD_OFFSET]         # offset of central directory
         self._comment = endrec[_ECD_COMMENT]    # archive comment
 
-        # "concat" is zero, unless zip was concatenated to another file
-        concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
+        # self._start_disk:  Position of the start of ZIP archive
+        # It is zero, unless ZIP was concatenated to another file
+        self._start_disk = endrec[_ECD_LOCATION] - size_cd - offset_cd
         if endrec[_ECD_SIGNATURE] == stringEndArchive64:
             # If Zip64 extension structures are present, account for them
-            concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
+            self._start_disk -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
 
         if self.debug > 2:
-            inferred = concat + offset_cd
-            print("given, inferred, offset", offset_cd, inferred, concat)
+            inferred = self._start_disk + offset_cd
+            print("given, inferred, offset", offset_cd, inferred, self._start_disk)
         # self.start_dir:  Position of start of central directory
-        self.start_dir = offset_cd + concat
+        self.start_dir = offset_cd + self._start_disk
         fp.seek(self.start_dir, 0)
         data = fp.read(size_cd)
         fp = io.BytesIO(data)
@@ -1147,7 +1149,7 @@ class ZipFile:
                             t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
 
             x._decodeExtra()
-            x.header_offset = x.header_offset + concat
+            x.header_offset = x.header_offset + self._start_disk
             self.filelist.append(x)
             self.NameToInfo[x.filename] = x
 
@@ -1627,11 +1629,10 @@ class ZipFile:
                 file_size = zinfo.file_size
                 compress_size = zinfo.compress_size
 
-            if zinfo.header_offset > ZIP64_LIMIT:
-                extra.append(zinfo.header_offset)
+            header_offset = zinfo.header_offset - self._start_disk
+            if header_offset > ZIP64_LIMIT:
+                extra.append(header_offset)
                 header_offset = 0xffffffff
-            else:
-                header_offset = zinfo.header_offset
 
             extra_data = zinfo.extra
             min_version = 0
@@ -1678,7 +1679,7 @@ class ZipFile:
         # Write end-of-zip-archive record
         centDirCount = len(self.filelist)
         centDirSize = pos2 - self.start_dir
-        centDirOffset = self.start_dir
+        centDirOffset = self.start_dir - self._start_disk
         requires_zip64 = None
         if centDirCount > ZIP_FILECOUNT_LIMIT:
             requires_zip64 = "Files count"
index d09da2f..c76c4f1 100755 (executable)
@@ -242,9 +242,9 @@ def library_recipes():
 
         result.extend([
           dict(
-              name="OpenSSL 1.0.2h",
-              url="https://www.openssl.org/source/openssl-1.0.2h.tar.gz",
-              checksum='9392e65072ce4b614c1392eefc1f23d0',
+              name="OpenSSL 1.0.2j",
+              url="https://www.openssl.org/source/openssl-1.0.2j.tar.gz",
+              checksum='96322138f0b69e61b7212bc53d5e912b',
               patches=[
                   "openssl_sdk_makedepend.patch",
                    ],
index 96a8841..e22d67e 100644 (file)
@@ -1,8 +1,6 @@
 # HG changeset patch
-# Parent  d377390f787c0739a3e89f669def72d7167e5108
-# openssl_sdk_makedepend.patch
 #
-#      using openssl 1.0.2f
+#      using openssl 1.0.2j
 #
 # - support building with an OS X SDK
 
@@ -11,7 +9,7 @@ diff Configure
 diff --git a/Configure b/Configure
 --- a/Configure
 +++ b/Configure
-@@ -638,12 +638,12 @@
+@@ -642,12 +642,12 @@
  
  ##### MacOS X (a.k.a. Rhapsody or Darwin) setup
  "rhapsody-ppc-cc","cc:-O3 -DB_ENDIAN::(unknown):MACOSX_RHAPSODY::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}::",
@@ -30,13 +28,13 @@ diff --git a/Configure b/Configure
  "debug-darwin-ppc-cc","cc:-DBN_DEBUG -DREF_CHECK -DCONF_DEBUG -DCRYPTO_MDEBUG -DB_ENDIAN -g -Wall -O::-D_REENTRANT:MACOSX::BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${ppc32_asm}:osx32:dlfcn:darwin-shared:-fPIC:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
  # iPhoneOS/iOS
  "iphoneos-cross","llvm-gcc:-O3 -isysroot \$(CROSS_TOP)/SDKs/\$(CROSS_SDK) -fomit-frame-pointer -fno-common::-D_REENTRANT:iOS:-Wl,-search_paths_first%:BN_LLONG RC4_CHAR RC4_CHUNK DES_UNROLL BF_PTR:${no_asm}:dlfcn:darwin-shared:-fPIC -fno-common:-dynamiclib:.\$(SHLIB_MAJOR).\$(SHLIB_MINOR).dylib",
-@@ -1717,8 +1717,7 @@
-               s/^CC=.*$/CC= $cc/;
+@@ -1728,8 +1728,7 @@
                s/^AR=\s*ar/AR= $ar/;
                s/^RANLIB=.*/RANLIB= $ranlib/;
+               s/^RC=.*/RC= $windres/;
 -              s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $cc eq "gcc";
 -              s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/ if $ecc eq "gcc" || $ecc eq "clang";
-+              s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/
++              s/^MAKEDEPPROG=.*$/MAKEDEPPROG= $cc/;
                }
        s/^CFLAG=.*$/CFLAG= $cflags/;
        s/^DEPFLAG=.*$/DEPFLAG=$depflags/;
index f7c3b35..5507687 100644 (file)
@@ -36,7 +36,7 @@
        <key>CFBundleExecutable</key>
        <string>IDLE</string>
        <key>CFBundleGetInfoString</key>
-       <string>%version%, © 2001-2016 Python Software Foundation</string>
+       <string>%version%, © 2001-2017 Python Software Foundation</string>
        <key>CFBundleIconFile</key>
        <string>IDLE.icns</string>
        <key>CFBundleIdentifier</key>
index 8b8beb9..986760d 100644 (file)
@@ -68,8 +68,6 @@ for idx, value in enumerate(sys.argv):
         break
 
 # Now it is safe to import idlelib.
-from idlelib import macosxSupport
-macosxSupport._appbundle = True
 from idlelib.PyShell import main
 if __name__ == '__main__':
     main()
index 4a5eeb5..f1ab79f 100644 (file)
@@ -40,7 +40,7 @@
        <key>CFBundleExecutable</key>
        <string>Python Launcher</string>
        <key>CFBundleGetInfoString</key>
-       <string>%VERSION%, © 2001-2016 Python Software Foundation</string>
+       <string>%VERSION%, © 2001-2017 Python Software Foundation</string>
        <key>CFBundleIconFile</key>
        <string>PythonLauncher.icns</string>
        <key>CFBundleIdentifier</key>
index e75fb06..25779a2 100644 (file)
@@ -34,7 +34,7 @@
 - (BOOL)shouldShowUI
 {
     // if this call comes before applicationDidFinishLaunching: we
-    // should terminate immedeately after starting the script.
+    // should terminate immediately after starting the script.
     if (!initial_action_done)
         should_terminate = YES;
     initial_action_done = YES;
index a0bb971..a23166e 100644 (file)
@@ -37,7 +37,7 @@
        <key>CFBundleInfoDictionaryVersion</key>
        <string>6.0</string>
        <key>CFBundleLongVersionString</key>
-       <string>%version%, (c) 2001-2016 Python Software Foundation.</string>
+       <string>%version%, (c) 2001-2017 Python Software Foundation.</string>
        <key>CFBundleName</key>
        <string>Python</string>
        <key>CFBundlePackageType</key>
index fcba7d9..7a64619 100644 (file)
@@ -17,9 +17,9 @@
        <key>CFBundlePackageType</key>
        <string>FMWK</string>
        <key>CFBundleShortVersionString</key>
-       <string>%VERSION%, (c) 2001-2016 Python Software Foundation.</string>
+       <string>%VERSION%, (c) 2001-2017 Python Software Foundation.</string>
        <key>CFBundleLongVersionString</key>
-       <string>%VERSION%, (c) 2001-2016 Python Software Foundation.</string>
+       <string>%VERSION%, (c) 2001-2017 Python Software Foundation.</string>
        <key>CFBundleSignature</key>
        <string>????</string>
        <key>CFBundleVersion</key>
index 87528a0..a88b7d5 100644 (file)
@@ -20,6 +20,7 @@
 
 # === Variables set by makesetup ===
 
+MODNAMES=       _MODNAMES_
 MODOBJS=        _MODOBJS_
 MODLIBS=        _MODLIBS_
 
@@ -90,7 +91,7 @@ PY_CFLAGS_NODIST=$(CONFIGURE_CFLAGS_NODIST) $(CFLAGS_NODIST)
 # Both CPPFLAGS and LDFLAGS need to contain the shell's value for setup.py to
 # be able to build extension modules using the directories specified in the
 # environment variables
-PY_CPPFLAGS=   $(BASECPPFLAGS) -I. -IInclude -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) $(CPPFLAGS)
+PY_CPPFLAGS=   $(BASECPPFLAGS) -I. -I$(srcdir)/Include $(CONFIGURE_CPPFLAGS) $(CPPFLAGS)
 PY_LDFLAGS=    $(CONFIGURE_LDFLAGS) $(LDFLAGS)
 NO_AS_NEEDED=  @NO_AS_NEEDED@
 LDLAST=                @LDLAST@
@@ -221,7 +222,7 @@ LIBOBJS=    @LIBOBJS@
 PYTHON=                python$(EXE)
 BUILDPYTHON=   python$(BUILDEXE)
 
-cross_compiling=@cross_compiling@
+PYTHON_FOR_GEN=@PYTHON_FOR_GEN@
 PYTHON_FOR_BUILD=@PYTHON_FOR_BUILD@
 _PYTHON_HOST_PLATFORM=@_PYTHON_HOST_PLATFORM@
 BUILD_GNU_TYPE=        @build@
@@ -339,7 +340,7 @@ PGENOBJS=   $(POBJS) $(PGOBJS)
 OPCODE_H_DIR=  $(srcdir)/Include
 OPCODE_H_SCRIPT= $(srcdir)/Tools/scripts/generate_opcode_h.py
 OPCODE_H=      $(OPCODE_H_DIR)/opcode.h
-OPCODE_H_GEN=  @OPCODEHGEN@  $(OPCODE_H_SCRIPT) $(srcdir)/Lib/opcode.py $(OPCODE_H)
+OPCODE_H_GEN=  $(PYTHON_FOR_GEN) $(OPCODE_H_SCRIPT) $(srcdir)/Lib/opcode.py $(OPCODE_H)
 #
 ##########################################################################
 # AST
@@ -352,7 +353,7 @@ AST_ASDL=   $(srcdir)/Parser/Python.asdl
 ASDLGEN_FILES= $(srcdir)/Parser/asdl.py $(srcdir)/Parser/asdl_c.py
 # Note that a build now requires Python to exist before the build starts.
 # Use "hg touch" to fix up screwed up file mtimes in a checkout.
-ASDLGEN=       @ASDLGEN@ $(srcdir)/Parser/asdl_c.py
+ASDLGEN=       $(PYTHON_FOR_GEN) $(srcdir)/Parser/asdl_c.py
 
 ##########################################################################
 # Python
@@ -481,7 +482,7 @@ LIBRARY_OBJS=       \
 # Rules
 
 # Default target
-all:           build_all
+all:           @DEF_MAKE_ALL_RULE@
 build_all:     $(BUILDPYTHON) oldsharedmods sharedmods gdbhooks Programs/_testembed python-config
 
 # Compile a binary with profile guided optimization.
@@ -505,7 +506,7 @@ profile-opt:
        $(MAKE) profile-removal
 
 build_all_generate_profile:
-       $(MAKE) all CFLAGS_NODIST="$(CFLAGS) $(PGO_PROF_GEN_FLAG) @LTOFLAGS@" LDFLAGS="$(LDFLAGS) $(PGO_PROF_GEN_FLAG) @LTOFLAGS@" LIBS="$(LIBS)"
+       $(MAKE) @DEF_MAKE_RULE@ CFLAGS_NODIST="$(CFLAGS) $(PGO_PROF_GEN_FLAG) @LTOFLAGS@" LDFLAGS="$(LDFLAGS) $(PGO_PROF_GEN_FLAG) @LTOFLAGS@" LIBS="$(LIBS)"
 
 run_profile_task:
        : # FIXME: can't run for a cross build
@@ -515,14 +516,14 @@ build_all_merge_profile:
        $(LLVM_PROF_MERGER)
 
 build_all_use_profile:
-       $(MAKE) all CFLAGS_NODIST="$(CFLAGS) $(PGO_PROF_USE_FLAG) @LTOFLAGS@" LDFLAGS="$(LDFLAGS) @LTOFLAGS@"
+       $(MAKE) @DEF_MAKE_RULE@ CFLAGS_NODIST="$(CFLAGS) $(PGO_PROF_USE_FLAG) @LTOFLAGS@" LDFLAGS="$(LDFLAGS) @LTOFLAGS@"
 
 # Compile and run with gcov
 .PHONY=coverage coverage-lcov coverage-report
 coverage:
        @echo "Building with support for coverage checking:"
        $(MAKE) clean profile-removal
-       $(MAKE) all CFLAGS="$(CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov"
+       $(MAKE) @DEF_MAKE_RULE@ CFLAGS="$(CFLAGS) -O0 -pg -fprofile-arcs -ftest-coverage" LIBS="$(LIBS) -lgcov"
 
 coverage-lcov:
        @echo "Creating Coverage HTML report with LCOV:"
@@ -718,17 +719,13 @@ Programs/_freeze_importlib.o: Programs/_freeze_importlib.c Makefile
 Programs/_freeze_importlib: Programs/_freeze_importlib.o $(LIBRARY_OBJS_OMIT_FROZEN)
        $(LINKCC) $(PY_LDFLAGS) -o $@ Programs/_freeze_importlib.o $(LIBRARY_OBJS_OMIT_FROZEN) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST)
 
-Python/importlib_external.h: $(srcdir)/Lib/importlib/_bootstrap_external.py Programs/_freeze_importlib
-       if test "$(cross_compiling)" != "yes"; then \
-           ./Programs/_freeze_importlib \
-               $(srcdir)/Lib/importlib/_bootstrap_external.py Python/importlib_external.h; \
-       fi
+Python/importlib_external.h: @GENERATED_COMMENT@ $(srcdir)/Lib/importlib/_bootstrap_external.py Programs/_freeze_importlib
+       ./Programs/_freeze_importlib \
+           $(srcdir)/Lib/importlib/_bootstrap_external.py Python/importlib_external.h
 
-Python/importlib.h: $(srcdir)/Lib/importlib/_bootstrap.py Programs/_freeze_importlib
-       if test "$(cross_compiling)" != "yes"; then \
-           ./Programs/_freeze_importlib \
-               $(srcdir)/Lib/importlib/_bootstrap.py Python/importlib.h; \
-       fi
+Python/importlib.h: @GENERATED_COMMENT@ $(srcdir)/Lib/importlib/_bootstrap.py Programs/_freeze_importlib
+       ./Programs/_freeze_importlib \
+           $(srcdir)/Lib/importlib/_bootstrap.py Python/importlib.h
 
 
 ############################################################################
@@ -788,22 +785,11 @@ Python/sysmodule.o: $(srcdir)/Python/sysmodule.c Makefile
 
 $(IO_OBJS): $(IO_H)
 
-$(GRAMMAR_H): $(GRAMMAR_INPUT) $(PGEN)
+$(GRAMMAR_H): @GENERATED_COMMENT@ $(GRAMMAR_INPUT) $(PGEN)
        @$(MKDIR_P) Include
-       # Avoid copying the file onto itself for an in-tree build
-       if test "$(cross_compiling)" != "yes"; then \
-               $(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C); \
-       else \
-               cp $(srcdir)/Include/graminit.h $(GRAMMAR_H).tmp; \
-               mv $(GRAMMAR_H).tmp $(GRAMMAR_H); \
-       fi
-$(GRAMMAR_C): $(GRAMMAR_H)
-       if test "$(cross_compiling)" != "yes"; then \
-               touch $(GRAMMAR_C); \
-       else \
-               cp $(srcdir)/Python/graminit.c $(GRAMMAR_C).tmp; \
-               mv $(GRAMMAR_C).tmp $(GRAMMAR_C); \
-       fi
+       $(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C)
+$(GRAMMAR_C): @GENERATED_COMMENT@ $(GRAMMAR_H)
+       touch $(GRAMMAR_C)
 
 $(PGEN): $(PGENOBJS)
                $(CC) $(OPT) $(PY_LDFLAGS) $(PGENOBJS) $(LIBS) -o $(PGEN)
@@ -880,7 +866,7 @@ Objects/dictobject.o: $(srcdir)/Objects/stringlib/eq.h
 Objects/setobject.o: $(srcdir)/Objects/stringlib/eq.h
 
 $(OPCODETARGETS_H): $(OPCODETARGETGEN_FILES)
-       $(OPCODETARGETGEN) $(OPCODETARGETS_H)
+       $(PYTHON_FOR_GEN) $(OPCODETARGETGEN) $(OPCODETARGETS_H)
 
 Python/ceval.o: $(OPCODETARGETS_H) $(srcdir)/Python/ceval_gil.h
 
@@ -888,7 +874,7 @@ Python/frozen.o: Python/importlib.h Python/importlib_external.h
 
 Objects/typeobject.o: Objects/typeslots.inc
 Objects/typeslots.inc: $(srcdir)/Include/typeslots.h $(srcdir)/Objects/typeslots.py
-       $(PYTHON) $(srcdir)/Objects/typeslots.py < $(srcdir)/Include/typeslots.h > Objects/typeslots.inc
+       $(PYTHON_FOR_GEN) $(srcdir)/Objects/typeslots.py < $(srcdir)/Include/typeslots.h Objects/typeslots.inc
 
 ############################################################################
 # Header files
@@ -1026,7 +1012,7 @@ testuniversal:    all platform
 
 # Like testall, but with only one pass and without multiple processes.
 # Run an optional script to include information about the build environment.
-buildbottest:  all platform
+buildbottest:  build_all platform
                -@if which pybuildbot.identify >/dev/null 2>&1; then \
                        pybuildbot.identify "CC='$(CC)'" "CXX='$(CXX)'"; \
                fi
@@ -1236,6 +1222,7 @@ LIBSUBDIRS=       tkinter tkinter/test tkinter/test/test_tkinter \
                importlib test/test_importlib test/test_importlib/builtin \
                test/test_importlib/extension test/test_importlib/frozen \
                test/test_importlib/import_ test/test_importlib/source \
+               test/test_tools test/test_warnings test/test_warnings/data \
                turtledemo \
                multiprocessing multiprocessing/dummy \
                unittest unittest/test unittest/test/testmock \
@@ -1355,7 +1342,7 @@ python-config: $(srcdir)/Misc/python-config.in Misc/python-config.sh
        # is not available in configure
        sed -e "s,@EXENAME@,$(BINDIR)/python$(LDVERSION)$(EXE)," < $(srcdir)/Misc/python-config.in >python-config.py
        # Replace makefile compat. variable references with shell script compat. ones; $(VAR) -> ${VAR}
-       sed -e 's,\$$(\([A-Za-z0-9_]*\)),\$$\{\1\},g' < Misc/python-config.sh >python-config
+       LC_ALL=C sed -e 's,\$$(\([A-Za-z0-9_]*\)),\$$\{\1\},g' < Misc/python-config.sh >python-config
        # On Darwin, always use the python version of the script, the shell
        # version doesn't use the compiler customizations that are provided
        # in python (_osx_support.py).
@@ -1422,16 +1409,16 @@ libainstall:    all python-config
        $(INSTALL_SCRIPT) $(srcdir)/install-sh $(DESTDIR)$(LIBPL)/install-sh
        $(INSTALL_SCRIPT) python-config.py $(DESTDIR)$(LIBPL)/python-config.py
        $(INSTALL_SCRIPT) python-config $(DESTDIR)$(BINDIR)/python$(LDVERSION)-config
-       @if [ -s Programs/python.exp -a \
+       @if [ -s Modules/python.exp -a \
                "`echo $(MACHDEP) | sed 's/^\(...\).*/\1/'`" = "aix" ]; then \
                echo; echo "Installing support files for building shared extension modules on AIX:"; \
-               $(INSTALL_DATA) Programs/python.exp             \
+               $(INSTALL_DATA) Modules/python.exp              \
                                $(DESTDIR)$(LIBPL)/python.exp;          \
                echo; echo "$(LIBPL)/python.exp";               \
                $(INSTALL_SCRIPT) $(srcdir)/Modules/makexp_aix  \
                                $(DESTDIR)$(LIBPL)/makexp_aix;          \
                echo "$(LIBPL)/makexp_aix";                     \
-               $(INSTALL_SCRIPT) $(srcdir)/Modules/ld_so_aix   \
+               $(INSTALL_SCRIPT) Modules/ld_so_aix     \
                                $(DESTDIR)$(LIBPL)/ld_so_aix;           \
                echo "$(LIBPL)/ld_so_aix";                      \
                echo; echo "See Misc/AIX-NOTES for details.";   \
@@ -1563,10 +1550,10 @@ autoconf:
 # Create a tags file for vi
 tags::
        cd $(srcdir); \
-       ctags -w -t Include/*.h; \
-       for i in $(SRCDIRS); do ctags -w -t -a $$i/*.[ch]; \
+       ctags -w Include/*.h; \
+       for i in $(SRCDIRS); do ctags -w -a $$i/*.[ch]; \
        done; \
-       sort -o tags tags
+       LC_ALL=C sort -o tags tags
 
 # Create a tags file for GNU Emacs
 TAGS::
@@ -1609,7 +1596,7 @@ clean: pycremoval
        -rm -f pybuilddir.txt
        -rm -f Lib/lib2to3/*Grammar*.pickle
        -rm -f Programs/_testembed Programs/_freeze_importlib
-       -rm -rf build
+       -find build -type f -a ! -name '*.gc??' -exec rm -f {} ';'
 
 profile-removal:
        find . -name '*.gc??' -exec rm -f {} ';'
@@ -1635,9 +1622,13 @@ distclean: clobber
        done
        -rm -f core Makefile Makefile.pre config.status \
                Modules/Setup Modules/Setup.local Modules/Setup.config \
-               Modules/ld_so_aix Programs/python.exp Misc/python.pc
+               Modules/ld_so_aix Modules/python.exp Misc/python.pc
        -rm -f python*-gdb.py
-       find $(srcdir)/[a-zA-Z]* '(' -name '*.fdc' -o -name '*~' \
+       # Issue #28258: set LC_ALL to avoid issues with Estonian locale.
+       # Expansion is performed here by shell (spawned by make) itself before
+       # arguments are passed to find. So LC_ALL=C must be set as a separate
+       # command.
+       LC_ALL=C; find $(srcdir)/[a-zA-Z]* '(' -name '*.fdc' -o -name '*~' \
                                     -o -name '[@,#]*' -o -name '*.old' \
                                     -o -name '*.orig' -o -name '*.rej' \
                                     -o -name '*.bak' ')' \
index 632c85c..59b7704 100644 (file)
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -41,6 +41,7 @@ A. Amoroso
 Mark Anacker
 Shashwat Anand
 Anders Andersen
+Tycho Andersen
 John Anderson
 Pehr Anderson
 Erik Andersén
@@ -59,6 +60,7 @@ Alicia Arlen
 Jeffrey Armstrong
 Jason Asbahr
 David Ascher
+Ammar Askar
 Chris AtLee
 Aymeric Augustin
 John Aycock
@@ -154,6 +156,7 @@ Finn Bock
 Paul Boddie
 Matthew Boedicker
 Robin Boerdijk
+Andra Bogildea
 David Bolen
 Wouter Bolsterlee
 Gawain Bolton
@@ -186,6 +189,7 @@ Tom Bridgman
 Anthony Briggs
 Keith Briggs
 Tobias Brink
+Dillon Brock
 Richard Brodie
 Michael Broghton
 Ammar Brohi
@@ -217,12 +221,14 @@ Katherine Busch
 Ralph Butler
 Laurent De Buyst
 Zach Byrne
+Vedran Čačić
 Nicolas Cadou
 Jp Calderone
 Arnaud Calmettes
 Daniel Calvelo
 Tony Campbell
 Brett Cannon
+Tristan Carel
 Mike Carlton
 Pierre Carrier
 Terry Carroll
@@ -313,6 +319,7 @@ Simon Cross
 Felipe Cruz
 Drew Csillag
 Joaquin Cuenca Abela
+Sebastian Cufre
 John Cugini
 Tom Culliton
 Raúl Cumplido
@@ -444,6 +451,7 @@ Frederik Fix
 Tom Flanagan
 Matt Fleming
 Hernán Martínez Foffani
+Benjamin Fogle
 Artem Fokin
 Arnaud Fontaine
 Michael Foord
@@ -569,6 +577,7 @@ Travis B. Hartwell
 Larry Hastings
 Tim Hatch
 Shane Hathaway
+Michael Haubenwallner
 Janko Hauser
 Rycharde Hawkes
 Ben Hayden
@@ -649,6 +658,7 @@ Jeremy Hylton
 Ludwig Hähne
 Gerhard Häring
 Fredrik Håård
+Florian Höch
 Catalin Iacob
 Mihai Ibanescu
 Ali Ikinci
@@ -773,6 +783,7 @@ Jeff Knupp
 Kubilay Kocak
 Greg Kochanski
 Manvisha Kodali
+Niklas Koep
 Damon Kohler
 Marko Kohtala
 Vajrasky Kok
@@ -831,6 +842,8 @@ Julia Lawall
 Chris Lawrence
 Mark Lawrence
 Chris Laws
+Michael Layzell
+Michael Lazar
 Brian Leair
 Mathieu Leduc-Hamel
 Amandine Lee
@@ -939,6 +952,7 @@ Graham Matthews
 mattip
 Martin Matusiak
 Dieter Maurer
+Lev Maximov
 Daniel May
 Madison May
 Lucas Maystre
@@ -988,11 +1002,13 @@ Damien Miller
 Jason V. Miller
 Jay T. Miller
 Katie Miller
+Oren Milman
 Roman Milner
 Julien Miotte
 Andrii V. Mishkovskyi
 Dom Mitchell
 Dustin J. Mitchell
+Tim Mitchell
 Zubin Mithra
 Florian Mladitsch
 Doug Moen
@@ -1112,6 +1128,7 @@ Alecsandru Patrascu
 Randy Pausch
 Samuele Pedroni
 Justin Peel
+Loic Pefferkorn
 Marcel van der Peijl
 Berker Peksag
 Andreas Pelme
@@ -1119,6 +1136,7 @@ Steven Pemberton
 Bo Peng
 Santiago Peresón
 George Peristerakis
+Thomas Perl
 Mathieu Perreault
 Mark Perrego
 Trevor Perrin
@@ -1187,6 +1205,7 @@ Burton Radons
 Abhilash Raj
 Shorya Raj
 Jeff Ramnani
+Bayard Randel
 Varpu Rantala
 Brodie Rao
 Senko Rasic
@@ -1256,6 +1275,7 @@ Guido van Rossum
 Just van Rossum
 Hugo van Rossum
 Saskia van Rossum
+Robin Roth
 Clement Rouault
 Donald Wallace Rouse II
 Liam Routt
@@ -1278,6 +1298,7 @@ James Rutherford
 Chris Ryland
 Bernt Røskar Brenna
 Constantina S.
+Matthieu S
 Patrick Sabin
 Sébastien Sablé
 Suman Saha
@@ -1342,6 +1363,7 @@ Daniel Shahaf
 Mark Shannon
 Ha Shao
 Richard Shapiro
+Soumya Sharma
 Varun Sharma
 Daniel Shaulov
 Vlad Shcherbina
@@ -1356,6 +1378,7 @@ Shiyao Ma
 Alex Shkop
 Joel Shprentz
 Yue Shuaijie
+Jaysinh Shukla
 Terrel Shumway
 Eric Siegerman
 Paul Sijben
@@ -1439,6 +1462,7 @@ Al Sweigart
 Thenault Sylvain
 Péter Szabó
 John Szakmeister
+Piotr Szczepaniak
 Amir Szekely
 Maciej Szulik
 Arfrever Frehtes Taifersar Arahesis
@@ -1447,6 +1471,7 @@ Takase Arihiro
 Indra Talip
 Neil Tallim
 Geoff Talvola
+Anish Tambe
 Musashi Tamura
 William Tanksley
 Christian Tanzer
@@ -1585,6 +1610,7 @@ Truida Wiedijk
 Felix Wiemann
 Gerry Wiener
 Frank Wierzbicki
+Mariatta Wijaya
 Santoso Wijaya
 Chris Wilcox
 Bryce "Zooko" Wilcox-O'Hearn
@@ -1631,6 +1657,7 @@ Xiang Zhang
 Robert Xiao
 Florent Xicluna
 Arnon Yaari
+Alakshendra Yadav
 Hirokazu Yamamoto
 Ka-Ping Yee
 Jason Yeo
@@ -1655,7 +1682,10 @@ Uwe Zessin
 Cheng Zhang
 Kai Zhu
 Tarek Ziadé
+Jelle Zijlstra
 Gennadiy Zlobin
 Doug Zongker
 Peter Åstrand
 evilzero
+Chi Hsuan Yen
+Dhushyanth Ramasamy
index 6782333..9655d4c 100644 (file)
@@ -1131,7 +1131,7 @@ Library
   and http.client. Patch by EungJun Yi.
 
 - Issue #14777: tkinter may return undecoded UTF-8 bytes as a string when
-  accessing the Tk clipboard.  Modify clipboad_get() to first request type
+  accessing the Tk clipboard.  Modify clipboard_get() to first request type
   UTF8_STRING when no specific type is requested in an X11 windowing
   environment, falling back to the current default type STRING if that fails.
   Original patch by Thomas Kluyver.
@@ -1339,7 +1339,7 @@ Core and Builtins
 Library
 -------
 
-- Issue #14768: os.path.expanduser('~/a') doesn't works correctly when HOME is '/'.
+- Issue #14768: os.path.expanduser('~/a') doesn't work correctly when HOME is '/'.
 
 - Issue #14371: Support bzip2 in zipfile module.  Patch by Serhiy Storchaka.
 
@@ -2194,7 +2194,7 @@ Core and Builtins
   NULL).
 
 - Issue #10829: Refactor PyUnicode_FromFormat(), use the same function to parse
-  the format string in the 3 steps, fix crashs on invalid format strings.
+  the format string in the 3 steps, fix crashes on invalid format strings.
 
 - Issue #13007: whichdb should recognize gdbm 1.9 magic numbers.
 
@@ -5693,7 +5693,7 @@ Library
   for reading).
 
 - hashlib has two new constant attributes: algorithms_guaranteed and
-  algorithms_avaiable that respectively list the names of hash algorithms
+  algorithms_available that respectively list the names of hash algorithms
   guaranteed to exist in all Python implementations and the names of hash
   algorithms available in the current process.
 
@@ -7344,7 +7344,7 @@ Library
 - Issue #2846: Add support for gzip.GzipFile reading zero-padded files.  Patch
   by Brian Curtin.
 
-- Issue #7681: Use floor division in appropiate places in the wave module.
+- Issue #7681: Use floor division in appropriate places in the wave module.
 
 - Issue #5372: Drop the reuse of .o files in Distutils' ccompiler (since
   Extension extra options may change the output without changing the .c
@@ -9016,7 +9016,7 @@ Library
 - Issue #5976: Fixed Distutils test_check_environ.
 
 - Issue #5941: Distutils build_clib command was not working anymore because
-  of an incomplete costumization of the archiver command. Added ARFLAGS in the
+  of an incomplete customization of the archiver command. Added ARFLAGS in the
   Makefile besides AR and make Distutils use it. Original patch by David
   Cournapeau.
 
@@ -10921,7 +10921,7 @@ Platforms
 
 - Support for BeOS and AtheOS was removed (according to PEP 11).
 
-- Support for RiscOS, Irix, Tru64 was removed (alledgedly).
+- Support for RiscOS, Irix, Tru64 was removed (allegedly).
 
 Tools/Demos
 -----------
@@ -12912,7 +12912,7 @@ Library
 - Bug #947906: An object oriented interface has been added to the calendar
   module. It's possible to generate HTML calendar now and the module can be
   called as a script (e.g. via ``python -mcalendar``). Localized month and
-  weekday names can be ouput (even if an exotic encoding is used) using
+  weekday names can be output (even if an exotic encoding is used) using
   special classes that use unicode.
 
 Build
@@ -13295,7 +13295,7 @@ Library
   ``True`` for ``!=``, and raises ``TypeError`` for other comparison
   operators.  Because datetime is a subclass of date, comparing only the
   base class (date) members can still be done, if that's desired, by
-  forcing using of the approprate date method; e.g.,
+  forcing using of the appropriate date method; e.g.,
   ``a_date.__eq__(a_datetime)`` is true if and only if the year, month
   and day members of ``a_date`` and ``a_datetime`` are equal.
 
@@ -21545,7 +21545,7 @@ Thu Feb 18 20:51:50 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>
        Bow to font-lock at the end of the docstring, since it throws stuff
        off.
 
-       Make sure the path paramter to readmodule() is a list before adding it
+       Make sure the path parameter to readmodule() is a list before adding it
        with sys.path, or the addition could fail.
 
 
@@ -23445,7 +23445,7 @@ uudecode bug where it complaints about trailing garbage is still there
 decimal numbers).
 
 - In string.atof(), don't fail when the "re" module is unavailable.
-Plug the ensueing security leak by supplying an empty __builtins__
+Plug the ensuing security leak by supplying an empty __builtins__
 directory to eval().
 
 - A bunch of small fixes and improvements to Tkinter.py.
@@ -23597,7 +23597,7 @@ an underscore and used to initialize the pointer.
 - The warning about a thread still having a frame now only happens in
 verbose mode.
 
-- Change the signal finialization so that it also resets the signal
+- Change the signal finalization so that it also resets the signal
 handlers.  After this has been called, our signal handlers are no
 longer active!
 
@@ -23770,7 +23770,7 @@ Netscape on Windows/Mac).
 
 - copy.py: Make sure the objects returned by __getinitargs__() are
 kept alive (in the memo) to avoid a certain kind of nasty crash.  (Not
-easily reproducable because it requires a later call to
+easily reproducible because it requires a later call to
 __getinitargs__() to return a tuple that happens to be allocated at
 the same address.)
 
@@ -23970,7 +23970,7 @@ in Python.  An example completer, rlcompleter.py, is provided.
 
 - The traceback.py module has a new function tb_lineno() by Marc-Andre
 Lemburg which extracts the line number from the linenumber table in
-the code object.  Apparently the traceback object doesn't contains the
+the code object.  Apparently the traceback object doesn't contain the
 right linenumber when -O is used.  Rather than guessing whether -O is
 on or off, the module itself uses tb_lineno() unconditionally.
 
@@ -26057,7 +26057,7 @@ machinery is moved to the new file importdl.c.
 module implementing deepcopy and normal (shallow) copy operations.
 See the library reference manual.
 
-- Documentation strings for many objects types are accessible through
+- Documentation strings for many object types are accessible through
 the __doc__ attribute.  Modules, classes and functions support special
 syntax to initialize the __doc__ attribute: if the first statement
 consists of just a string literal, that string literal becomes the
@@ -27402,7 +27402,7 @@ bullet-proof, after reports of (minor) trouble on certain platforms.
 There is now a script to patch Makefile and config.c to add a new
 optional built-in module: Addmodule.sh.  Read the script before using!
 
-Useing Addmodule.sh, all optional modules can now be configured at
+Using Addmodule.sh, all optional modules can now be configured at
 compile time using Configure.py, so there are no modules left that
 require dynamic loading.
 
@@ -27833,9 +27833,9 @@ SOCKET: symbolic constant definitions for socket options
 
 SUNAUDIODEV: symbolic constant definitions for sunaudiodef (sun only)
 
-SV: symbolic constat definitions for sv (sgi only)
+SV: symbolic constant definitions for sv (sgi only)
 
-CD: symbolic constat definitions for cd (sgi only)
+CD: symbolic constant definitions for cd (sgi only)
 
 
 New demos
index 4ad2551..41cfdba 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -2,8 +2,702 @@
 Python News
 +++++++++++
 
-What's New in Python 3.5.2 final?
-=================================
+What's New in Python 3.5.3?
+===========================
+
+Release date: 2017-01-16
+
+There were no code changes between 3.5.3rc1 and 3.5.3 final.
+
+
+What's New in Python 3.5.3 release candidate 1?
+===============================================
+
+Release date: 2017-01-02
+
+Core and Builtins
+-----------------
+
+- Issue #29073: bytearray formatting no longer truncates on first null byte.
+
+- Issue #28932: Do not include <sys/random.h> if it does not exist.
+
+- Issue #28147: Fix a memory leak in split-table dictionaries: setattr()
+  must not convert combined table into split table.
+
+- Issue #25677: Correct the positioning of the syntax error caret for
+  indented blocks.  Based on patch by Michael Layzell.
+
+- Issue #29000: Fixed bytes formatting of octals with zero padding in alternate
+  form.
+
+- Issue #28512: Fixed setting the offset attribute of SyntaxError by
+  PyErr_SyntaxLocationEx() and PyErr_SyntaxLocationObject().
+
+- Issue #28991:  functools.lru_cache() was susceptible to an obscure reentrancy
+  bug caused by a monkey-patched len() function.
+
+- Issue #28648: Fixed crash in Py_DecodeLocale() in debug build on Mac OS X
+  when decode astral characters.  Patch by Xiang Zhang.
+
+- Issue #19398: Extra slash no longer added to sys.path components in case of
+  empty compile-time PYTHONPATH components.
+
+- Issue #28426: Fixed potential crash in PyUnicode_AsDecodedObject() in debug
+  build.
+
+- Issue #23782: Fixed possible memory leak in _PyTraceback_Add() and exception
+  loss in PyTraceBack_Here().
+
+- Issue #28379: Added sanity checks and tests for PyUnicode_CopyCharacters().
+  Patch by Xiang Zhang.
+
+- Issue #28376: The type of long range iterator is now registered as Iterator.
+  Patch by Oren Milman.
+
+- Issue #28376: The constructor of range_iterator now checks that step is not 0.
+  Patch by Oren Milman.
+
+- Issue #26906: Resolving special methods of uninitialized type now causes
+  implicit initialization of the type instead of a fail.
+
+- Issue #18287: PyType_Ready() now checks that tp_name is not NULL.
+  Original patch by Niklas Koep.
+
+- Issue #24098: Fixed possible crash when AST is changed in process of
+  compiling it.
+
+- Issue #28350: String constants with null character no longer interned.
+
+- Issue #26617: Fix crash when GC runs during weakref callbacks.
+
+- Issue #27942: String constants now interned recursively in tuples and frozensets.
+
+- Issue #21578: Fixed misleading error message when ImportError called with
+  invalid keyword args.
+
+- Issue #28203: Fix incorrect type in error message from
+  ``complex(1.0, {2:3})``. Patch by Soumya Sharma.
+
+- Issue #27955: Fallback on reading /dev/urandom device when the getrandom()
+  syscall fails with EPERM, for example when blocked by SECCOMP.
+
+- Issue #28131: Fix a regression in zipimport's compile_source().  zipimport
+  should use the same optimization level as the interpreter.
+
+- Issue #25221: Fix corrupted result from PyLong_FromLong(0) when
+  Python is compiled with NSMALLPOSINTS = 0.
+
+- Issue #25758: Prevents zipimport from unnecessarily encoding a filename
+  (patch by Eryk Sun)
+
+- Issue #28189: dictitems_contains no longer swallows compare errors.
+  (Patch by Xiang Zhang)
+
+- Issue #27812: Properly clear out a generator's frame's backreference to the
+  generator to prevent crashes in frame.clear().
+
+- Issue #27811: Fix a crash when a coroutine that has not been awaited is
+  finalized with warnings-as-errors enabled.
+
+- Issue #27587: Fix another issue found by PVS-Studio: Null pointer check
+  after use of 'def' in _PyState_AddModule().
+  Initial patch by Christian Heimes.
+
+- Issue #26020: set literal evaluation order did not match documented behaviour.
+
+- Issue #27782: Multi-phase extension module import now correctly allows the
+  ``m_methods`` field to be used to add module level functions to instances
+  of non-module types returned from ``Py_create_mod``. Patch by Xiang Zhang.
+
+- Issue #27936: The round() function accepted a second None argument
+  for some types but not for others.  Fixed the inconsistency by
+  accepting None for all numeric types.
+
+- Issue #27487: Warn if a submodule argument to "python -m" or
+  runpy.run_module() is found in sys.modules after parent packages are
+  imported, but before the submodule is executed.
+
+- Issue #27558: Fix a SystemError in the implementation of "raise" statement.
+  In a brand new thread, raise a RuntimeError since there is no active
+  exception to reraise. Patch written by Xiang Zhang.
+
+- Issue #27419: Standard __import__() no longer look up "__import__" in globals
+  or builtins for importing submodules or "from import".  Fixed handling an
+  error of non-string package name.
+
+- Issue #27083: Respect the PYTHONCASEOK environment variable under Windows.
+
+- Issue #27514: Make having too many statically nested blocks a SyntaxError
+  instead of SystemError.
+
+- Issue #27473: Fixed possible integer overflow in bytes and bytearray
+  concatenations.  Patch by Xiang Zhang.
+
+- Issue #27507: Add integer overflow check in bytearray.extend().  Patch by
+  Xiang Zhang.
+
+- Issue #27581: Don't rely on wrapping for overflow check in
+  PySequence_Tuple().  Patch by Xiang Zhang.
+
+- Issue #27443: __length_hint__() of bytearray iterators no longer return a
+  negative integer for a resized bytearray.
+
+- Issue #27942: Fix memory leak in codeobject.c
+
+Library
+-------
+
+- Issue #15812: inspect.getframeinfo() now correctly shows the first line of
+  a context.  Patch by Sam Breese.
+
+- Issue #29094: Offsets in a ZIP file created with extern file object and modes
+  "w" and "x" now are relative to the start of the file.
+
+- Issue #13051: Fixed recursion errors in large or resized
+  curses.textpad.Textbox.  Based on patch by Tycho Andersen.
+
+- Issue #29119: Fix weakrefs in the pure python version of
+  collections.OrderedDict move_to_end() method.
+  Contributed by Andra Bogildea.
+
+- Issue #9770: curses.ascii predicates now work correctly with negative
+  integers.
+
+- Issue #28427: old keys should not remove new values from
+  WeakValueDictionary when collecting from another thread.
+
+- Issue 28923: Remove editor artifacts from Tix.py.
+
+- Issue #28871: Fixed a crash when deallocate deep ElementTree.
+
+- Issue #19542: Fix bugs in WeakValueDictionary.setdefault() and
+  WeakValueDictionary.pop() when a GC collection happens in another
+  thread.
+
+- Issue #20191: Fixed a crash in resource.prlimit() when pass a sequence that
+  doesn't own its elements as limits.
+
+- Issue #28779: multiprocessing.set_forkserver_preload() would crash the
+  forkserver process if a preloaded module instantiated some
+  multiprocessing objects such as locks.
+
+- Issue #28847: dbm.dumb now supports reading read-only files and no longer
+  writes the index file when it is not changed.
+
+- Issue #25659: In ctypes, prevent a crash calling the from_buffer() and
+  from_buffer_copy() methods on abstract classes like Array.
+
+- Issue #28732: Fix crash in os.spawnv() with no elements in args
+
+- Issue #28485: Always raise ValueError for negative
+  compileall.compile_dir(workers=...) parameter, even when multithreading is
+  unavailable.
+
+- Issue #28387: Fixed possible crash in _io.TextIOWrapper deallocator when
+  the garbage collector is invoked in other thread.  Based on patch by
+  Sebastian Cufre.
+
+- Issue #27517: LZMA compressor and decompressor no longer raise exceptions if
+  given empty data twice.  Patch by Benjamin Fogle.
+
+- Issue #28549: Fixed segfault in curses's addch() with ncurses6.
+
+- Issue #28449: tarfile.open() with mode "r" or "r:" now tries to open a tar
+  file with compression before trying to open it without compression.  Otherwise
+  it had 50% chance failed with ignore_zeros=True.
+
+- Issue #23262: The webbrowser module now supports Firefox 36+ and derived
+  browsers.  Based on patch by Oleg Broytman.
+
+- Issue #27939: Fixed bugs in tkinter.ttk.LabeledScale and tkinter.Scale caused
+  by representing the scale as float value internally in Tk.  tkinter.IntVar
+  now works if float value is set to underlying Tk variable.
+
+- Issue #28255: calendar.TextCalendar().prmonth() no longer prints a space
+  at the start of new line after printing a month's calendar.  Patch by
+  Xiang Zhang.
+
+- Issue #20491: The textwrap.TextWrapper class now honors non-breaking spaces.
+  Based on patch by Kaarle Ritvanen.
+
+- Issue #28353: os.fwalk() no longer fails on broken links.
+
+- Issue #25464: Fixed HList.header_exists() in tkinter.tix module by addin
+  a workaround to Tix library bug.
+
+- Issue #28488: shutil.make_archive() no longer add entry "./" to ZIP archive.
+
+- Issue #24452: Make webbrowser support Chrome on Mac OS X.
+
+- Issue #20766: Fix references leaked by pdb in the handling of SIGINT
+  handlers.
+
+- Issue #26293: Fixed writing ZIP files that starts not from the start of the
+  file.  Offsets in ZIP file now are relative to the start of the archive in
+  conforming to the specification.
+
+- Issue #28321: Fixed writing non-BMP characters with binary format in plistlib.
+
+- Issue #28322: Fixed possible crashes when unpickle itertools objects from
+  incorrect pickle data.  Based on patch by John Leitch.
+
+- Fix possible integer overflows and crashes in the mmap module with unusual
+  usage patterns.
+
+- Issue #1703178: Fix the ability to pass the --link-objects option to the
+  distutils build_ext command.
+
+- Issue #28253: Fixed calendar functions for extreme months: 0001-01
+  and 9999-12.
+
+  Methods itermonthdays() and itermonthdays2() are reimplemented so
+  that they don't call itermonthdates() which can cause datetime.date
+  under/overflow.
+
+- Issue #28275: Fixed possible use after free in the decompress()
+  methods of the LZMADecompressor and BZ2Decompressor classes.
+  Original patch by John Leitch.
+
+- Issue #27897: Fixed possible crash in sqlite3.Connection.create_collation()
+  if pass invalid string-like object as a name.  Patch by Xiang Zhang.
+
+- Issue #18893: Fix invalid exception handling in Lib/ctypes/macholib/dyld.py.
+  Patch by Madison May.
+
+- Issue #27611: Fixed support of default root window in the tkinter.tix module.
+
+- Issue #27348: In the traceback module, restore the formatting of exception
+  messages like "Exception: None".  This fixes a regression introduced in
+  3.5a2.
+
+- Issue #25651: Allow falsy values to be used for msg parameter of subTest().
+
+- Issue #27932: Prevent memory leak in win32_ver().
+
+- Fix UnboundLocalError in socket._sendfile_use_sendfile.
+
+- Issue #28075: Check for ERROR_ACCESS_DENIED in Windows implementation of
+  os.stat().  Patch by Eryk Sun.
+
+- Issue #25270: Prevent codecs.escape_encode() from raising SystemError when
+  an empty bytestring is passed.
+
+- Issue #28181: Get antigravity over HTTPS. Patch by Kaartic Sivaraam.
+
+- Issue #25895: Enable WebSocket URL schemes in urllib.parse.urljoin.
+  Patch by Gergely Imreh and Markus Holtermann.
+
+- Issue #27599: Fixed buffer overrun in binascii.b2a_qp() and binascii.a2b_qp().
+
+- Issue #19003:m email.generator now replaces only \r and/or \n line
+  endings, per the RFC, instead of all unicode line endings.
+
+- Issue #28019: itertools.count() no longer rounds non-integer step in range
+  between 1.0 and 2.0 to 1.
+
+- Issue #25969: Update the lib2to3 grammar to handle the unpacking
+  generalizations added in 3.5.
+
+- Issue #14977: mailcap now respects the order of the lines in the mailcap
+  files ("first match"), as required by RFC 1542.  Patch by Michael Lazar.
+
+- Issue #24594: Validates persist parameter when opening MSI database
+
+- Issue #17582: xml.etree.ElementTree nows preserves whitespaces in attributes
+  (Patch by Duane Griffin.  Reviewed and approved by Stefan Behnel.)
+
+- Issue #28047: Fixed calculation of line length used for the base64 CTE
+  in the new email policies.
+
+- Issue #27445: Don't pass str(_charset) to MIMEText.set_payload().
+  Patch by Claude Paroz.
+
+- Issue #22450: urllib now includes an "Accept: */*" header among the
+  default headers.  This makes the results of REST API requests more
+  consistent and predictable especially when proxy servers are involved.
+
+- lib2to3.pgen3.driver.load_grammar() now creates a stable cache file
+  between runs given the same Grammar.txt input regardless of the hash
+  randomization setting.
+
+- Issue #27570: Avoid zero-length memcpy() etc calls with null source
+  pointers in the "ctypes" and "array" modules.
+
+- Issue #22233: Break email header lines *only* on the RFC specified CR and LF
+  characters, not on arbitrary unicode line breaks.  This also fixes a bug in
+  HTTP header parsing.
+
+- Issue 27988: Fix email iter_attachments incorrect mutation of payload list.
+
+- Issue #27691: Fix ssl module's parsing of GEN_RID subject alternative name
+  fields in X.509 certs.
+
+- Issue #27850: Remove 3DES from ssl module's default cipher list to counter
+  measure sweet32 attack (CVE-2016-2183).
+
+- Issue #27766: Add ChaCha20 Poly1305 to ssl module's default ciper list.
+  (Required OpenSSL 1.1.0 or LibreSSL).
+
+- Issue #26470: Port ssl and hashlib module to OpenSSL 1.1.0.
+
+- Remove support for passing a file descriptor to os.access. It never worked but
+  previously didn't raise.
+
+- Issue #12885: Fix error when distutils encounters symlink.
+
+- Issue #27881: Fixed possible bugs when setting sqlite3.Connection.isolation_level.
+  Based on patch by Xiang Zhang.
+
+- Issue #27861: Fixed a crash in sqlite3.Connection.cursor() when a factory
+  creates not a cursor.  Patch by Xiang Zhang.
+
+- Issue #19884: Avoid spurious output on OS X with Gnu Readline.
+
+- Issue #27706: Restore deterministic behavior of random.Random().seed()
+  for string seeds using seeding version 1.  Allows sequences of calls
+  to random() to exactly match those obtained in Python 2.
+  Patch by Nofar Schnider.
+
+- Issue #10513: Fix a regression in Connection.commit().  Statements should
+  not be reset after a commit.
+
+- A new version of typing.py from https://github.com/python/typing:
+  - Collection (only for 3.6) (Issue #27598)
+  - Add FrozenSet to __all__ (upstream #261)
+  - fix crash in _get_type_vars() (upstream #259)
+  - Remove the dict constraint in ForwardRef._eval_type (upstream #252)
+
+- Issue #27539: Fix unnormalised ``Fraction.__pow__`` result in the case
+  of negative exponent and negative base.
+
+- Issue #21718: cursor.description is now available for queries using CTEs.
+
+- Issue #2466: posixpath.ismount now correctly recognizes mount points which
+  the user does not have permission to access.
+
+- Issue #27773: Correct some memory management errors server_hostname in
+  _ssl.wrap_socket().
+
+- Issue #26750: unittest.mock.create_autospec() now works properly for
+  subclasses of property() and other data descriptors.
+
+- In the curses module, raise an error if window.getstr() or window.instr() is
+  passed a negative value.
+
+- Issue #27783: Fix possible usage of uninitialized memory in
+  operator.methodcaller.
+
+- Issue #27774: Fix possible Py_DECREF on unowned object in _sre.
+
+- Issue #27760: Fix possible integer overflow in binascii.b2a_qp.
+
+- Issue #27758: Fix possible integer overflow in the _csv module for large
+  record lengths.
+
+- Issue #27568: Prevent HTTPoxy attack (CVE-2016-1000110). Ignore the
+  HTTP_PROXY variable when REQUEST_METHOD environment is set, which indicates
+  that the script is in CGI mode.
+
+- Issue #27656: Do not assume sched.h defines any SCHED_* constants.
+
+- Issue #27130: In the "zlib" module, fix handling of large buffers
+  (typically 4 GiB) when compressing and decompressing.  Previously, inputs
+  were limited to 4 GiB, and compression and decompression operations did not
+  properly handle results of 4 GiB.
+
+- Issue #27533: Release GIL in nt._isdir
+
+- Issue #17711: Fixed unpickling by the persistent ID with protocol 0.
+  Original patch by Alexandre Vassalotti.
+
+- Issue #27522: Avoid an unintentional reference cycle in email.feedparser.
+
+- Issue #26844: Fix error message for imp.find_module() to refer to 'path'
+  instead of 'name'. Patch by Lev Maximov.
+
+- Issue #23804: Fix SSL zero-length recv() calls to not block and not raise
+  an error about unclean EOF.
+
+- Issue #27466: Change time format returned by http.cookie.time2netscape,
+  confirming the netscape cookie format and making it consistent with
+  documentation.
+
+- Issue #26664: Fix activate.fish by removing mis-use of ``$``.
+
+- Issue #22115: Fixed tracing Tkinter variables: trace_vdelete() with wrong
+  mode no longer break tracing, trace_vinfo() now always returns a list of
+  pairs of strings, tracing in the "u" mode now works.
+
+- Fix a scoping issue in importlib.util.LazyLoader which triggered an
+  UnboundLocalError when lazy-loading a module that was already put into
+  sys.modules.
+
+- Issue #27079: Fixed curses.ascii functions isblank(), iscntrl() and ispunct().
+
+- Issue #26754: Some functions (compile() etc) accepted a filename argument
+  encoded as an iterable of integers. Now only strings and byte-like objects
+  are accepted.
+
+- Issue #27048: Prevents distutils failing on Windows when environment
+  variables contain non-ASCII characters
+
+- Issue #27330: Fixed possible leaks in the ctypes module.
+
+- Issue #27238: Got rid of bare excepts in the turtle module.  Original patch
+  by Jelle Zijlstra.
+
+- Issue #27122: When an exception is raised within the context being managed
+  by a contextlib.ExitStack() and one of the exit stack generators
+  catches and raises it in a chain, do not re-raise the original exception
+  when exiting, let the new chained one through.  This avoids the PEP 479
+  bug described in issue25782.
+
+- [Security] Issue #27278: Fix os.urandom() implementation using getrandom() on
+  Linux.  Truncate size to INT_MAX and loop until we collected enough random
+  bytes, instead of casting a directly Py_ssize_t to int.
+
+- Issue #26386: Fixed ttk.TreeView selection operations with item id's
+  containing spaces.
+
+- [Security] Issue #22636: Avoid shell injection problems with
+  ctypes.util.find_library().
+
+- Issue #16182: Fix various functions in the "readline" module to use the
+  locale encoding, and fix get_begidx() and get_endidx() to return code point
+  indexes.
+
+- Issue #27392: Add loop.connect_accepted_socket().
+  Patch by Jim Fulton.
+
+- Issue #27930: Improved behaviour of logging.handlers.QueueListener.
+  Thanks to Paulo Andrade and Petr Viktorin for the analysis and patch.
+
+- Issue #21201: Improves readability of multiprocessing error message.  Thanks
+  to Wojciech Walczak for patch.
+
+- Issue #27456: asyncio: Set TCP_NODELAY by default.
+
+- Issue #27906: Fix socket accept exhaustion during high TCP traffic.
+  Patch by Kevin Conway.
+
+- Issue #28174: Handle when SO_REUSEPORT isn't properly supported.
+  Patch by Seth Michael Larson.
+
+- Issue #26654: Inspect functools.partial in asyncio.Handle.__repr__.
+  Patch by iceboy.
+
+- Issue #26909: Fix slow pipes IO in asyncio.
+  Patch by INADA Naoki.
+
+- Issue #28176: Fix callbacks race in asyncio.SelectorLoop.sock_connect.
+
+- Issue #27759: Fix selectors incorrectly retain invalid file descriptors.
+  Patch by Mark Williams.
+
+- Issue #28368: Refuse monitoring processes if the child watcher has
+  no loop attached.
+  Patch by Vincent Michel.
+
+- Issue #28369: Raise RuntimeError when transport's FD is used with
+  add_reader, add_writer, etc.
+
+- Issue #28370: Speedup asyncio.StreamReader.readexactly.
+  Patch by Коренберг Марк.
+
+- Issue #28371: Deprecate passing asyncio.Handles to run_in_executor.
+
+- Issue #28372: Fix asyncio to support formatting of non-python coroutines.
+
+- Issue #28399: Remove UNIX socket from FS before binding.
+  Patch by Коренберг Марк.
+
+- Issue #27972: Prohibit Tasks to await on themselves.
+
+- Issue #26923: Fix asyncio.Gather to refuse being cancelled once all 
+  children are done.
+  Patch by Johannes Ebke.
+
+- Issue #26796: Don't configure the number of workers for default 
+  threadpool executor.
+  Initial patch by Hans Lawrenz.
+
+- Issue #28600: Optimize loop.call_soon().
+
+- Issue #28613: Fix get_event_loop() return the current loop if 
+  called from coroutines/callbacks.
+
+- Issue #28639: Fix inspect.isawaitable to always return bool
+  Patch by Justin Mayfield.
+
+- Issue #28652: Make loop methods reject socket kinds they do not support.
+
+- Issue #28653: Fix a refleak in functools.lru_cache.
+
+- Issue #28703: Fix asyncio.iscoroutinefunction to handle Mock objects.
+
+- Issue #24142: Reading a corrupt config file left the parser in an
+  invalid state.  Original patch by Florian Höch.
+
+- Issue #28990: Fix SSL hanging if connection is closed before handshake 
+  completed.
+  (Patch by HoHo-Ho)
+
+IDLE
+----
+
+- 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.
+
+- 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 #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 #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 #27452: add line counter and crc to IDLE configHandler test dump.
+
+- 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.
+
+C API
+-----
+
+- Issue #28808: PyUnicode_CompareWithASCIIString() now never raises exceptions.
+
+- Issue #26754: PyUnicode_FSDecoder() accepted a filename argument encoded as
+  an iterable of integers. Now only strings and bytes-like objects are accepted.
+
+Documentation
+-------------
+
+- Issue #28513: Documented command-line interface of zipfile.
+
+Tests
+-----
+
+- Issue #28950: Disallow -j0 to be combined with -T/-l/-M in regrtest
+  command line arguments.
+
+- Issue #28666: Now test.support.rmtree is able to remove unwritable or
+  unreadable directories.
+
+- Issue #23839: Various caches now are cleared before running every test file.
+
+- Issue #28409: regrtest: fix the parser of command line arguments.
+
+- Issue #27787: Call gc.collect() before checking each test for "dangling
+  threads", since the dangling threads are weak references.
+
+- Issue #27369: In test_pyexpat, avoid testing an error message detail that
+  changed in Expat 2.2.0.
+
+Tools/Demos
+-----------
+
+- Issue #27952: Get Tools/scripts/fixcid.py working with Python 3 and the
+  current "re" module, avoid invalid Python backslash escapes, and fix a bug
+  parsing escaped C quote signs.
+
+- Issue #27332: Fixed the type of the first argument of module-level functions
+  generated by Argument Clinic.  Patch by Petr Viktorin.
+
+- Issue #27418: Fixed Tools/importbench/importbench.py.
+
+Windows
+-------
+
+- Issue #28251: Improvements to help manuals on Windows.
+
+- Issue #28110: launcher.msi has different product codes between 32-bit and
+  64-bit
+
+- Issue #25144: Ensures TargetDir is set before continuing with custom
+  install.
+
+- Issue #27469: Adds a shell extension to the launcher so that drag and drop
+  works correctly.
+
+- Issue #27309: Enabled proper Windows styles in python[w].exe manifest.
+
+Build
+-----
+
+- Issue #29080: Removes hard dependency on hg.exe from PCBuild/build.bat
+
+- Issue #23903: Added missed names to PC/python3.def.
+
+- Issue #10656: Fix out-of-tree building on AIX.  Patch by Tristan Carel and
+  Michael Haubenwallner.
+
+- Issue #26359: Rename --with-optimiations to --enable-optimizations.
+
+- Issue #28444: Fix missing extensions modules when cross compiling.
+
+- Issue #28248: Update Windows build and OS X installers to use OpenSSL 1.0.2j.
+
+- Issue #28258: Fixed build with Estonian locale (python-config and distclean
+  targets in Makefile).  Patch by Arfrever Frehtes Taifersar Arahesis.
+
+- Issue #26661: setup.py now detects system libffi with multiarch wrapper.
+
+- Issue #28066: Fix the logic that searches build directories for generated
+  include files when building outside the source tree.
+
+- Issue #15819: Remove redundant include search directory option for building
+  outside the source tree.
+
+- Issue #27566: Fix clean target in freeze makefile (patch by Lisa Roach)
+
+- Issue #27705: Update message in validate_ucrtbase.py
+
+- Issue #27983: Cause lack of llvm-profdata tool when using clang as
+  required for PGO linking to be a configure time error rather than
+  make time when --with-optimizations is enabled.  Also improve our
+  ability to find the llvm-profdata tool on MacOS and some Linuxes.
+
+- Issue #26307: The profile-opt build now applies PGO to the built-in modules.
+
+- Issue #26359: Add the --with-optimizations configure flag.
+
+- Issue #27713: Suppress spurious build warnings when updating importlib's
+  bootstrap files.  Patch by Xiang Zhang
+
+- Issue #25825: Correct the references to Modules/python.exp and ld_so_aix,
+  which are required on AIX.  This updates references to an installation path
+  that was changed in 3.2a4, and undoes changed references to the build tree
+  that were made in 3.5.0a1.
+
+- Issue #27453: CPP invocation in configure must use CPPFLAGS. Patch by
+  Chi Hsuan Yen.
+
+- Issue #27641: The configure script now inserts comments into the makefile
+  to prevent the pgen and _freeze_importlib executables from being cross-
+  compiled.
+
+- Issue #26662: Set PYTHON_FOR_GEN in configure as the Python program to be
+  used for file generation during the build.
+
+- Issue #10910: Avoid C++ compilation errors on FreeBSD and OS X.
+  Also update FreedBSD version checks for the original ctype UTF-8 workaround.
+
+- Issue #28676: Prevent missing 'getentropy' declaration warning on macOS.
+  Patch by Gareth Rees.
+
+
+What's New in Python 3.5.2?
+===========================
 
 Release date: 2016-06-26
 
@@ -129,7 +823,8 @@ Core and Builtins
   This allows sys.getsize() to work correctly with their subclasses with
   __slots__ defined.
 
-- Issue #25709: Fixed problem with in-place string concatenation and utf-8 cache.
+- Issue #25709: Fixed problem with in-place string concatenation and utf-8
+  cache.
 
 - Issue #27147: Mention PEP 420 in the importlib docs.
 
@@ -160,10 +855,10 @@ Core and Builtins
 Library
 -------
 
-- Issue #26556: Update expat to 2.1.1, fixes CVE-2015-1283.
+- [Security] Issue #26556: Update expat to 2.1.1, fixes CVE-2015-1283.
 
-- Fix TLS stripping vulnerability in smptlib, CVE-2016-0772.  Reported by Team
-  Oststrom
+- [Security] Fix TLS stripping vulnerability in smtplib, CVE-2016-0772.
+  Reported by Team Oststrom
 
 - Issue #21386: Implement missing IPv4Address.is_global property.  It was
   documented since 07a5610bae9d.  Initial patch by Roger Luethi.
@@ -187,9 +882,10 @@ Library
 - Issue #21313: Fix the "platform" module to tolerate when sys.version
   contains truncated build information.
 
-- Issue #26839: On Linux, :func:`os.urandom` now calls ``getrandom()`` with
-  ``GRND_NONBLOCK`` to fall back on reading ``/dev/urandom`` if the urandom
-  entropy pool is not initialized yet. Patch written by Colm Buckley.
+- [Security] Issue #26839: On Linux, :func:`os.urandom` now calls
+  ``getrandom()`` with ``GRND_NONBLOCK`` to fall back on reading
+  ``/dev/urandom`` if the urandom entropy pool is not initialized yet. Patch
+  written by Colm Buckley.
 
 - Issue #27164: In the zlib module, allow decompressing raw Deflate streams
   with a predefined zdict.  Based on patch by Xiang Zhang.
@@ -295,9 +991,9 @@ Library
 - Issue #24838: tarfile's ustar and gnu formats now correctly calculate name
   and link field limits for multibyte character encodings like utf-8.
 
-- Issue #26657: Fix directory traversal vulnerability with http.server on
-  Windows.  This fixes a regression that was introduced in 3.3.4rc1 and
-  3.4.0rc1.  Based on patch by Philipp Hagemeister.
+- [Security] Issue #26657: Fix directory traversal vulnerability with
+  http.server on Windows.  This fixes a regression that was introduced in
+  3.3.4rc1 and 3.4.0rc1.  Based on patch by Philipp Hagemeister.
 
 - Issue #26717: Stop encoding Latin-1-ized WSGI paths with UTF-8.  Patch by
   Anthony Sottile.
@@ -344,8 +1040,8 @@ Library
 - Issue #26560: Avoid potential ValueError in BaseHandler.start_response.
   Initial patch by Peter Inglesby.
 
-- Issue #26313: ssl.py _load_windows_store_certs fails if windows cert store
-  is empty. Patch by Baji.
+- [Security] Issue #26313: ssl.py _load_windows_store_certs fails if windows
+  cert store is empty. Patch by Baji.
 
 - Issue #26569: Fix :func:`pyclbr.readmodule` and :func:`pyclbr.readmodule_ex`
   to support importing packages.
@@ -374,7 +1070,8 @@ Library
   The bufsize parameter is no longer used.
 
 - Issue #2202: Fix UnboundLocalError in
-  AbstractDigestAuthHandler.get_algorithm_impls.  Initial patch by Mathieu Dupuy.
+  AbstractDigestAuthHandler.get_algorithm_impls.  Initial patch by Mathieu
+  Dupuy.
 
 - Issue #25718: Fixed pickling and copying the accumulate() iterator with
   total is None.
@@ -406,7 +1103,8 @@ Library
   the connected socket) when verify_request() returns false.  Patch by Aviv
   Palivoda.
 
-- Issue #25939: On Windows open the cert store readonly in ssl.enum_certificates.
+- [Security] Issue #25939: On Windows open the cert store readonly in
+  ssl.enum_certificates.
 
 - Issue #25995: os.walk() no longer uses FDs proportional to the tree depth.
 
@@ -612,6 +1310,9 @@ IDLE
 Documentation
 -------------
 
+- Issue #19489: Moved the search box from the sidebar to the header and footer
+  of each page.  Patch by Ammar Askar.
+
 - Issue #24136: Document the new PEP 448 unpacking syntax of 3.5.
 
 - Issue #26736: Used HTTPS for external links in the documentation if possible.
@@ -1810,8 +2511,8 @@ Library
 - Issue #1322: platform.dist() and platform.linux_distribution() functions are
   now deprecated.  Initial patch by Vajrasky Kok.
 
-- Issue #22486: Added the math.gcd() function.  The fractions.gcd() function now is
-  deprecated.  Based on patch by Mark Dickinson.
+- Issue #22486: Added the math.gcd() function.  The fractions.gcd() function
+  now is deprecated.  Based on patch by Mark Dickinson.
 
 - Issue #24064: Property() docstrings are now writeable.
   (Patch by Berker Peksag.)
@@ -1871,7 +2572,7 @@ Library
   JoinableQueue was merged with Queue).
 
 - Issue #23908: os functions now reject paths with embedded null character
-  on Windows instead of silently truncate them.
+  on Windows instead of silently truncating them.
 
 - Issue #23728: binascii.crc_hqx() could return an integer outside of the range
   0-0xffff for empty data.
@@ -2061,7 +2762,7 @@ Library
   the FTP connection failed to fix a ResourceWarning.
 
 - Issue #23853: :meth:`socket.socket.sendall` does no more reset the socket
-  timeout each time data is sent successfuly. The socket timeout is now the
+  timeout each time data is sent successfully. The socket timeout is now the
   maximum total duration to send all data.
 
 - Issue #22721: An order of multiline pprint output of set or dict containing
@@ -3070,7 +3771,7 @@ Library
 
 - Issue #18643: Add socket.socketpair() on Windows.
 
-- Issue #22435: Fix a file descriptor leak when SocketServer bind fails.
+- Issue #22435: Fix a file descriptor leak when socketserver bind fails.
 
 - Issue #13096: Fixed segfault in CTypes POINTER handling of large
   values.
@@ -3124,6 +3825,12 @@ Library
 - Issue #20218: Added convenience methods read_text/write_text and read_bytes/
   write_bytes to pathlib.Path objects.
 
+- Issue #22396: On 32-bit AIX platform, don't expose os.posix_fadvise() nor
+  os.posix_fallocate() because their prototypes in system headers are wrong.
+
+- Issue #22517: When an io.BufferedRWPair object is deallocated, clear its
+  weakrefs.
+
 - Issue #22437: Number of capturing groups in regular expression is no longer
   limited by 100.
 
@@ -3201,7 +3908,7 @@ Library
 - Issue #22168: Prevent turtle AttributeError with non-default Canvas on OS X.
 
 - Issue #21147: sqlite3 now raises an exception if the request contains a null
-  character instead of truncate it.  Based on patch by Victor Stinner.
+  character instead of truncating it.  Based on patch by Victor Stinner.
 
 - Issue #13968: The glob module now supports recursive search in
   subdirectories using the "**" pattern.
@@ -4053,7 +4760,7 @@ Build
   an explicit runtime library dependency.
 
 - Issue #17861: Tools/scripts/generate_opcode_h.py automatically regenerates
-  Include/opcode.h from Lib/opcode.py if the later gets any change.
+  Include/opcode.h from Lib/opcode.py if the latter gets any change.
 
 - Issue #20644: OS X installer build support for documentation build changes
   in 3.4.1: assume externally supplied sphinx-build is available in /usr/bin.
@@ -4275,7 +4982,7 @@ Tools/Demos
 
 - Issue #22120: For functions using an unsigned integer return converter,
   Argument Clinic now generates a cast to that type for the comparison
-  to -1 in the generated code.  (This supresses a compilation warning.)
+  to -1 in the generated code.  (This suppresses a compilation warning.)
 
 - Issue #18974: Tools/scripts/diff.py now uses argparse instead of optparse.
 
@@ -4469,7 +5176,7 @@ Core and Builtins
 
 - Issue #20588: Make Python-ast.c C89 compliant.
 
-- Issue #20437: Fixed 22 potential bugs when deleting objects references.
+- Issue #20437: Fixed 22 potential bugs when deleting object references.
 
 - Issue #20500: Displaying an exception at interpreter shutdown no longer
   risks triggering an assertion failure in PyObject_Str.
@@ -5374,8 +6081,8 @@ Core and Builtins
   when the creation of the replacement exception won't lose any information.
 
 - Issue #19466: Clear the frames of daemon threads earlier during the
-  Python shutdown to call objects destructors. So "unclosed file" resource
-  warnings are now corretly emitted for daemon threads.
+  Python shutdown to call object destructors. So "unclosed file" resource
+  warnings are now correctly emitted for daemon threads.
 
 - Issue #19514: Deduplicate some _Py_IDENTIFIER declarations.
   Patch by Andrei Dorian Duma.
@@ -6305,7 +7012,7 @@ Library
 
 - Issue #18709: Fix CVE-2013-4238. The SSL module now handles NULL bytes
   inside subjectAltName correctly. Formerly the module has used OpenSSL's
-  GENERAL_NAME_print() function to get the string represention of ASN.1
+  GENERAL_NAME_print() function to get the string representation of ASN.1
   strings for ``rfc822Name`` (email), ``dNSName`` (DNS) and
   ``uniformResourceIdentifier`` (URI).
 
@@ -6398,7 +7105,7 @@ IDLE
 Documentation
 -------------
 
-- Issue #18743: Fix references to non-existant "StringIO" module.
+- Issue #18743: Fix references to non-existent "StringIO" module.
 
 - Issue #18783: Removed existing mentions of Python long type in docstrings,
   error messages and comments.
@@ -6962,7 +7669,7 @@ Library
   on Windows and adds no value over and above python -m pydoc ...
 
 - Issue #18155: The csv module now correctly handles csv files that use
-  a delimter character that has a special meaning in regexes, instead of
+  a delimiter character that has a special meaning in regexes, instead of
   throwing an exception.
 
 - Issue #14360: encode_quopri can now be successfully used as an encoder
@@ -7337,7 +8044,7 @@ Library
   specifically addresses a stack misalignment issue on x86 and issues on
   some more recent platforms.
 
-- Issue #8862: Fixed curses cleanup when getkey is interrputed by a signal.
+- Issue #8862: Fixed curses cleanup when getkey is interrupted by a signal.
 
 - Issue #17443: imaplib.IMAP4_stream was using the default unbuffered IO
   in subprocess, but the imap code assumes buffered IO.  In Python2 this
index 493e7c1..749f2f0 100644 (file)
@@ -30,7 +30,7 @@ typedef struct {} DIR;
 typedef struct {} RFILE;
 
 /* Python/pythonrun.c
- * resourece leak false positive */
+ * resource leak false positive */
 
 void Py_FatalError(const char *msg) {
     __coverity_panic__();
@@ -140,7 +140,7 @@ static PyObject *
 build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
 {
     PyObject *result;
-    
+
     __coverity_tainted_data_sanitize__(y);
     __coverity_tainted_data_sanitize__(m);
     __coverity_tainted_data_sanitize__(d);
index 3d530d7..28f19b6 100644 (file)
@@ -111,7 +111,7 @@ program.
 .TP
 .B \-B
 Don't write
-.I .py[co]
+.I .pyc
 files on import. See also PYTHONDONTWRITEBYTECODE.
 .TP
 .B \-b
@@ -391,7 +391,7 @@ specifying \fB\-d\fP multiple times.
 .IP PYTHONDONTWRITEBYTECODE
 If this is set to a non-empty string it is equivalent to specifying
 the \fB\-B\fP option (don't try to write
-.I .py[co]
+.I .pyc
 files).
 .IP PYTHONINSPECT
 If this is set to a non-empty string it is equivalent to specifying
index e3e0eb1..67e1b65 100644 (file)
@@ -534,8 +534,10 @@ decompress(BZ2Decompressor *d, char *data, size_t len, Py_ssize_t max_length)
     }
 
     result = decompress_buf(d, max_length);
-    if(result == NULL)
+    if(result == NULL) {
+        bzs->next_in = NULL;
         return NULL;
+    }
 
     if (d->eof) {
         d->needs_input = 0;
index 7575773..9b1194e 100644 (file)
@@ -64,8 +64,8 @@ all lower case letters, and either return None, or a tuple of functions
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_register(PyModuleDef *module, PyObject *search_function)
-/*[clinic end generated code: output=d17608b6ad380eb8 input=369578467955cae4]*/
+_codecs_register(PyObject *module, PyObject *search_function)
+/*[clinic end generated code: output=d1bf21e99db7d6d3 input=369578467955cae4]*/
 {
     if (PyCodec_Register(search_function))
         return NULL;
@@ -82,8 +82,8 @@ Looks up a codec tuple in the Python codec registry and returns a CodecInfo obje
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_lookup_impl(PyModuleDef *module, const char *encoding)
-/*[clinic end generated code: output=798e41aff0c04ef6 input=3c572c0db3febe9c]*/
+_codecs_lookup_impl(PyObject *module, const char *encoding)
+/*[clinic end generated code: output=9f0afa572080c36d input=3c572c0db3febe9c]*/
 {
     return _PyCodec_Lookup(encoding);
 }
@@ -104,9 +104,9 @@ codecs.register_error that can handle ValueErrors.
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_encode_impl(PyModuleDef *module, PyObject *obj, const char *encoding,
+_codecs_encode_impl(PyObject *module, PyObject *obj, const char *encoding,
                     const char *errors)
-/*[clinic end generated code: output=5c073f62249c8d7c input=cd5b685040ff61f0]*/
+/*[clinic end generated code: output=385148eb9a067c86 input=cd5b685040ff61f0]*/
 {
     if (encoding == NULL)
         encoding = PyUnicode_GetDefaultEncoding();
@@ -131,9 +131,9 @@ codecs.register_error that can handle ValueErrors.
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_decode_impl(PyModuleDef *module, PyObject *obj, const char *encoding,
+_codecs_decode_impl(PyObject *module, PyObject *obj, const char *encoding,
                     const char *errors)
-/*[clinic end generated code: output=c81cbf6189a7f878 input=7702c0cc2fa1add6]*/
+/*[clinic end generated code: output=679882417dc3a0bd input=7702c0cc2fa1add6]*/
 {
     if (encoding == NULL)
         encoding = PyUnicode_GetDefaultEncoding();
@@ -154,8 +154,8 @@ Purge the named codec from the internal codec lookup cache
 [clinic start generated code]*/
 
 static PyObject *
-_codecs__forget_codec_impl(PyModuleDef *module, const char *encoding)
-/*[clinic end generated code: output=b56a9b99d2d28080 input=18d5d92d0e386c38]*/
+_codecs__forget_codec_impl(PyObject *module, const char *encoding)
+/*[clinic end generated code: output=0bde9f0a5b084aa2 input=18d5d92d0e386c38]*/
 {
     if (_PyCodec_Forget(encoding) < 0) {
         return NULL;
@@ -181,9 +181,9 @@ _codecs.escape_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_escape_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_escape_decode_impl(PyObject *module, Py_buffer *data,
                            const char *errors)
-/*[clinic end generated code: output=648fa3e78d03e658 input=0018edfd99db714d]*/
+/*[clinic end generated code: output=505200ba8056979a input=0018edfd99db714d]*/
 {
     PyObject *decoded = PyBytes_DecodeEscape(data->buf, data->len,
                                              errors, 0, NULL);
@@ -198,9 +198,9 @@ _codecs.escape_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_escape_encode_impl(PyModuleDef *module, PyObject *data,
+_codecs_escape_encode_impl(PyObject *module, PyObject *data,
                            const char *errors)
-/*[clinic end generated code: output=fcd6f34fe4111c50 input=da9ded00992f32f2]*/
+/*[clinic end generated code: output=4af1d477834bab34 input=da9ded00992f32f2]*/
 {
     Py_ssize_t size;
     Py_ssize_t newsize;
@@ -262,9 +262,9 @@ _codecs.unicode_internal_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_unicode_internal_decode_impl(PyModuleDef *module, PyObject *obj,
+_codecs_unicode_internal_decode_impl(PyObject *module, PyObject *obj,
                                      const char *errors)
-/*[clinic end generated code: output=9fe47c2cd8807d92 input=8d57930aeda170c6]*/
+/*[clinic end generated code: output=edbfe175e09eff9a input=8d57930aeda170c6]*/
 {
     if (PyUnicode_Check(obj)) {
         if (PyUnicode_READY(obj) < 0)
@@ -295,9 +295,9 @@ _codecs.utf_7_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_7_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_7_decode_impl(PyObject *module, Py_buffer *data,
                           const char *errors, int final)
-/*[clinic end generated code: output=ca945e907e72e827 input=bc4d6247ecdb01e6]*/
+/*[clinic end generated code: output=0cd3a944a32a4089 input=bc4d6247ecdb01e6]*/
 {
     Py_ssize_t consumed = data->len;
     PyObject *decoded = PyUnicode_DecodeUTF7Stateful(data->buf, data->len,
@@ -315,9 +315,9 @@ _codecs.utf_8_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_8_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_8_decode_impl(PyObject *module, Py_buffer *data,
                           const char *errors, int final)
-/*[clinic end generated code: output=7309f9ff4ef5c9b6 input=39161d71e7422ee2]*/
+/*[clinic end generated code: output=10f74dec8d9bb8bf input=39161d71e7422ee2]*/
 {
     Py_ssize_t consumed = data->len;
     PyObject *decoded = PyUnicode_DecodeUTF8Stateful(data->buf, data->len,
@@ -335,9 +335,9 @@ _codecs.utf_16_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_16_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_16_decode_impl(PyObject *module, Py_buffer *data,
                            const char *errors, int final)
-/*[clinic end generated code: output=8d2fa0507d9bef2c input=f3cf01d1461007ce]*/
+/*[clinic end generated code: output=783b442abcbcc2d0 input=f3cf01d1461007ce]*/
 {
     int byteorder = 0;
     /* This is overwritten unless final is true. */
@@ -357,9 +357,9 @@ _codecs.utf_16_le_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_16_le_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_16_le_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int final)
-/*[clinic end generated code: output=4fd621515ef4ce18 input=a77e3bf97335d94e]*/
+/*[clinic end generated code: output=899b9e6364379dcd input=a77e3bf97335d94e]*/
 {
     int byteorder = -1;
     /* This is overwritten unless final is true. */
@@ -379,9 +379,9 @@ _codecs.utf_16_be_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_16_be_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_16_be_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int final)
-/*[clinic end generated code: output=792f4eacb3e1fa05 input=606f69fae91b5563]*/
+/*[clinic end generated code: output=49f6465ea07669c8 input=606f69fae91b5563]*/
 {
     int byteorder = 1;
     /* This is overwritten unless final is true. */
@@ -409,9 +409,9 @@ _codecs.utf_16_ex_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_16_ex_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_16_ex_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int byteorder, int final)
-/*[clinic end generated code: output=f136a186dc2defa0 input=f6e7f697658c013e]*/
+/*[clinic end generated code: output=0f385f251ecc1988 input=f6e7f697658c013e]*/
 {
     /* This is overwritten unless final is true. */
     Py_ssize_t consumed = data->len;
@@ -433,9 +433,9 @@ _codecs.utf_32_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_32_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_32_decode_impl(PyObject *module, Py_buffer *data,
                            const char *errors, int final)
-/*[clinic end generated code: output=b7635e55857e8efb input=86d4f41c6c2e763d]*/
+/*[clinic end generated code: output=2fc961807f7b145f input=86d4f41c6c2e763d]*/
 {
     int byteorder = 0;
     /* This is overwritten unless final is true. */
@@ -455,9 +455,9 @@ _codecs.utf_32_le_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_32_le_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_32_le_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int final)
-/*[clinic end generated code: output=a79d1787d8ddf988 input=d18b650772d188ba]*/
+/*[clinic end generated code: output=ec8f46b67a94f3e6 input=d18b650772d188ba]*/
 {
     int byteorder = -1;
     /* This is overwritten unless final is true. */
@@ -477,9 +477,9 @@ _codecs.utf_32_be_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_32_be_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_32_be_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int final)
-/*[clinic end generated code: output=a8356b0f36779981 input=19c271b5d34926d8]*/
+/*[clinic end generated code: output=ff82bae862c92c4e input=19c271b5d34926d8]*/
 {
     int byteorder = 1;
     /* This is overwritten unless final is true. */
@@ -507,9 +507,9 @@ _codecs.utf_32_ex_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_32_ex_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_32_ex_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int byteorder, int final)
-/*[clinic end generated code: output=ab8c70977c1992f5 input=4af3e6ccfe34a076]*/
+/*[clinic end generated code: output=6bfb177dceaf4848 input=4af3e6ccfe34a076]*/
 {
     Py_ssize_t consumed = data->len;
     PyObject *decoded = PyUnicode_DecodeUTF32Stateful(data->buf, data->len,
@@ -528,9 +528,9 @@ _codecs.unicode_escape_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_unicode_escape_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_unicode_escape_decode_impl(PyObject *module, Py_buffer *data,
                                    const char *errors)
-/*[clinic end generated code: output=d1aa63f2620c4999 input=49fd27d06813a7f5]*/
+/*[clinic end generated code: output=3ca3c917176b82ab input=49fd27d06813a7f5]*/
 {
     PyObject *decoded = PyUnicode_DecodeUnicodeEscape(data->buf, data->len,
                                                       errors);
@@ -545,9 +545,9 @@ _codecs.raw_unicode_escape_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_raw_unicode_escape_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_raw_unicode_escape_decode_impl(PyObject *module, Py_buffer *data,
                                        const char *errors)
-/*[clinic end generated code: output=0bf96cc182d81379 input=770903a211434ebc]*/
+/*[clinic end generated code: output=c98eeb56028070a6 input=770903a211434ebc]*/
 {
     PyObject *decoded = PyUnicode_DecodeRawUnicodeEscape(data->buf, data->len,
                                                          errors);
@@ -562,9 +562,9 @@ _codecs.latin_1_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_latin_1_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_latin_1_decode_impl(PyObject *module, Py_buffer *data,
                             const char *errors)
-/*[clinic end generated code: output=66b916f5055aaf13 input=5cad0f1759c618ec]*/
+/*[clinic end generated code: output=07f3dfa3f72c7d8f input=5cad0f1759c618ec]*/
 {
     PyObject *decoded = PyUnicode_DecodeLatin1(data->buf, data->len, errors);
     return codec_tuple(decoded, data->len);
@@ -578,9 +578,9 @@ _codecs.ascii_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_ascii_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_ascii_decode_impl(PyObject *module, Py_buffer *data,
                           const char *errors)
-/*[clinic end generated code: output=7f213a1b5cdafc65 input=ad1106f64037bd16]*/
+/*[clinic end generated code: output=2627d72058d42429 input=ad1106f64037bd16]*/
 {
     PyObject *decoded = PyUnicode_DecodeASCII(data->buf, data->len, errors);
     return codec_tuple(decoded, data->len);
@@ -595,9 +595,9 @@ _codecs.charmap_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_charmap_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_charmap_decode_impl(PyObject *module, Py_buffer *data,
                             const char *errors, PyObject *mapping)
-/*[clinic end generated code: output=87d27f365098bbae input=19712ca35c5a80e2]*/
+/*[clinic end generated code: output=2c335b09778cf895 input=19712ca35c5a80e2]*/
 {
     PyObject *decoded;
 
@@ -619,9 +619,9 @@ _codecs.mbcs_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_mbcs_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_mbcs_decode_impl(PyObject *module, Py_buffer *data,
                          const char *errors, int final)
-/*[clinic end generated code: output=0ebaf3a5b20e53fa input=d492c1ca64f4fa8a]*/
+/*[clinic end generated code: output=39b65b8598938c4b input=d492c1ca64f4fa8a]*/
 {
     Py_ssize_t consumed = data->len;
     PyObject *decoded = PyUnicode_DecodeMBCSStateful(data->buf, data->len,
@@ -639,9 +639,9 @@ _codecs.code_page_decode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_code_page_decode_impl(PyModuleDef *module, int codepage,
+_codecs_code_page_decode_impl(PyObject *module, int codepage,
                               Py_buffer *data, const char *errors, int final)
-/*[clinic end generated code: output=4318e3d9971e31ba input=4f3152a304e21d51]*/
+/*[clinic end generated code: output=53008ea967da3fff input=4f3152a304e21d51]*/
 {
     Py_ssize_t consumed = data->len;
     PyObject *decoded = PyUnicode_DecodeCodePageStateful(codepage,
@@ -663,9 +663,9 @@ _codecs.readbuffer_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_readbuffer_encode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_readbuffer_encode_impl(PyObject *module, Py_buffer *data,
                                const char *errors)
-/*[clinic end generated code: output=319cc24083299859 input=b7c322b89d4ab923]*/
+/*[clinic end generated code: output=c645ea7cdb3d6e86 input=b7c322b89d4ab923]*/
 {
     PyObject *result = PyBytes_FromStringAndSize(data->buf, data->len);
     return codec_tuple(result, data->len);
@@ -679,9 +679,9 @@ _codecs.unicode_internal_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_unicode_internal_encode_impl(PyModuleDef *module, PyObject *obj,
+_codecs_unicode_internal_encode_impl(PyObject *module, PyObject *obj,
                                      const char *errors)
-/*[clinic end generated code: output=be08457068ad503b input=8628f0280cf5ba61]*/
+/*[clinic end generated code: output=a72507dde4ea558f input=8628f0280cf5ba61]*/
 {
     if (PyErr_WarnEx(PyExc_DeprecationWarning,
                      "unicode_internal codec has been deprecated",
@@ -724,9 +724,9 @@ _codecs.utf_7_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_7_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_7_encode_impl(PyObject *module, PyObject *str,
                           const char *errors)
-/*[clinic end generated code: output=a7accc496a32b759 input=fd91a78f103b0421]*/
+/*[clinic end generated code: output=0feda21ffc921bc8 input=fd91a78f103b0421]*/
 {
     PyObject *v;
 
@@ -749,9 +749,9 @@ _codecs.utf_8_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_8_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_8_encode_impl(PyObject *module, PyObject *str,
                           const char *errors)
-/*[clinic end generated code: output=ec831d80e7aedede input=2c22d40532f071f3]*/
+/*[clinic end generated code: output=02bf47332b9c796c input=2c22d40532f071f3]*/
 {
     PyObject *v;
 
@@ -782,9 +782,9 @@ _codecs.utf_16_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_16_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_16_encode_impl(PyObject *module, PyObject *str,
                            const char *errors, int byteorder)
-/*[clinic end generated code: output=93ac58e960a9ee4d input=3935a489b2d5385e]*/
+/*[clinic end generated code: output=c654e13efa2e64e4 input=3935a489b2d5385e]*/
 {
     PyObject *v;
 
@@ -807,9 +807,9 @@ _codecs.utf_16_le_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_16_le_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_16_le_encode_impl(PyObject *module, PyObject *str,
                               const char *errors)
-/*[clinic end generated code: output=422bedb8da34fb66 input=bc27df05d1d20dfe]*/
+/*[clinic end generated code: output=431b01e55f2d4995 input=bc27df05d1d20dfe]*/
 {
     PyObject *v;
 
@@ -832,9 +832,9 @@ _codecs.utf_16_be_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_16_be_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_16_be_encode_impl(PyObject *module, PyObject *str,
                               const char *errors)
-/*[clinic end generated code: output=3aa7ee9502acdd77 input=5a69d4112763462b]*/
+/*[clinic end generated code: output=96886a6fd54dcae3 input=5a69d4112763462b]*/
 {
     PyObject *v;
 
@@ -865,9 +865,9 @@ _codecs.utf_32_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_32_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_32_encode_impl(PyObject *module, PyObject *str,
                            const char *errors, int byteorder)
-/*[clinic end generated code: output=3e7d5a003b02baed input=434a1efa492b8d58]*/
+/*[clinic end generated code: output=5c760da0c09a8b83 input=434a1efa492b8d58]*/
 {
     PyObject *v;
 
@@ -890,9 +890,9 @@ _codecs.utf_32_le_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_32_le_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_32_le_encode_impl(PyObject *module, PyObject *str,
                               const char *errors)
-/*[clinic end generated code: output=5dda641cd33dbfc2 input=dfa2d7dc78b99422]*/
+/*[clinic end generated code: output=b65cd176de8e36d6 input=dfa2d7dc78b99422]*/
 {
     PyObject *v;
 
@@ -915,9 +915,9 @@ _codecs.utf_32_be_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_utf_32_be_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_32_be_encode_impl(PyObject *module, PyObject *str,
                               const char *errors)
-/*[clinic end generated code: output=ccca8b44d91a7c7a input=4595617b18169002]*/
+/*[clinic end generated code: output=1d9e71a9358709e9 input=4595617b18169002]*/
 {
     PyObject *v;
 
@@ -940,9 +940,9 @@ _codecs.unicode_escape_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_unicode_escape_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_unicode_escape_encode_impl(PyObject *module, PyObject *str,
                                    const char *errors)
-/*[clinic end generated code: output=389f23d2b8f8d80b input=8273506f14076912]*/
+/*[clinic end generated code: output=66271b30bc4f7a3c input=8273506f14076912]*/
 {
     PyObject *v;
 
@@ -965,9 +965,9 @@ _codecs.raw_unicode_escape_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_raw_unicode_escape_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_raw_unicode_escape_encode_impl(PyObject *module, PyObject *str,
                                        const char *errors)
-/*[clinic end generated code: output=fec4e39d6ec37a62 input=181755d5dfacef3c]*/
+/*[clinic end generated code: output=a66a806ed01c830a input=181755d5dfacef3c]*/
 {
     PyObject *v;
 
@@ -990,9 +990,9 @@ _codecs.latin_1_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_latin_1_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_latin_1_encode_impl(PyObject *module, PyObject *str,
                             const char *errors)
-/*[clinic end generated code: output=ecf00eb8e48c889c input=f03f6dcf1d84bee4]*/
+/*[clinic end generated code: output=2c28c83a27884e08 input=f03f6dcf1d84bee4]*/
 {
     PyObject *v;
 
@@ -1015,9 +1015,9 @@ _codecs.ascii_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_ascii_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_ascii_encode_impl(PyObject *module, PyObject *str,
                           const char *errors)
-/*[clinic end generated code: output=a9d18fc6b6b91cfb input=d87e25a10a593fee]*/
+/*[clinic end generated code: output=b5e035182d33befc input=d87e25a10a593fee]*/
 {
     PyObject *v;
 
@@ -1041,9 +1041,9 @@ _codecs.charmap_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_charmap_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_charmap_encode_impl(PyObject *module, PyObject *str,
                             const char *errors, PyObject *mapping)
-/*[clinic end generated code: output=14ca42b83853c643 input=85f4172661e8dad9]*/
+/*[clinic end generated code: output=047476f48495a9e9 input=85f4172661e8dad9]*/
 {
     PyObject *v;
 
@@ -1068,8 +1068,8 @@ _codecs.charmap_build
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_charmap_build_impl(PyModuleDef *module, PyObject *map)
-/*[clinic end generated code: output=9485b58fa44afa6a input=d91a91d1717dbc6d]*/
+_codecs_charmap_build_impl(PyObject *module, PyObject *map)
+/*[clinic end generated code: output=bb073c27031db9ac input=d91a91d1717dbc6d]*/
 {
     return PyUnicode_BuildEncodingMap(map);
 }
@@ -1084,9 +1084,8 @@ _codecs.mbcs_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_mbcs_encode_impl(PyModuleDef *module, PyObject *str,
-                         const char *errors)
-/*[clinic end generated code: output=d1a013bc68798bd7 input=65c09ee1e4203263]*/
+_codecs_mbcs_encode_impl(PyObject *module, PyObject *str, const char *errors)
+/*[clinic end generated code: output=76e2e170c966c080 input=65c09ee1e4203263]*/
 {
     PyObject *v;
 
@@ -1110,9 +1109,9 @@ _codecs.code_page_encode
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_code_page_encode_impl(PyModuleDef *module, int code_page,
-                              PyObject *str, const char *errors)
-/*[clinic end generated code: output=3b406618dbfbce25 input=c8562ec460c2e309]*/
+_codecs_code_page_encode_impl(PyObject *module, int code_page, PyObject *str,
+                              const char *errors)
+/*[clinic end generated code: output=45673f6085657a9e input=c8562ec460c2e309]*/
 {
     PyObject *v;
 
@@ -1147,9 +1146,9 @@ error and must return a (replacement, new position) tuple.
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_register_error_impl(PyModuleDef *module, const char *errors,
+_codecs_register_error_impl(PyObject *module, const char *errors,
                             PyObject *handler)
-/*[clinic end generated code: output=be00d3b1849ce68a input=5e6709203c2e33fe]*/
+/*[clinic end generated code: output=fa2f7d1879b3067d input=5e6709203c2e33fe]*/
 {
     if (PyCodec_RegisterError(errors, handler))
         return NULL;
@@ -1168,8 +1167,8 @@ LookupError, if no handler exists under this name.
 [clinic start generated code]*/
 
 static PyObject *
-_codecs_lookup_error_impl(PyModuleDef *module, const char *name)
-/*[clinic end generated code: output=731e6df8c83c6158 input=4775dd65e6235aba]*/
+_codecs_lookup_error_impl(PyObject *module, const char *name)
+/*[clinic end generated code: output=087f05dc0c9a98cc input=4775dd65e6235aba]*/
 {
     return PyCodec_LookupError(name);
 }
index d422cfd..8e4737c 100644 (file)
@@ -31,8 +31,8 @@ results for a given *word*.
 [clinic start generated code]*/
 
 static PyObject *
-crypt_crypt_impl(PyModuleDef *module, const char *word, const char *salt)
-/*[clinic end generated code: output=995ad1e854d83069 input=0e8edec9c364352b]*/
+crypt_crypt_impl(PyObject *module, const char *word, const char *salt)
+/*[clinic end generated code: output=0512284a03d2803c input=0e8edec9c364352b]*/
 {
     /* On some platforms (AtheOS) crypt returns NULL for an invalid
        salt. Return None in that case. XXX Maybe raise an exception?  */
index 101f449..b428279 100644 (file)
@@ -1014,11 +1014,19 @@ join_append_data(WriterObj *self, unsigned int field_kind, void *field_data,
     int i;
     Py_ssize_t rec_len;
 
-#define ADDCH(c) \
+#define INCLEN \
+    do {\
+        if (!copy_phase && rec_len == PY_SSIZE_T_MAX) {    \
+            goto overflow; \
+        } \
+        rec_len++; \
+    } while(0)
+
+#define ADDCH(c)                                \
     do {\
         if (copy_phase) \
             self->rec[rec_len] = c;\
-        rec_len++;\
+        INCLEN;\
     } while(0)
 
     rec_len = self->rec_len;
@@ -1072,11 +1080,18 @@ join_append_data(WriterObj *self, unsigned int field_kind, void *field_data,
     if (*quoted) {
         if (copy_phase)
             ADDCH(dialect->quotechar);
-        else
-            rec_len += 2;
+        else {
+            INCLEN; /* starting quote */
+            INCLEN; /* ending quote */
+        }
     }
     return rec_len;
+
+  overflow:
+    PyErr_NoMemory();
+    return -1;
 #undef ADDCH
+#undef INCLEN
 }
 
 static int
index 2e01323..b32a0ce 100644 (file)
@@ -332,7 +332,7 @@ _ctypes_alloc_format_string_with_shape(int ndim, const Py_ssize_t *shape,
 
 /*
   PyCStructType_Type - a meta type/class.  Creating a new class using this one as
-  __metaclass__ will call the contructor StructUnionType_new.  It replaces the
+  __metaclass__ will call the constructor StructUnionType_new.  It replaces the
   tp_dict member with a new instance of StgDict, and initializes the C
   accessible fields somehow.
 */
@@ -469,7 +469,10 @@ CDataType_from_buffer(PyObject *type, PyObject *args)
     Py_ssize_t offset = 0;
 
     StgDictObject *dict = PyType_stgdict(type);
-    assert (dict);
+    if (!dict) {
+        PyErr_SetString(PyExc_TypeError, "abstract class");
+        return NULL;
+    }
 
     if (!PyArg_ParseTuple(args, "O|n:from_buffer", &obj, &offset))
         return NULL;
@@ -537,9 +540,12 @@ CDataType_from_buffer_copy(PyObject *type, PyObject *args)
     Py_ssize_t offset = 0;
     PyObject *result;
     StgDictObject *dict = PyType_stgdict(type);
-    assert (dict);
+    if (!dict) {
+        PyErr_SetString(PyExc_TypeError, "abstract class");
+        return NULL;
+    }
 
-    if (!PyArg_ParseTuple(args, "y*|n:from_buffer", &buffer, &offset))
+    if (!PyArg_ParseTuple(args, "y*|n:from_buffer_copy", &buffer, &offset))
         return NULL;
 
     if (offset < 0) {
@@ -734,8 +740,7 @@ PyCStructType_setattro(PyObject *self, PyObject *key, PyObject *value)
         return -1;
 
     if (value && PyUnicode_Check(key) &&
-        /* XXX struni _PyUnicode_AsString can fail (also in other places)! */
-        0 == strcmp(_PyUnicode_AsString(key), "_fields_"))
+        _PyUnicode_EqualToASCIIString(key, "_fields_"))
         return PyCStructUnionType_update_stgdict(self, value, 1);
     return 0;
 }
@@ -749,7 +754,7 @@ UnionType_setattro(PyObject *self, PyObject *key, PyObject *value)
         return -1;
 
     if (PyUnicode_Check(key) &&
-        0 == strcmp(_PyUnicode_AsString(key), "_fields_"))
+        _PyUnicode_EqualToASCIIString(key, "_fields_"))
         return PyCStructUnionType_update_stgdict(self, value, 0);
     return 0;
 }
@@ -1124,7 +1129,7 @@ CharArray_get_raw(CDataObject *self)
 static PyObject *
 CharArray_get_value(CDataObject *self)
 {
-    int i;
+    Py_ssize_t i;
     char *ptr = self->b_ptr;
     for (i = 0; i < self->b_size; ++i)
         if (*ptr++ == '\0')
@@ -1180,9 +1185,9 @@ static PyGetSetDef CharArray_getsets[] = {
 static PyObject *
 WCharArray_get_value(CDataObject *self)
 {
-    unsigned int i;
+    Py_ssize_t i;
     wchar_t *ptr = (wchar_t *)self->b_ptr;
-    for (i = 0; i < self->b_size/sizeof(wchar_t); ++i)
+    for (i = 0; i < self->b_size/(Py_ssize_t)sizeof(wchar_t); ++i)
         if (*ptr++ == (wchar_t)0)
             break;
     return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i);
@@ -1211,7 +1216,7 @@ WCharArray_set_value(CDataObject *self, PyObject *value)
     wstr = PyUnicode_AsUnicodeAndSize(value, &len);
     if (wstr == NULL)
         return -1;
-    if ((unsigned)len > self->b_size/sizeof(wchar_t)) {
+    if ((size_t)len > self->b_size/sizeof(wchar_t)) {
         PyErr_SetString(PyExc_ValueError,
                         "string too long");
         result = -1;
@@ -1252,8 +1257,10 @@ add_methods(PyTypeObject *type, PyMethodDef *meth)
         descr = PyDescr_NewMethod(type, meth);
         if (descr == NULL)
             return -1;
-        if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
+        if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0) {
+            Py_DECREF(descr);
             return -1;
+        }
         Py_DECREF(descr);
     }
     return 0;
@@ -1268,8 +1275,10 @@ add_members(PyTypeObject *type, PyMemberDef *memb)
         descr = PyDescr_NewMember(type, memb);
         if (descr == NULL)
             return -1;
-        if (PyDict_SetItemString(dict, memb->name, descr) < 0)
+        if (PyDict_SetItemString(dict, memb->name, descr) < 0) {
+            Py_DECREF(descr);
             return -1;
+        }
         Py_DECREF(descr);
     }
     return 0;
@@ -1285,8 +1294,10 @@ add_getset(PyTypeObject *type, PyGetSetDef *gsp)
         descr = PyDescr_NewGetSet(type, gsp);
         if (descr == NULL)
             return -1;
-        if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
+        if (PyDict_SetItemString(dict, gsp->name, descr) < 0) {
+            Py_DECREF(descr);
             return -1;
+        }
         Py_DECREF(descr);
     }
     return 0;
@@ -1375,8 +1386,10 @@ PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
         goto error;
     }
     stgdict->shape[0] = length;
-    memmove(&stgdict->shape[1], itemdict->shape,
-        sizeof(Py_ssize_t) * (stgdict->ndim - 1));
+    if (stgdict->ndim > 1) {
+        memmove(&stgdict->shape[1], itemdict->shape,
+            sizeof(Py_ssize_t) * (stgdict->ndim - 1));
+    }
 
     itemsize = itemdict->size;
     if (length * itemsize < 0) {
@@ -1778,6 +1791,7 @@ static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject
 
     newname = PyUnicode_Concat(name, suffix);
     if (newname == NULL) {
+        Py_DECREF(swapped_args);
         return NULL;
     }
 
@@ -1797,8 +1811,10 @@ static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject
 
     stgdict = (StgDictObject *)PyObject_CallObject(
         (PyObject *)&PyCStgDict_Type, NULL);
-    if (!stgdict) /* XXX leaks result! */
+    if (!stgdict) {
+        Py_DECREF(result);
         return NULL;
+    }
 
     stgdict->ffi_type_pointer = *fmt->pffi_type;
     stgdict->align = fmt->pffi_type->alignment;
@@ -1978,8 +1994,10 @@ PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
             PyObject *meth;
             int x;
             meth = PyDescr_NewClassMethod(result, ml);
-            if (!meth)
+            if (!meth) {
+                Py_DECREF(result);
                 return NULL;
+            }
             x = PyDict_SetItemString(result->tp_dict,
                                      ml->ml_name,
                                      meth);
@@ -2159,8 +2177,10 @@ converters_from_argtypes(PyObject *ob)
 
     nArgs = PyTuple_GET_SIZE(ob);
     converters = PyTuple_New(nArgs);
-    if (!converters)
+    if (!converters) {
+        Py_DECREF(ob);
         return NULL;
+    }
 
     /* I have to check if this is correct. Using c_char, which has a size
        of 1, will be assumed to be pushed as only one byte!
@@ -4052,14 +4072,9 @@ _init_pos_args(PyObject *self, PyTypeObject *type,
         }
         val = PyTuple_GET_ITEM(args, i + index);
         if (kwds && PyDict_GetItem(kwds, name)) {
-            char *field = PyBytes_AsString(name);
-            if (field == NULL) {
-                PyErr_Clear();
-                field = "???";
-            }
             PyErr_Format(PyExc_TypeError,
-                         "duplicate values for field '%s'",
-                         field);
+                         "duplicate values for field %R",
+                         name);
             Py_DECREF(pair);
             Py_DECREF(name);
             return -1;
@@ -5128,18 +5143,18 @@ comerror_init(PyObject *self, PyObject *args, PyObject *kwds)
     int status;
 
     if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
-    return -1;
+        return -1;
 
     if (!PyArg_ParseTuple(args, "OOO:COMError", &hresult, &text, &details))
         return -1;
 
     a = PySequence_GetSlice(args, 1, PySequence_Size(args));
     if (!a)
-    return -1;
+        return -1;
     status = PyObject_SetAttrString(self, "args", a);
     Py_DECREF(a);
     if (status < 0)
-    return -1;
+        return -1;
 
     if (PyObject_SetAttrString(self, "hresult", hresult) < 0)
         return -1;
index f957e02..3c7f892 100644 (file)
@@ -26,6 +26,24 @@ _testfunc_cbk_reg_double(double a, double b, double c, double d, double e,
     return func(a*a, b*b, c*c, d*d, e*e);
 }
 
+/*
+ * This structure should be the same as in test_callbacks.py and the
+ * method test_callback_large_struct. See issues 17310 and 20160: the
+ * structure must be larger than 8 bytes long.
+ */
+
+typedef struct {
+    unsigned long first;
+    unsigned long second;
+    unsigned long third;
+} Test;
+
+EXPORT(void)
+_testfunc_cbk_large_struct(Test in, void (*func)(Test))
+{
+    func(in);
+}
+
 EXPORT(void)testfunc_array(int values[4])
 {
     printf("testfunc_array %d %d %d %d\n",
index 7cd6164..91413d7 100644 (file)
@@ -305,7 +305,7 @@ static void closure_fcn(ffi_cif *cif,
 static CThunkObject* CThunkObject_new(Py_ssize_t nArgs)
 {
     CThunkObject *p;
-    int i;
+    Py_ssize_t i;
 
     p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs);
     if (p == NULL) {
@@ -313,11 +313,13 @@ static CThunkObject* CThunkObject_new(Py_ssize_t nArgs)
         return NULL;
     }
 
-    p->pcl_exec = NULL;
     p->pcl_write = NULL;
+    p->pcl_exec = NULL;
     memset(&p->cif, 0, sizeof(p->cif));
+    p->flags = 0;
     p->converters = NULL;
     p->callable = NULL;
+    p->restype = NULL;
     p->setfunc = NULL;
     p->ffi_restype = NULL;
 
index 03a911f..abd3bc9 100644 (file)
@@ -157,8 +157,10 @@ _ctypes_get_errobj(int **pspace)
             return NULL;
         memset(space, 0, sizeof(int) * 2);
         errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
-        if (errobj == NULL)
+        if (errobj == NULL) {
+            PyMem_Free(space);
             return NULL;
+        }
         if (-1 == PyDict_SetItem(dict, error_object_name,
                                  errobj)) {
             Py_DECREF(errobj);
@@ -1668,7 +1670,9 @@ POINTER(PyObject *self, PyObject *cls)
         return result;
     }
     if (PyUnicode_CheckExact(cls)) {
-        char *name = _PyUnicode_AsString(cls);
+        const char *name = PyUnicode_AsUTF8(cls);
+        if (name == NULL)
+            return NULL;
         buf = PyMem_Malloc(strlen(name) + 3 + 1);
         if (buf == NULL)
             return PyErr_NoMemory();
@@ -1681,6 +1685,10 @@ POINTER(PyObject *self, PyObject *cls)
         if (result == NULL)
             return result;
         key = PyLong_FromVoidPtr(result);
+        if (key == NULL) {
+            Py_DECREF(result);
+            return NULL;
+        }
     } else if (PyType_Check(cls)) {
         typ = (PyTypeObject *)cls;
         buf = PyMem_Malloc(strlen(typ->tp_name) + 3 + 1);
index 8cb6d66..d666be5 100644 (file)
@@ -1246,8 +1246,7 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length)
                         "unicode string expected instead of %s instance",
                         value->ob_type->tp_name);
         return NULL;
-    } else
-        Py_INCREF(value);
+    }
 
     wstr = PyUnicode_AsUnicodeAndSize(value, &size);
     if (wstr == NULL)
@@ -1256,7 +1255,6 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length)
         PyErr_Format(PyExc_ValueError,
                      "string too long (%zd, maximum length %zd)",
                      size, length);
-        Py_DECREF(value);
         return NULL;
     } else if (size < length-1)
         /* copy terminating NUL character if there is space */
@@ -1266,6 +1264,7 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length)
         return NULL;
     }
 
+    Py_INCREF(value);
     return value;
 }
 
@@ -1292,9 +1291,7 @@ s_set(void *ptr, PyObject *value, Py_ssize_t length)
     char *data;
     Py_ssize_t size;
 
-    if(PyBytes_Check(value)) {
-        Py_INCREF(value);
-    } else {
+    if(!PyBytes_Check(value)) {
         PyErr_Format(PyExc_TypeError,
                      "expected bytes, %s found",
                      value->ob_type->tp_name);
@@ -1302,11 +1299,9 @@ s_set(void *ptr, PyObject *value, Py_ssize_t length)
     }
 
     data = PyBytes_AS_STRING(value);
-    if (!data)
-        return NULL;
     size = strlen(data); /* XXX Why not Py_SIZE(value)? */
     if (size < length) {
-        /* This will copy the leading NUL character
+        /* This will copy the terminating NUL character
          * if there is space for it.
          */
         ++size;
@@ -1314,13 +1309,11 @@ s_set(void *ptr, PyObject *value, Py_ssize_t length)
         PyErr_Format(PyExc_ValueError,
                      "bytes too long (%zd, maximum length %zd)",
                      size, length);
-        Py_DECREF(value);
         return NULL;
     }
     /* Also copy the terminating NUL character if there is space */
     memcpy((char *)ptr, data, size);
 
-    Py_DECREF(value);
     _RET(value);
 }
 
@@ -1428,9 +1421,7 @@ BSTR_set(void *ptr, PyObject *value, Py_ssize_t size)
     /* convert value into a PyUnicodeObject or NULL */
     if (Py_None == value) {
         value = NULL;
-    } else if (PyUnicode_Check(value)) {
-        Py_INCREF(value); /* for the descref below */
-    } else {
+    } else if (!PyUnicode_Check(value)) {
         PyErr_Format(PyExc_TypeError,
                         "unicode string expected instead of %s instance",
                         value->ob_type->tp_name);
@@ -1449,7 +1440,6 @@ BSTR_set(void *ptr, PyObject *value, Py_ssize_t size)
             return NULL;
         }
         bstr = SysAllocStringLen(wvalue, (unsigned)wsize);
-        Py_DECREF(value);
     } else
         bstr = NULL;
 
index 0d3f724..f2df5c0 100644 (file)
@@ -238,7 +238,7 @@ typedef struct {
  StgDictObject function to a generic one.
 
  Currently, PyCFuncPtr types have 'converters' and 'checker' entries in their
- type dict.  They are only used to cache attributes from other entries, whihc
+ type dict.  They are only used to cache attributes from other entries, which
  is wrong.
 
  One use case is the .value attribute that all simple types have.  But some
index b7586c7..1d82929 100644 (file)
@@ -378,7 +378,7 @@ ffi_prep_incoming_args_SYSV(char *stack, void **rvalue,
 
   if ( cif->rtype->type == FFI_TYPE_STRUCT ) {
     *rvalue = *(void **) argp;
-    argp += 4;
+    argp += sizeof(void *);
   }
 
   p_argv = avalue;
@@ -389,13 +389,23 @@ ffi_prep_incoming_args_SYSV(char *stack, void **rvalue,
 
       /* Align if necessary */
       if ((sizeof(char *) - 1) & (size_t) argp) {
-       argp = (char *) ALIGN(argp, sizeof(char*));
+        argp = (char *) ALIGN(argp, sizeof(char*));
       }
 
       z = (*p_arg)->size;
 
       /* because we're little endian, this is what it turns into.   */
 
+#ifdef _WIN64
+      if (z > 8) {
+        /* On Win64, if a single argument takes more than 8 bytes,
+         * then it is always passed by reference.
+         */
+        *p_argv = *((void**) argp);
+        z = 8;
+      }
+      else
+#endif
       *p_argv = (void*) argp;
 
       p_argv++;
index 96826b5..1776b79 100644 (file)
@@ -102,7 +102,7 @@ initialize_aggregate(
 /* Perform machine independent ffi_cif preparation, then call
    machine dependent routine. */
 
-#if defined(X86_DARWIN)
+#if defined(X86_DARWIN) && !defined __x86_64__
 
 static inline bool
 struct_on_stack(
@@ -125,7 +125,7 @@ struct_on_stack(
        }
 }
 
-#endif // defined(X86_DARWIN)
+#endif // defined(X86_DARWIN) && !defined __x86_64__
 
 // Arguments' ffi_type->alignment must be nonzero.
 ffi_status
index 879afb8..6c0fda9 100644 (file)
@@ -391,9 +391,11 @@ PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct
         }
         memset(stgdict->ffi_type_pointer.elements, 0,
                sizeof(ffi_type *) * (basedict->length + len + 1));
-        memcpy(stgdict->ffi_type_pointer.elements,
-               basedict->ffi_type_pointer.elements,
-               sizeof(ffi_type *) * (basedict->length));
+        if (basedict->length > 0) {
+            memcpy(stgdict->ffi_type_pointer.elements,
+                   basedict->ffi_type_pointer.elements,
+                   sizeof(ffi_type *) * (basedict->length));
+        }
         ffi_ofs = basedict->length;
     } else {
         offset = 0;
index d64bdc7..896d40d 100644 (file)
@@ -230,7 +230,7 @@ PyCurses_ConvertToChtype(PyCursesWindowObject *win, PyObject *obj, chtype *ch)
                 encoding = win->encoding;
             else
                 encoding = screen_encoding;
-            bytes = PyUnicode_AsEncodedObject(obj, encoding, NULL);
+            bytes = PyUnicode_AsEncodedString(obj, encoding, NULL);
             if (bytes == NULL)
                 return 0;
             if (PyBytes_GET_SIZE(bytes) == 1)
@@ -280,7 +280,7 @@ static int
 PyCurses_ConvertToCchar_t(PyCursesWindowObject *win, PyObject *obj,
                           chtype *ch
 #ifdef HAVE_NCURSESW
-                          , cchar_t *wch
+                          , wchar_t *wch
 #endif
                           )
 {
@@ -298,8 +298,7 @@ PyCurses_ConvertToCchar_t(PyCursesWindowObject *win, PyObject *obj,
                          PyUnicode_GET_LENGTH(obj));
             return 0;
         }
-        memset(wch->chars, 0, sizeof(wch->chars));
-        wch->chars[0] = buffer[0];
+        *wch = buffer[0];
         return 2;
 #else
         return PyCurses_ConvertToChtype(win, obj, ch);
@@ -352,7 +351,7 @@ PyCurses_ConvertToString(PyCursesWindowObject *win, PyObject *obj,
         return 2;
 #else
         assert (wstr == NULL);
-        *bytes = PyUnicode_AsEncodedObject(obj, win->encoding, NULL);
+        *bytes = PyUnicode_AsEncodedString(obj, win->encoding, NULL);
         if (*bytes == NULL)
             return 0;
         return 1;
@@ -597,7 +596,8 @@ curses_window_addch_impl(PyCursesWindowObject *self, int group_left_1, int y,
     int type;
     chtype cch;
 #ifdef HAVE_NCURSESW
-    cchar_t wch;
+    wchar_t wstr[2];
+    cchar_t wcval;
 #endif
     const char *funcname;
 
@@ -605,14 +605,15 @@ curses_window_addch_impl(PyCursesWindowObject *self, int group_left_1, int y,
       attr = A_NORMAL;
 
 #ifdef HAVE_NCURSESW
-    type = PyCurses_ConvertToCchar_t(cwself, ch, &cch, &wch);
+    type = PyCurses_ConvertToCchar_t(cwself, ch, &cch, wstr);
     if (type == 2) {
         funcname = "add_wch";
-        wch.attr = attr;
+        wstr[1] = L'\0';
+        setcchar(&wcval, wstr, attr, 0, NULL);
         if (coordinates_group)
-            rtn = mvwadd_wch(cwself->win,y,x, &wch);
+            rtn = mvwadd_wch(cwself->win,y,x, &wcval);
         else {
-            rtn = wadd_wch(cwself->win, &wch);
+            rtn = wadd_wch(cwself->win, &wcval);
         }
     }
     else
@@ -1221,6 +1222,10 @@ PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args)
     case 1:
         if (!PyArg_ParseTuple(args,"i;n", &n))
             return NULL;
+        if (n < 0) {
+            PyErr_SetString(PyExc_ValueError, "'n' must be nonnegative");
+            return NULL;
+        }
         Py_BEGIN_ALLOW_THREADS
         rtn2 = wgetnstr(self->win, rtn, Py_MIN(n, 1023));
         Py_END_ALLOW_THREADS
@@ -1239,6 +1244,10 @@ PyCursesWindow_GetStr(PyCursesWindowObject *self, PyObject *args)
     case 3:
         if (!PyArg_ParseTuple(args,"iii;y,x,n", &y, &x, &n))
             return NULL;
+        if (n < 0) {
+            PyErr_SetString(PyExc_ValueError, "'n' must be nonnegative");
+            return NULL;
+        }
 #ifdef STRICT_SYSV_CURSES
         Py_BEGIN_ALLOW_THREADS
         rtn2 = wmove(self->win,y,x)==ERR ? ERR :
@@ -1385,6 +1394,10 @@ PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args)
     case 1:
         if (!PyArg_ParseTuple(args,"i;n", &n))
             return NULL;
+        if (n < 0) {
+            PyErr_SetString(PyExc_ValueError, "'n' must be nonnegative");
+            return NULL;
+        }
         rtn2 = winnstr(self->win, rtn, Py_MIN(n, 1023));
         break;
     case 2:
@@ -1395,6 +1408,10 @@ PyCursesWindow_InStr(PyCursesWindowObject *self, PyObject *args)
     case 3:
         if (!PyArg_ParseTuple(args, "iii;y,x,n", &y, &x, &n))
             return NULL;
+        if (n < 0) {
+            PyErr_SetString(PyExc_ValueError, "'n' must be nonnegative");
+            return NULL;
+        }
         rtn2 = mvwinnstr(self->win, y, x, rtn, Py_MIN(n,1023));
         break;
     default:
index 02899e4..ea8790b 100644 (file)
@@ -430,9 +430,9 @@ Return a database object.
 [clinic start generated code]*/
 
 static PyObject *
-dbmopen_impl(PyModuleDef *module, const char *filename, const char *flags,
+dbmopen_impl(PyObject *module, const char *filename, const char *flags,
              int mode)
-/*[clinic end generated code: output=e8d4b36f25c733fd input=226334bade5764e6]*/
+/*[clinic end generated code: output=5fade8cf16e0755f input=226334bade5764e6]*/
 {
     int iflags;
 
index 112b44f..6efdc91 100644 (file)
@@ -1119,12 +1119,12 @@ context_getattr(PyObject *self, PyObject *name)
     PyObject *retval;
 
     if (PyUnicode_Check(name)) {
-        if (PyUnicode_CompareWithASCIIString(name, "traps") == 0) {
+        if (_PyUnicode_EqualToASCIIString(name, "traps")) {
             retval = ((PyDecContextObject *)self)->traps;
             Py_INCREF(retval);
             return retval;
         }
-        if (PyUnicode_CompareWithASCIIString(name, "flags") == 0) {
+        if (_PyUnicode_EqualToASCIIString(name, "flags")) {
             retval = ((PyDecContextObject *)self)->flags;
             Py_INCREF(retval);
             return retval;
@@ -1144,10 +1144,10 @@ context_setattr(PyObject *self, PyObject *name, PyObject *value)
     }
 
     if (PyUnicode_Check(name)) {
-        if (PyUnicode_CompareWithASCIIString(name, "traps") == 0) {
+        if (_PyUnicode_EqualToASCIIString(name, "traps")) {
             return context_settraps_dict(self, value);
         }
-        if (PyUnicode_CompareWithASCIIString(name, "flags") == 0) {
+        if (_PyUnicode_EqualToASCIIString(name, "flags")) {
             return context_setstatus_dict(self, value);
         }
     }
@@ -2208,6 +2208,14 @@ PyDecType_FromLongExact(PyTypeObject *type, const PyObject *pylong,
     return dec;
 }
 
+/* External C-API functions */
+static binaryfunc _py_long_multiply;
+static binaryfunc _py_long_floor_divide;
+static ternaryfunc _py_long_power;
+static unaryfunc _py_float_abs;
+static PyCFunction _py_long_bit_length;
+static PyCFunction _py_float_as_integer_ratio;
+
 /* Return a PyDecObject or a subtype from a PyFloatObject.
    Conversion is exact. */
 static PyObject *
@@ -2258,13 +2266,13 @@ PyDecType_FromFloatExact(PyTypeObject *type, PyObject *v,
     }
 
     /* absolute value of the float */
-    tmp = PyObject_CallMethod(v, "__abs__", NULL);
+    tmp = _py_float_abs(v);
     if (tmp == NULL) {
         return NULL;
     }
 
     /* float as integer ratio: numerator/denominator */
-    n_d = PyObject_CallMethod(tmp, "as_integer_ratio", NULL);
+    n_d = _py_float_as_integer_ratio(tmp, NULL);
     Py_DECREF(tmp);
     if (n_d == NULL) {
         return NULL;
@@ -2272,7 +2280,7 @@ PyDecType_FromFloatExact(PyTypeObject *type, PyObject *v,
     n = PyTuple_GET_ITEM(n_d, 0);
     d = PyTuple_GET_ITEM(n_d, 1);
 
-    tmp = PyObject_CallMethod(d, "bit_length", NULL);
+    tmp = _py_long_bit_length(d, NULL);
     if (tmp == NULL) {
         Py_DECREF(n_d);
         return NULL;
@@ -2438,14 +2446,14 @@ dectuple_as_str(PyObject *dectuple)
     tmp = PyTuple_GET_ITEM(dectuple, 2);
     if (PyUnicode_Check(tmp)) {
         /* special */
-        if (PyUnicode_CompareWithASCIIString(tmp, "F") == 0) {
+        if (_PyUnicode_EqualToASCIIString(tmp, "F")) {
             strcat(sign_special, "Inf");
             is_infinite = 1;
         }
-        else if (PyUnicode_CompareWithASCIIString(tmp, "n") == 0) {
+        else if (_PyUnicode_EqualToASCIIString(tmp, "n")) {
             strcat(sign_special, "NaN");
         }
-        else if (PyUnicode_CompareWithASCIIString(tmp, "N") == 0) {
+        else if (_PyUnicode_EqualToASCIIString(tmp, "N")) {
             strcat(sign_special, "sNaN");
         }
         else {
@@ -2630,12 +2638,18 @@ PyDecType_FromSequenceExact(PyTypeObject *type, PyObject *v,
 
 /* class method */
 static PyObject *
-dec_from_float(PyObject *dec, PyObject *pyfloat)
+dec_from_float(PyObject *type, PyObject *pyfloat)
 {
     PyObject *context;
+    PyObject *result;
 
     CURRENT_CONTEXT(context);
-    return PyDecType_FromFloatExact((PyTypeObject *)dec, pyfloat, context);
+    result = PyDecType_FromFloatExact(&PyDec_Type, pyfloat, context);
+    if (type != (PyObject *)&PyDec_Type && result != NULL) {
+        Py_SETREF(result, PyObject_CallFunctionObjArgs(type, result, NULL));
+    }
+
+    return result;
 }
 
 /* create_decimal_from_float */
@@ -5505,6 +5519,32 @@ static struct int_constmap int_constants [] = {
 #define CHECK_PTR(expr) \
     do { if ((expr) == NULL) goto error; } while (0)
 
+
+static PyCFunction
+cfunc_noargs(PyTypeObject *t, const char *name)
+{
+    struct PyMethodDef *m;
+
+    if (t->tp_methods == NULL) {
+        goto error;
+    }
+
+    for (m = t->tp_methods; m->ml_name != NULL; m++) {
+        if (strcmp(name, m->ml_name) == 0) {
+            if (!(m->ml_flags & METH_NOARGS)) {
+                goto error;
+            }
+            return m->ml_meth;
+        }
+    }
+
+error:
+    PyErr_Format(PyExc_RuntimeError,
+        "internal error: could not find method %s", name);
+    return NULL;
+}
+
+
 PyMODINIT_FUNC
 PyInit__decimal(void)
 {
@@ -5529,6 +5569,16 @@ PyInit__decimal(void)
     mpd_setminalloc(_Py_DEC_MINALLOC);
 
 
+    /* Init external C-API functions */
+    _py_long_multiply = PyLong_Type.tp_as_number->nb_multiply;
+    _py_long_floor_divide = PyLong_Type.tp_as_number->nb_floor_divide;
+    _py_long_power = PyLong_Type.tp_as_number->nb_power;
+    _py_float_abs = PyFloat_Type.tp_as_number->nb_absolute;
+    ASSIGN_PTR(_py_float_as_integer_ratio, cfunc_noargs(&PyFloat_Type,
+                                                        "as_integer_ratio"));
+    ASSIGN_PTR(_py_long_bit_length, cfunc_noargs(&PyLong_Type, "bit_length"));
+
+
     /* Init types */
     PyDec_Type.tp_base = &PyBaseObject_Type;
     PyDecContext_Type.tp_base = &PyBaseObject_Type;
index 0f1d6a1..7d50dd0 100644 (file)
@@ -652,6 +652,7 @@ static void
 element_dealloc(ElementObject* self)
 {
     PyObject_GC_UnTrack(self);
+    Py_TRASHCAN_SAFE_BEGIN(self)
 
     if (self->weakreflist != NULL)
         PyObject_ClearWeakRefs((PyObject *) self);
@@ -662,6 +663,7 @@ element_dealloc(ElementObject* self)
 
     RELEASE(sizeof(ElementObject), "destroy element");
     Py_TYPE(self)->tp_free((PyObject *)self);
+    Py_TRASHCAN_SAFE_END(self)
 }
 
 /* -------------------------------------------------------------------- */
@@ -1582,10 +1584,23 @@ _elementtree_Element_remove_impl(ElementObject *self, PyObject *subelement)
 static PyObject*
 element_repr(ElementObject* self)
 {
-    if (self->tag)
-        return PyUnicode_FromFormat("<Element %R at %p>", self->tag, self);
-    else
+    int status;
+
+    if (self->tag == NULL)
         return PyUnicode_FromFormat("<Element at %p>", self);
+
+    status = Py_ReprEnter((PyObject *)self);
+    if (status == 0) {
+        PyObject *res;
+        res = PyUnicode_FromFormat("<Element %R at %p>", self->tag, self);
+        Py_ReprLeave((PyObject *)self);
+        return res;
+    }
+    if (status > 0)
+        PyErr_Format(PyExc_RuntimeError,
+                     "reentrant call inside %s.__repr__",
+                     Py_TYPE(self)->tp_name);
+    return NULL;
 }
 
 /*[clinic input]
@@ -3673,11 +3688,11 @@ xmlparser_getattro(XMLParserObject* self, PyObject* nameobj)
 {
     if (PyUnicode_Check(nameobj)) {
         PyObject* res;
-        if (PyUnicode_CompareWithASCIIString(nameobj, "entity") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "entity"))
             res = self->entity;
-        else if (PyUnicode_CompareWithASCIIString(nameobj, "target") == 0)
+        else if (_PyUnicode_EqualToASCIIString(nameobj, "target"))
             res = self->target;
-        else if (PyUnicode_CompareWithASCIIString(nameobj, "version") == 0) {
+        else if (_PyUnicode_EqualToASCIIString(nameobj, "version")) {
             return PyUnicode_FromFormat(
                 "Expat %d.%d.%d", XML_MAJOR_VERSION,
                 XML_MINOR_VERSION, XML_MICRO_VERSION);
index 1aa4571..9c9ab5f 100644 (file)
@@ -203,40 +203,45 @@ static PyGetSetDef partial_getsetlist[] = {
 static PyObject *
 partial_repr(partialobject *pto)
 {
-    PyObject *result;
+    PyObject *result = NULL;
     PyObject *arglist;
-    PyObject *tmp;
     Py_ssize_t i, n;
     PyObject *key, *value;
+    int status;
 
-    arglist = PyUnicode_FromString("");
-    if (arglist == NULL) {
-        return NULL;
+    status = Py_ReprEnter((PyObject *)pto);
+    if (status != 0) {
+        if (status < 0)
+            return NULL;
+        return PyUnicode_FromFormat("%s(...)", Py_TYPE(pto)->tp_name);
     }
+
+    arglist = PyUnicode_FromString("");
+    if (arglist == NULL)
+        goto done;
     /* Pack positional arguments */
     assert (PyTuple_Check(pto->args));
     n = PyTuple_GET_SIZE(pto->args);
     for (i = 0; i < n; i++) {
-        tmp = PyUnicode_FromFormat("%U, %R", arglist,
-                                   PyTuple_GET_ITEM(pto->args, i));
-        Py_DECREF(arglist);
-        if (tmp == NULL)
-            return NULL;
-        arglist = tmp;
+        Py_SETREF(arglist, PyUnicode_FromFormat("%U, %R", arglist,
+                                        PyTuple_GET_ITEM(pto->args, i)));
+        if (arglist == NULL)
+            goto done;
     }
     /* Pack keyword arguments */
     assert (PyDict_Check(pto->kw));
     for (i = 0; PyDict_Next(pto->kw, &i, &key, &value);) {
-        tmp = PyUnicode_FromFormat("%U, %U=%R", arglist,
-                                    key, value);
-        Py_DECREF(arglist);
-        if (tmp == NULL)
-            return NULL;
-        arglist = tmp;
+        Py_SETREF(arglist, PyUnicode_FromFormat("%U, %U=%R", arglist,
+                                                key, value));
+        if (arglist == NULL)
+            goto done;
     }
     result = PyUnicode_FromFormat("%s(%R%U)", Py_TYPE(pto)->tp_name,
                                   pto->fn, arglist);
     Py_DECREF(arglist);
+
+ done:
+    Py_ReprLeave((PyObject *)pto);
     return result;
 }
 
@@ -776,8 +781,10 @@ infinite_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwd
     if (!key)
         return NULL;
     hash = PyObject_Hash(key);
-    if (hash == -1)
+    if (hash == -1) {
+        Py_DECREF(key);
         return NULL;
+    }
     result = _PyDict_GetItem_KnownHash(self->cache, key, hash);
     if (result) {
         Py_INCREF(result);
@@ -832,8 +839,10 @@ bounded_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds
     if (!key)
         return NULL;
     hash = PyObject_Hash(key);
-    if (hash == -1)
+    if (hash == -1) {
+        Py_DECREF(key);
         return NULL;
+    }
     link  = (lru_list_elem *)_PyDict_GetItem_KnownHash(self->cache, key, hash);
     if (link) {
         lru_cache_extricate_link(link);
index f070a14..b840bf5 100644 (file)
@@ -562,9 +562,8 @@ when the database has to be created.  It defaults to octal 0o666.
 [clinic start generated code]*/
 
 static PyObject *
-dbmopen_impl(PyModuleDef *module, const char *name, const char *flags,
-             int mode)
-/*[clinic end generated code: output=365b31415c03ccd4 input=55563cd60e51984a]*/
+dbmopen_impl(PyObject *module, const char *name, const char *flags, int mode)
+/*[clinic end generated code: output=31aa1bafdf5da688 input=55563cd60e51984a]*/
 {
     int iflags;
 
index 44765ac..ff57614 100644 (file)
@@ -21,7 +21,6 @@
 
 /* EVP is the preferred interface to hashing in OpenSSL */
 #include <openssl/evp.h>
-#include <openssl/hmac.h>
 /* We use the object interface to discover what hashes OpenSSL supports. */
 #include <openssl/objects.h>
 #include "openssl/err.h"
 #define HASH_OBJ_CONSTRUCTOR 0
 #endif
 
+#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER)
+/* OpenSSL < 1.1.0 */
+#define EVP_MD_CTX_new EVP_MD_CTX_create
+#define EVP_MD_CTX_free EVP_MD_CTX_destroy
+#define HAS_FAST_PKCS5_PBKDF2_HMAC 0
+#include <openssl/hmac.h>
+#else
+/* OpenSSL >= 1.1.0 */
+#define HAS_FAST_PKCS5_PBKDF2_HMAC 1
+#endif
+
 
 typedef struct {
     PyObject_HEAD
     PyObject            *name;  /* name of this hash algorithm */
-    EVP_MD_CTX           ctx;   /* OpenSSL message digest context */
+    EVP_MD_CTX          *ctx;   /* OpenSSL message digest context */
 #ifdef WITH_THREAD
     PyThread_type_lock   lock;  /* OpenSSL context lock */
 #endif
@@ -48,7 +58,6 @@ static PyTypeObject EVPtype;
 
 #define DEFINE_CONSTS_FOR_NEW(Name)  \
     static PyObject *CONST_ ## Name ## _name_obj = NULL; \
-    static EVP_MD_CTX CONST_new_ ## Name ## _ctx; \
     static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
 
 DEFINE_CONSTS_FOR_NEW(md5)
@@ -59,19 +68,57 @@ DEFINE_CONSTS_FOR_NEW(sha384)
 DEFINE_CONSTS_FOR_NEW(sha512)
 
 
+/* LCOV_EXCL_START */
+static PyObject *
+_setException(PyObject *exc)
+{
+    unsigned long errcode;
+    const char *lib, *func, *reason;
+
+    errcode = ERR_peek_last_error();
+    if (!errcode) {
+        PyErr_SetString(exc, "unknown reasons");
+        return NULL;
+    }
+    ERR_clear_error();
+
+    lib = ERR_lib_error_string(errcode);
+    func = ERR_func_error_string(errcode);
+    reason = ERR_reason_error_string(errcode);
+
+    if (lib && func) {
+        PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
+    }
+    else if (lib) {
+        PyErr_Format(exc, "[%s] %s", lib, reason);
+    }
+    else {
+        PyErr_SetString(exc, reason);
+    }
+    return NULL;
+}
+/* LCOV_EXCL_STOP */
+
 static EVPobject *
 newEVPobject(PyObject *name)
 {
     EVPobject *retval = (EVPobject *)PyObject_New(EVPobject, &EVPtype);
+    if (retval == NULL) {
+        return NULL;
+    }
+
+    retval->ctx = EVP_MD_CTX_new();
+    if (retval->ctx == NULL) {
+        PyErr_NoMemory();
+        return NULL;
+    }
 
     /* save the name for .name to return */
-    if (retval != NULL) {
-        Py_INCREF(name);
-        retval->name = name;
+    Py_INCREF(name);
+    retval->name = name;
 #ifdef WITH_THREAD
-        retval->lock = NULL;
+    retval->lock = NULL;
 #endif
-    }
 
     return retval;
 }
@@ -86,7 +133,7 @@ EVP_hash(EVPobject *self, const void *vp, Py_ssize_t len)
             process = MUNCH_SIZE;
         else
             process = Py_SAFE_DOWNCAST(len, Py_ssize_t, unsigned int);
-        EVP_DigestUpdate(&self->ctx, (const void*)cp, process);
+        EVP_DigestUpdate(self->ctx, (const void*)cp, process);
         len -= process;
         cp += process;
     }
@@ -101,16 +148,19 @@ EVP_dealloc(EVPobject *self)
     if (self->lock != NULL)
         PyThread_free_lock(self->lock);
 #endif
-    EVP_MD_CTX_cleanup(&self->ctx);
+    EVP_MD_CTX_free(self->ctx);
     Py_XDECREF(self->name);
     PyObject_Del(self);
 }
 
-static void locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
+static int
+locked_EVP_MD_CTX_copy(EVP_MD_CTX *new_ctx_p, EVPobject *self)
 {
+    int result;
     ENTER_HASHLIB(self);
-    EVP_MD_CTX_copy(new_ctx_p, &self->ctx);
+    result = EVP_MD_CTX_copy(new_ctx_p, self->ctx);
     LEAVE_HASHLIB(self);
+    return result;
 }
 
 /* External methods for a hash object */
@@ -126,7 +176,9 @@ EVP_copy(EVPobject *self, PyObject *unused)
     if ( (newobj = newEVPobject(self->name))==NULL)
         return NULL;
 
-    locked_EVP_MD_CTX_copy(&newobj->ctx, self);
+    if (!locked_EVP_MD_CTX_copy(newobj->ctx, self)) {
+        return _setException(PyExc_ValueError);
+    }
     return (PyObject *)newobj;
 }
 
@@ -137,16 +189,24 @@ static PyObject *
 EVP_digest(EVPobject *self, PyObject *unused)
 {
     unsigned char digest[EVP_MAX_MD_SIZE];
-    EVP_MD_CTX temp_ctx;
+    EVP_MD_CTX *temp_ctx;
     PyObject *retval;
     unsigned int digest_size;
 
-    locked_EVP_MD_CTX_copy(&temp_ctx, self);
-    digest_size = EVP_MD_CTX_size(&temp_ctx);
-    EVP_DigestFinal(&temp_ctx, digest, NULL);
+    temp_ctx = EVP_MD_CTX_new();
+    if (temp_ctx == NULL) {
+        PyErr_NoMemory();
+        return NULL;
+    }
+
+    if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
+        return _setException(PyExc_ValueError);
+    }
+    digest_size = EVP_MD_CTX_size(temp_ctx);
+    EVP_DigestFinal(temp_ctx, digest, NULL);
 
     retval = PyBytes_FromStringAndSize((const char *)digest, digest_size);
-    EVP_MD_CTX_cleanup(&temp_ctx);
+    EVP_MD_CTX_free(temp_ctx);
     return retval;
 }
 
@@ -157,15 +217,23 @@ static PyObject *
 EVP_hexdigest(EVPobject *self, PyObject *unused)
 {
     unsigned char digest[EVP_MAX_MD_SIZE];
-    EVP_MD_CTX temp_ctx;
+    EVP_MD_CTX *temp_ctx;
     unsigned int digest_size;
 
+    temp_ctx = EVP_MD_CTX_new();
+    if (temp_ctx == NULL) {
+        PyErr_NoMemory();
+        return NULL;
+    }
+
     /* Get the raw (binary) digest value */
-    locked_EVP_MD_CTX_copy(&temp_ctx, self);
-    digest_size = EVP_MD_CTX_size(&temp_ctx);
-    EVP_DigestFinal(&temp_ctx, digest, NULL);
+    if (!locked_EVP_MD_CTX_copy(temp_ctx, self)) {
+        return _setException(PyExc_ValueError);
+    }
+    digest_size = EVP_MD_CTX_size(temp_ctx);
+    EVP_DigestFinal(temp_ctx, digest, NULL);
 
-    EVP_MD_CTX_cleanup(&temp_ctx);
+    EVP_MD_CTX_free(temp_ctx);
 
     return _Py_strhex((const char *)digest, digest_size);
 }
@@ -219,7 +287,7 @@ static PyObject *
 EVP_get_block_size(EVPobject *self, void *closure)
 {
     long block_size;
-    block_size = EVP_MD_CTX_block_size(&self->ctx);
+    block_size = EVP_MD_CTX_block_size(self->ctx);
     return PyLong_FromLong(block_size);
 }
 
@@ -227,7 +295,7 @@ static PyObject *
 EVP_get_digest_size(EVPobject *self, void *closure)
 {
     long size;
-    size = EVP_MD_CTX_size(&self->ctx);
+    size = EVP_MD_CTX_size(self->ctx);
     return PyLong_FromLong(size);
 }
 
@@ -288,7 +356,7 @@ EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
             PyBuffer_Release(&view);
         return -1;
     }
-    EVP_DigestInit(&self->ctx, digest);
+    EVP_DigestInit(self->ctx, digest);
 
     self->name = name_obj;
     Py_INCREF(self->name);
@@ -385,9 +453,9 @@ EVPnew(PyObject *name_obj,
         return NULL;
 
     if (initial_ctx) {
-        EVP_MD_CTX_copy(&self->ctx, initial_ctx);
+        EVP_MD_CTX_copy(self->ctx, initial_ctx);
     } else {
-        EVP_DigestInit(&self->ctx, digest);
+        EVP_DigestInit(self->ctx, digest);
     }
 
     if (cp && len) {
@@ -453,6 +521,7 @@ EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
 
 #define PY_PBKDF2_HMAC 1
 
+#if !HAS_FAST_PKCS5_PBKDF2_HMAC
 /* Improved implementation of PKCS5_PBKDF2_HMAC()
  *
  * PKCS5_PBKDF2_HMAC_fast() hashes the password exactly one time instead of
@@ -534,37 +603,8 @@ PKCS5_PBKDF2_HMAC_fast(const char *pass, int passlen,
     HMAC_CTX_cleanup(&hctx_tpl);
     return 1;
 }
+#endif
 
-/* LCOV_EXCL_START */
-static PyObject *
-_setException(PyObject *exc)
-{
-    unsigned long errcode;
-    const char *lib, *func, *reason;
-
-    errcode = ERR_peek_last_error();
-    if (!errcode) {
-        PyErr_SetString(exc, "unknown reasons");
-        return NULL;
-    }
-    ERR_clear_error();
-
-    lib = ERR_lib_error_string(errcode);
-    func = ERR_func_error_string(errcode);
-    reason = ERR_reason_error_string(errcode);
-
-    if (lib && func) {
-        PyErr_Format(exc, "[%s: %s] %s", lib, func, reason);
-    }
-    else if (lib) {
-        PyErr_Format(exc, "[%s] %s", lib, reason);
-    }
-    else {
-        PyErr_SetString(exc, reason);
-    }
-    return NULL;
-}
-/* LCOV_EXCL_STOP */
 
 PyDoc_STRVAR(pbkdf2_hmac__doc__,
 "pbkdf2_hmac(hash_name, password, salt, iterations, dklen=None) -> key\n\
@@ -646,10 +686,17 @@ pbkdf2_hmac(PyObject *self, PyObject *args, PyObject *kwdict)
     key = PyBytes_AS_STRING(key_obj);
 
     Py_BEGIN_ALLOW_THREADS
+#if HAS_FAST_PKCS5_PBKDF2_HMAC
+    retval = PKCS5_PBKDF2_HMAC((char*)password.buf, (int)password.len,
+                               (unsigned char *)salt.buf, (int)salt.len,
+                               iterations, digest, dklen,
+                               (unsigned char *)key);
+#else
     retval = PKCS5_PBKDF2_HMAC_fast((char*)password.buf, (int)password.len,
                                     (unsigned char *)salt.buf, (int)salt.len,
                                     iterations, digest, dklen,
                                     (unsigned char *)key);
+#endif
     Py_END_ALLOW_THREADS
 
     if (!retval) {
@@ -724,7 +771,7 @@ generate_hash_name_list(void)
 /*
  *  This macro generates constructor function definitions for specific
  *  hash algorithms.  These constructors are much faster than calling
- *  the generic one passing it a python string and are noticably
+ *  the generic one passing it a python string and are noticeably
  *  faster than calling a python new() wrapper.  Thats important for
  *  code that wants to make hashes of a bunch of small strings.
  */
@@ -768,7 +815,7 @@ generate_hash_name_list(void)
     if (CONST_ ## NAME ## _name_obj == NULL) { \
         CONST_ ## NAME ## _name_obj = PyUnicode_FromString(#NAME); \
         if (EVP_get_digestbyname(#NAME)) { \
-            CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
+            CONST_new_ ## NAME ## _ctx_p = EVP_MD_CTX_new(); \
             EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
         } \
     } \
index ec68170..e9f22af 100644 (file)
@@ -227,10 +227,10 @@ opened in a binary mode.
 [clinic start generated code]*/
 
 static PyObject *
-_io_open_impl(PyModuleDef *module, PyObject *file, const char *mode,
+_io_open_impl(PyObject *module, PyObject *file, const char *mode,
               int buffering, const char *encoding, const char *errors,
               const char *newline, int closefd, PyObject *opener)
-/*[clinic end generated code: output=7615d0d746eb14d2 input=f4e1ca75223987bc]*/
+/*[clinic end generated code: output=aefafc4ce2b46dc0 input=f4e1ca75223987bc]*/
 {
     unsigned i;
 
@@ -654,7 +654,7 @@ PyInit__io(void)
     /* UnsupportedOperation inherits from ValueError and IOError */
     state->unsupported_operation = PyObject_CallFunction(
         (PyObject *)&PyType_Type, "s(OO){}",
-        "UnsupportedOperation", PyExc_ValueError, PyExc_IOError);
+        "UnsupportedOperation", PyExc_OSError, PyExc_ValueError);
     if (state->unsupported_operation == NULL)
         goto fail;
     Py_INCREF(state->unsupported_operation);
index a3abb93..6c88e32 100644 (file)
@@ -130,12 +130,12 @@ PyDoc_STRVAR(_io_open__doc__,
     {"open", (PyCFunction)_io_open, METH_VARARGS|METH_KEYWORDS, _io_open__doc__},
 
 static PyObject *
-_io_open_impl(PyModuleDef *module, PyObject *file, const char *mode,
+_io_open_impl(PyObject *module, PyObject *file, const char *mode,
               int buffering, const char *encoding, const char *errors,
               const char *newline, int closefd, PyObject *opener);
 
 static PyObject *
-_io_open(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_io_open(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"file", "mode", "buffering", "encoding", "errors", "newline", "closefd", "opener", NULL};
@@ -156,4 +156,4 @@ _io_open(PyModuleDef *module, PyObject *args, PyObject *kwargs)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=97cdc09bf68a8064 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=bc2c003cb7daeafe input=a9049054013a1b77]*/
index 212b0dd..57541a8 100644 (file)
@@ -90,7 +90,7 @@ iobase_unsupported(const char *message)
     return NULL;
 }
 
-/* Positionning */
+/* Positioning */
 
 PyDoc_STRVAR(iobase_seek_doc,
     "Change stream position.\n"
index 063caa6..46c99b5 100644 (file)
@@ -1023,7 +1023,7 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
         else if (PyUnicode_Check(res)) {
             encodefuncentry *e = encodefuncs;
             while (e->name != NULL) {
-                if (!PyUnicode_CompareWithASCIIString(res, e->name)) {
+                if (_PyUnicode_EqualToASCIIString(res, e->name)) {
                     self->encodefunc = e->encodefunc;
                     break;
                 }
@@ -1103,7 +1103,7 @@ _io_TextIOWrapper___init___impl(textio *self, PyObject *buffer,
 }
 
 static int
-_textiowrapper_clear(textio *self)
+textiowrapper_clear(textio *self)
 {
     self->ok = 0;
     Py_CLEAR(self->buffer);
@@ -1116,6 +1116,8 @@ _textiowrapper_clear(textio *self)
     Py_CLEAR(self->snapshot);
     Py_CLEAR(self->errors);
     Py_CLEAR(self->raw);
+
+    Py_CLEAR(self->dict);
     return 0;
 }
 
@@ -1125,11 +1127,11 @@ textiowrapper_dealloc(textio *self)
     self->finalizing = 1;
     if (_PyIOBase_finalize((PyObject *) self) < 0)
         return;
-    _textiowrapper_clear(self);
+    self->ok = 0;
     _PyObject_GC_UNTRACK(self);
     if (self->weakreflist != NULL)
         PyObject_ClearWeakRefs((PyObject *)self);
-    Py_CLEAR(self->dict);
+    textiowrapper_clear(self);
     Py_TYPE(self)->tp_free((PyObject *)self);
 }
 
@@ -1151,15 +1153,6 @@ textiowrapper_traverse(textio *self, visitproc visit, void *arg)
     return 0;
 }
 
-static int
-textiowrapper_clear(textio *self)
-{
-    if (_textiowrapper_clear(self) < 0)
-        return -1;
-    Py_CLEAR(self->dict);
-    return 0;
-}
-
 static PyObject *
 textiowrapper_closed_get(textio *self, void *context);
 
index b1d6add..b1307ef 100644 (file)
@@ -54,9 +54,10 @@ copy_grouping(char* s)
     int i;
     PyObject *result, *val = NULL;
 
-    if (s[0] == '\0')
+    if (s[0] == '\0') {
         /* empty string: no grouping at all */
         return PyList_New(0);
+    }
 
     for (i = 0; s[i] != '\0' && s[i] != CHAR_MAX; i++)
         ; /* nothing */
index 66e534f..7876e71 100644 (file)
@@ -185,7 +185,7 @@ normalizeUserObj(PyObject *obj)
             }
         }
         if (modname != NULL) {
-            if (PyUnicode_CompareWithASCIIString(modname, "builtins") != 0) {
+            if (!_PyUnicode_EqualToASCIIString(modname, "builtins")) {
                 PyObject *result;
                 result = PyUnicode_FromFormat("<%U.%s>", modname,
                                               fn->m_ml->ml_name);
index 846dc0e..e7b1ed9 100644 (file)
@@ -527,6 +527,8 @@ compress(Compressor *c, uint8_t *data, size_t len, lzma_action action)
         Py_BEGIN_ALLOW_THREADS
         lzret = lzma_code(&c->lzs, action);
         data_size = (char *)c->lzs.next_out - PyBytes_AS_STRING(result);
+        if (lzret == LZMA_BUF_ERROR && len == 0 && c->lzs.avail_out > 0)
+            lzret = LZMA_OK; /* That wasn't a real error */
         Py_END_ALLOW_THREADS
         if (catch_lzma_error(lzret))
             goto error;
@@ -906,6 +908,9 @@ decompress_buf(Decompressor *d, Py_ssize_t max_length)
     PyObject *result;
     lzma_stream *lzs = &d->lzs;
 
+    if (lzs->avail_in == 0)
+        return PyBytes_FromStringAndSize(NULL, 0);
+
     if (max_length < 0 || max_length >= INITIAL_BUFFER_SIZE)
         result = PyBytes_FromStringAndSize(NULL, INITIAL_BUFFER_SIZE);
     else
@@ -1005,8 +1010,10 @@ decompress(Decompressor *d, uint8_t *data, size_t len, Py_ssize_t max_length)
     }
 
     result = decompress_buf(d, max_length);
-    if(result == NULL)
+    if (result == NULL) {
+        lzs->next_in = NULL;
         return NULL;
+    }
 
     if (d->eof) {
         d->needs_input = 0;
@@ -1342,8 +1349,8 @@ Always returns True for CHECK_NONE and CHECK_CRC32.
 [clinic start generated code]*/
 
 static PyObject *
-_lzma_is_check_supported_impl(PyModuleDef *module, int check_id)
-/*[clinic end generated code: output=bb828e90e00ad96e input=5518297b97b2318f]*/
+_lzma_is_check_supported_impl(PyObject *module, int check_id)
+/*[clinic end generated code: output=e4f14ba3ce2ad0a5 input=5518297b97b2318f]*/
 {
     return PyBool_FromLong(lzma_check_is_supported(check_id));
 }
@@ -1360,8 +1367,8 @@ The result does not include the filter ID itself, only the options.
 [clinic start generated code]*/
 
 static PyObject *
-_lzma__encode_filter_properties_impl(PyModuleDef *module, lzma_filter filter)
-/*[clinic end generated code: output=b5fe690acd6b61d1 input=d4c64f1b557c77d4]*/
+_lzma__encode_filter_properties_impl(PyObject *module, lzma_filter filter)
+/*[clinic end generated code: output=5c93c8e14e7be5a8 input=d4c64f1b557c77d4]*/
 {
     lzma_ret lzret;
     uint32_t encoded_size;
@@ -1400,9 +1407,9 @@ The result does not include the filter ID itself, only the options.
 [clinic start generated code]*/
 
 static PyObject *
-_lzma__decode_filter_properties_impl(PyModuleDef *module, lzma_vli filter_id,
+_lzma__decode_filter_properties_impl(PyObject *module, lzma_vli filter_id,
                                      Py_buffer *encoded_props)
-/*[clinic end generated code: output=af248f570746668b input=246410800782160c]*/
+/*[clinic end generated code: output=714fd2ef565d5c60 input=246410800782160c]*/
 {
     lzma_filter filter;
     lzma_ret lzret;
index de85a90..cea962a 100644 (file)
@@ -114,6 +114,9 @@ semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
         assert(sigint_event != NULL);
         handles[nhandles++] = sigint_event;
     }
+    else {
+        sigint_event = NULL;
+    }
 
     /* do the wait */
     Py_BEGIN_ALLOW_THREADS
index 663bb21..f9c1c01 100644 (file)
@@ -20,8 +20,8 @@ Compute the stack effect of the opcode.
 [clinic start generated code]*/
 
 static int
-_opcode_stack_effect_impl(PyModuleDef *module, int opcode, PyObject *oparg)
-/*[clinic end generated code: output=1fcafd5596c6b050 input=2d0a9ee53c0418f5]*/
+_opcode_stack_effect_impl(PyObject *module, int opcode, PyObject *oparg)
+/*[clinic end generated code: output=ad39467fa3ad22ce input=2d0a9ee53c0418f5]*/
 {
     int effect;
     int oparg_int = 0;
index eb4f3a3..dfff1d2 100644 (file)
@@ -931,7 +931,7 @@ static PyObject *
 methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
     methodcallerobject *mc;
-    PyObject *name, *newargs;
+    PyObject *name;
 
     if (PyTuple_GET_SIZE(args) < 1) {
         PyErr_SetString(PyExc_TypeError, "methodcaller needs at least "
@@ -951,13 +951,7 @@ methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     if (mc == NULL)
         return NULL;
 
-    newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
-    if (newargs == NULL) {
-        Py_DECREF(mc);
-        return NULL;
-    }
-    mc->args = newargs;
-
+    name = PyTuple_GET_ITEM(args, 0);
     Py_INCREF(name);
     PyUnicode_InternInPlace(&name);
     mc->name = name;
@@ -965,6 +959,12 @@ methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     Py_XINCREF(kwds);
     mc->kwds = kwds;
 
+    mc->args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
+    if (mc->args == NULL) {
+        Py_DECREF(mc);
+        return NULL;
+    }
+
     PyObject_GC_Track(mc);
     return (PyObject *)mc;
 }
index e52da37..ac7f5c4 100644 (file)
@@ -1675,7 +1675,7 @@ whichmodule(PyObject *global, PyObject *dotted_path)
     while (PyDict_Next(modules_dict, &i, &module_name, &module)) {
         PyObject *candidate;
         if (PyUnicode_Check(module_name) &&
-            !PyUnicode_CompareWithASCIIString(module_name, "__main__"))
+            _PyUnicode_EqualToASCIIString(module_name, "__main__"))
             continue;
         if (module == Py_None)
             continue;
@@ -3406,26 +3406,30 @@ save_pers(PicklerObject *self, PyObject *obj, PyObject *func)
                 goto error;
         }
         else {
-            PyObject *pid_str = NULL;
-            char *pid_ascii_bytes;
-            Py_ssize_t size;
+            PyObject *pid_str;
 
             pid_str = PyObject_Str(pid);
             if (pid_str == NULL)
                 goto error;
 
-            /* XXX: Should it check whether the persistent id only contains
-               ASCII characters? And what if the pid contains embedded
+            /* XXX: Should it check whether the pid contains embedded
                newlines? */
-            pid_ascii_bytes = _PyUnicode_AsStringAndSize(pid_str, &size);
-            Py_DECREF(pid_str);
-            if (pid_ascii_bytes == NULL)
+            if (!PyUnicode_IS_ASCII(pid_str)) {
+                PyErr_SetString(_Pickle_GetGlobalState()->PicklingError,
+                                "persistent IDs in protocol 0 must be "
+                                "ASCII strings");
+                Py_DECREF(pid_str);
                 goto error;
+            }
 
             if (_Pickler_Write(self, &persid_op, 1) < 0 ||
-                _Pickler_Write(self, pid_ascii_bytes, size) < 0 ||
-                _Pickler_Write(self, "\n", 1) < 0)
+                _Pickler_Write(self, PyUnicode_DATA(pid_str),
+                               PyUnicode_GET_LENGTH(pid_str)) < 0 ||
+                _Pickler_Write(self, "\n", 1) < 0) {
+                Py_DECREF(pid_str);
                 goto error;
+            }
+            Py_DECREF(pid_str);
         }
         status = 1;
     }
@@ -5389,9 +5393,15 @@ load_persid(UnpicklerObject *self)
         if (len < 1)
             return bad_readline();
 
-        pid = PyBytes_FromStringAndSize(s, len - 1);
-        if (pid == NULL)
+        pid = PyUnicode_DecodeASCII(s, len - 1, "strict");
+        if (pid == NULL) {
+            if (PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
+                PyErr_SetString(_Pickle_GetGlobalState()->UnpicklingError,
+                                "persistent IDs in protocol 0 must be "
+                                "ASCII strings");
+            }
             return -1;
+        }
 
         /* This does not leak since _Pickle_FastCall() steals the reference
            to pid first. */
@@ -6961,9 +6971,9 @@ to map the new Python 3 names to the old module names used in Python
 [clinic start generated code]*/
 
 static PyObject *
-_pickle_dump_impl(PyModuleDef *module, PyObject *obj, PyObject *file,
+_pickle_dump_impl(PyObject *module, PyObject *obj, PyObject *file,
                   PyObject *protocol, int fix_imports)
-/*[clinic end generated code: output=0de7dff89c406816 input=830f8a64cef6f042]*/
+/*[clinic end generated code: output=a4774d5fde7d34de input=830f8a64cef6f042]*/
 {
     PicklerObject *pickler = _Pickler_New();
 
@@ -7015,9 +7025,9 @@ Python 2, so that the pickle data stream is readable with Python 2.
 [clinic start generated code]*/
 
 static PyObject *
-_pickle_dumps_impl(PyModuleDef *module, PyObject *obj, PyObject *protocol,
+_pickle_dumps_impl(PyObject *module, PyObject *obj, PyObject *protocol,
                    int fix_imports)
-/*[clinic end generated code: output=daa380db56fe07b9 input=293dbeda181580b7]*/
+/*[clinic end generated code: output=d75d5cda456fd261 input=293dbeda181580b7]*/
 {
     PyObject *result;
     PicklerObject *pickler = _Pickler_New();
@@ -7076,9 +7086,9 @@ string instances as bytes objects.
 [clinic start generated code]*/
 
 static PyObject *
-_pickle_load_impl(PyModuleDef *module, PyObject *file, int fix_imports,
+_pickle_load_impl(PyObject *module, PyObject *file, int fix_imports,
                   const char *encoding, const char *errors)
-/*[clinic end generated code: output=798f1c57cb2b4eb1 input=01b44dd3fc07afa7]*/
+/*[clinic end generated code: output=69e298160285199e input=01b44dd3fc07afa7]*/
 {
     PyObject *result;
     UnpicklerObject *unpickler = _Unpickler_New();
@@ -7130,9 +7140,9 @@ string instances as bytes objects.
 [clinic start generated code]*/
 
 static PyObject *
-_pickle_loads_impl(PyModuleDef *module, PyObject *data, int fix_imports,
+_pickle_loads_impl(PyObject *module, PyObject *data, int fix_imports,
                    const char *encoding, const char *errors)
-/*[clinic end generated code: output=61e9cdb01e36a736 input=70605948a719feb9]*/
+/*[clinic end generated code: output=1e7cb2343f2c440f input=70605948a719feb9]*/
 {
     PyObject *result;
     UnpicklerObject *unpickler = _Unpickler_New();
index 8bedab5..c0240e2 100644 (file)
@@ -522,7 +522,7 @@ error:
         char *cur;
         _Py_write_noraise(errpipe_write, "OSError:", 8);
         cur = hex_errno + sizeof(hex_errno);
-        while (saved_errno != 0 && cur > hex_errno) {
+        while (saved_errno != 0 && cur != hex_errno) {
             *--cur = Py_hexdigits[saved_errno % 16];
             saved_errno /= 16;
         }
index 7570624..70d0995 100644 (file)
 
 _Py_IDENTIFIER(cursor);
 
+static const char * const begin_statements[] = {
+    "BEGIN ",
+    "BEGIN DEFERRED",
+    "BEGIN IMMEDIATE",
+    "BEGIN EXCLUSIVE",
+    NULL
+};
+
 static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level);
 static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
 
@@ -164,6 +172,10 @@ int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject
 #ifdef WITH_THREAD
     self->thread_ident = PyThread_get_thread_ident();
 #endif
+    if (!check_same_thread && sqlite3_libversion_number() < 3003001) {
+        PyErr_SetString(pysqlite_NotSupportedError, "shared connections not available");
+        return -1;
+    }
     self->check_same_thread = check_same_thread;
 
     self->function_pinboard = PyDict_New();
@@ -254,9 +266,6 @@ void pysqlite_connection_dealloc(pysqlite_Connection* self)
         Py_END_ALLOW_THREADS
     }
 
-    if (self->begin_statement) {
-        PyMem_Free(self->begin_statement);
-    }
     Py_XDECREF(self->isolation_level);
     Py_XDECREF(self->function_pinboard);
     Py_XDECREF(self->row_factory);
@@ -296,7 +305,7 @@ error:
 
 PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
 {
-    static char *kwlist[] = {"factory", NULL, NULL};
+    static char *kwlist[] = {"factory", NULL};
     PyObject* factory = NULL;
     PyObject* cursor;
 
@@ -313,7 +322,16 @@ PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args,
         factory = (PyObject*)&pysqlite_CursorType;
     }
 
-    cursor = PyObject_CallFunction(factory, "O", self);
+    cursor = PyObject_CallFunctionObjArgs(factory, (PyObject *)self, NULL);
+    if (cursor == NULL)
+        return NULL;
+    if (!PyObject_TypeCheck(cursor, &pysqlite_CursorType)) {
+        PyErr_Format(PyExc_TypeError,
+                     "factory must return a cursor, not %.100s",
+                     Py_TYPE(cursor)->tp_name);
+        Py_DECREF(cursor);
+        return NULL;
+    }
 
     _pysqlite_drop_unused_cursor_references(self);
 
@@ -422,7 +440,6 @@ PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
     }
 
     if (self->inTransaction) {
-        pysqlite_do_all_statements(self, ACTION_RESET, 0);
 
         Py_BEGIN_ALLOW_THREADS
         rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
@@ -1171,59 +1188,48 @@ static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self
 
 static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
 {
-    PyObject* res;
-    PyObject* begin_statement;
-    static PyObject* begin_word;
-
-    Py_XDECREF(self->isolation_level);
-
-    if (self->begin_statement) {
-        PyMem_Free(self->begin_statement);
-        self->begin_statement = NULL;
-    }
-
     if (isolation_level == Py_None) {
-        Py_INCREF(Py_None);
-        self->isolation_level = Py_None;
-
-        res = pysqlite_connection_commit(self, NULL);
+        PyObject *res = pysqlite_connection_commit(self, NULL);
         if (!res) {
             return -1;
         }
         Py_DECREF(res);
 
+        self->begin_statement = NULL;
         self->inTransaction = 0;
     } else {
-        const char *statement;
-        Py_ssize_t size;
-
-        Py_INCREF(isolation_level);
-        self->isolation_level = isolation_level;
-
-        if (!begin_word) {
-            begin_word = PyUnicode_FromString("BEGIN ");
-            if (!begin_word) return -1;
-        }
-        begin_statement = PyUnicode_Concat(begin_word, isolation_level);
-        if (!begin_statement) {
+        const char * const *candidate;
+        PyObject *uppercase_level;
+        _Py_IDENTIFIER(upper);
+
+        if (!PyUnicode_Check(isolation_level)) {
+            PyErr_Format(PyExc_TypeError,
+                         "isolation_level must be a string or None, not %.100s",
+                         Py_TYPE(isolation_level)->tp_name);
             return -1;
         }
 
-        statement = _PyUnicode_AsStringAndSize(begin_statement, &size);
-        if (!statement) {
-            Py_DECREF(begin_statement);
+        uppercase_level = _PyObject_CallMethodIdObjArgs(
+                        (PyObject *)&PyUnicode_Type, &PyId_upper,
+                        isolation_level, NULL);
+        if (!uppercase_level) {
             return -1;
         }
-        self->begin_statement = PyMem_Malloc(size + 2);
-        if (!self->begin_statement) {
-            Py_DECREF(begin_statement);
+        for (candidate = begin_statements; *candidate; candidate++) {
+            if (_PyUnicode_EqualToASCIIString(uppercase_level, *candidate + 6))
+                break;
+        }
+        Py_DECREF(uppercase_level);
+        if (!*candidate) {
+            PyErr_SetString(PyExc_ValueError,
+                            "invalid value for isolation_level");
             return -1;
         }
-
-        strcpy(self->begin_statement, statement);
-        Py_DECREF(begin_statement);
+        self->begin_statement = *candidate;
     }
 
+    Py_INCREF(isolation_level);
+    Py_XSETREF(self->isolation_level, isolation_level);
     return 0;
 }
 
@@ -1517,11 +1523,13 @@ pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
         goto finally;
     }
 
-    if (!PyArg_ParseTuple(args, "O!O:create_collation(name, callback)", &PyUnicode_Type, &name, &callable)) {
+    if (!PyArg_ParseTuple(args, "UO:create_collation(name, callback)",
+                          &name, &callable)) {
         goto finally;
     }
 
-    uppercase_name = _PyObject_CallMethodId(name, &PyId_upper, "");
+    uppercase_name = _PyObject_CallMethodIdObjArgs((PyObject *)&PyUnicode_Type,
+                                                   &PyId_upper, name, NULL);
     if (!uppercase_name) {
         goto finally;
     }
index fbd9063..adbfb54 100644 (file)
@@ -55,9 +55,8 @@ typedef struct
     /* None for autocommit, otherwise a PyUnicode with the isolation level */
     PyObject* isolation_level;
 
-    /* NULL for autocommit, otherwise a string with the BEGIN statement; will be
-     * freed in connection destructor */
-    char* begin_statement;
+    /* NULL for autocommit, otherwise a string with the BEGIN statement */
+    const char* begin_statement;
 
     /* 1 if a check should be performed for each API call if the connection is
      * used from the same thread it was created in */
index 300da28..e1676de 100644 (file)
@@ -646,12 +646,11 @@ PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject*
             goto error;
         }
 
-        if (rc == SQLITE_ROW || (rc == SQLITE_DONE && statement_type == STATEMENT_SELECT)) {
-            if (self->description == Py_None) {
-                Py_BEGIN_ALLOW_THREADS
-                numcols = sqlite3_column_count(self->statement->st);
-                Py_END_ALLOW_THREADS
-
+        if (rc == SQLITE_ROW || rc == SQLITE_DONE) {
+            Py_BEGIN_ALLOW_THREADS
+            numcols = sqlite3_column_count(self->statement->st);
+            Py_END_ALLOW_THREADS
+            if (self->description == Py_None && numcols > 0) {
                 Py_SETREF(self->description, PyTuple_New(numcols));
                 if (!self->description) {
                     goto error;
index b51724b..0fb5a55 100644 (file)
@@ -42,7 +42,7 @@ extern PyObject* pysqlite_NotSupportedError;
 extern PyObject* time_time;
 extern PyObject* time_sleep;
 
-/* A dictionary, mapping colum types (INTEGER, VARCHAR, etc.) to converter
+/* A dictionary, mapping column types (INTEGER, VARCHAR, etc.) to converter
  * functions, that convert the SQL value to the appropriate Python value.
  * The key is uppercase.
  */
index 150229d..09b5835 100644 (file)
@@ -278,8 +278,8 @@ _sre.getcodesize -> int
 [clinic start generated code]*/
 
 static int
-_sre_getcodesize_impl(PyModuleDef *module)
-/*[clinic end generated code: output=794f1f98ef4883e5 input=bd6f6ecf4916bb2b]*/
+_sre_getcodesize_impl(PyObject *module)
+/*[clinic end generated code: output=e0db7ce34a6dd7b1 input=bd6f6ecf4916bb2b]*/
 {
     return sizeof(SRE_CODE);
 }
@@ -294,8 +294,8 @@ _sre.getlower -> int
 [clinic start generated code]*/
 
 static int
-_sre_getlower_impl(PyModuleDef *module, int character, int flags)
-/*[clinic end generated code: output=5fc3616ae2a4c306 input=087d2f1c44bbca6f]*/
+_sre_getlower_impl(PyObject *module, int character, int flags)
+/*[clinic end generated code: output=47eebc4c1214feb5 input=087d2f1c44bbca6f]*/
 {
     if (flags & SRE_FLAG_LOCALE)
         return sre_lower_locale(character);
@@ -1454,10 +1454,10 @@ _sre.compile
 [clinic start generated code]*/
 
 static PyObject *
-_sre_compile_impl(PyModuleDef *module, PyObject *pattern, int flags,
+_sre_compile_impl(PyObject *module, PyObject *pattern, int flags,
                   PyObject *code, Py_ssize_t groups, PyObject *groupindex,
                   PyObject *indexgroup)
-/*[clinic end generated code: output=3004b293730bf309 input=7d059ec8ae1edb85]*/
+/*[clinic end generated code: output=ef9c2b3693776404 input=7d059ec8ae1edb85]*/
 {
     /* "compile" pattern descriptor to pattern object */
 
@@ -2196,10 +2196,8 @@ _sre_SRE_Match_groupdict_impl(MatchObject *self, PyObject *default_value)
         if (!key)
             goto failed;
         value = match_getslice(self, key, default_value);
-        if (!value) {
-            Py_DECREF(key);
+        if (!value)
             goto failed;
-        }
         status = PyDict_SetItem(result, key, value);
         Py_DECREF(value);
         if (status < 0)
index 1117b55..a79c3a8 100644 (file)
@@ -55,6 +55,14 @@ static PySocketModule_APIObject PySocketModule;
 #include <sys/poll.h>
 #endif
 
+/* Don't warn about deprecated functions */
+#ifdef __GNUC__
+#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
+#endif
+#ifdef __clang__
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
 /* Include OpenSSL header files */
 #include "openssl/rsa.h"
 #include "openssl/crypto.h"
@@ -91,6 +99,10 @@ struct py_ssl_library_code {
 /* Include generated data (error codes) */
 #include "_ssl_data.h"
 
+#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
+#  define OPENSSL_VERSION_1_1 1
+#endif
+
 /* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
     http://www.openssl.org/news/changelog.html
  */
@@ -113,6 +125,71 @@ struct py_ssl_library_code {
 # define HAVE_ALPN
 #endif
 
+#ifndef INVALID_SOCKET /* MS defines this */
+#define INVALID_SOCKET (-1)
+#endif
+
+#ifdef OPENSSL_VERSION_1_1
+/* OpenSSL 1.1.0+ */
+#ifndef OPENSSL_NO_SSL2
+#define OPENSSL_NO_SSL2
+#endif
+#else /* OpenSSL < 1.1.0 */
+#if defined(WITH_THREAD)
+#define HAVE_OPENSSL_CRYPTO_LOCK
+#endif
+
+#define TLS_method SSLv23_method
+
+static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
+{
+    return ne->set;
+}
+
+#ifndef OPENSSL_NO_COMP
+static int COMP_get_type(const COMP_METHOD *meth)
+{
+    return meth->type;
+}
+#endif
+
+static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
+{
+    return ctx->default_passwd_callback;
+}
+
+static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
+{
+    return ctx->default_passwd_callback_userdata;
+}
+
+static int X509_OBJECT_get_type(X509_OBJECT *x)
+{
+    return x->type;
+}
+
+static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
+{
+    return x->data.x509;
+}
+
+static int BIO_up_ref(BIO *b)
+{
+    CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
+    return 1;
+}
+
+static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
+    return store->objs;
+}
+
+static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
+{
+    return store->param;
+}
+#endif /* OpenSSL < 1.1.0 or LibreSSL */
+
+
 enum py_ssl_error {
     /* these mirror ssl.h */
     PY_SSL_ERROR_NONE,
@@ -143,7 +220,7 @@ enum py_ssl_cert_requirements {
 enum py_ssl_version {
     PY_SSL_VERSION_SSL2,
     PY_SSL_VERSION_SSL3=1,
-    PY_SSL_VERSION_SSL23,
+    PY_SSL_VERSION_TLS,
 #if HAVE_TLSv1_2
     PY_SSL_VERSION_TLS1,
     PY_SSL_VERSION_TLS1_1,
@@ -483,7 +560,6 @@ newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
 {
     PySSLSocket *self;
     SSL_CTX *ctx = sslctx->ctx;
-    PyObject *hostname;
     long mode;
 
     self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
@@ -497,16 +573,16 @@ newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
     self->shutdown_seen_zero = 0;
     self->handshake_done = 0;
     self->owner = NULL;
+    self->server_hostname = NULL;
     if (server_hostname != NULL) {
-        hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
-                                   "idna", "strict");
+        PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
+                                              "idna", "strict");
         if (hostname == NULL) {
             Py_DECREF(self);
             return NULL;
         }
         self->server_hostname = hostname;
-    } else
-        self->server_hostname = NULL;
+    }
 
     Py_INCREF(sslctx);
 
@@ -524,8 +600,8 @@ newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
         /* BIOs are reference counted and SSL_set_bio borrows our reference.
          * To prevent a double free in memory_bio_dealloc() we need to take an
          * extra reference here. */
-        CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
-        CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
+        BIO_up_ref(inbio->bio);
+        BIO_up_ref(outbio->bio);
         SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
     }
     mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
@@ -559,7 +635,6 @@ newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
         self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
         if (self->Socket == NULL) {
             Py_DECREF(self);
-            Py_XDECREF(self->server_hostname);
             return NULL;
         }
     }
@@ -736,7 +811,7 @@ _create_tuple_for_X509_NAME (X509_NAME *xname)
 
         /* check to see if we've gotten to a new RDN */
         if (rdn_level >= 0) {
-            if (rdn_level != entry->set) {
+            if (rdn_level != X509_NAME_ENTRY_set(entry)) {
                 /* yes, new RDN */
                 /* add old RDN to DN */
                 rdnt = PyList_AsTuple(rdn);
@@ -753,7 +828,7 @@ _create_tuple_for_X509_NAME (X509_NAME *xname)
                     goto fail0;
             }
         }
-        rdn_level = entry->set;
+        rdn_level = X509_NAME_ENTRY_set(entry);
 
         /* now add this attribute to the current RDN */
         name = X509_NAME_ENTRY_get_object(entry);
@@ -851,18 +926,18 @@ _get_peer_alt_names (X509 *certificate) {
             goto fail;
         }
 
-        p = ext->value->data;
+        p = X509_EXTENSION_get_data(ext)->data;
         if (method->it)
             names = (GENERAL_NAMES*)
               (ASN1_item_d2i(NULL,
                              &p,
-                             ext->value->length,
+                             X509_EXTENSION_get_data(ext)->length,
                              ASN1_ITEM_ptr(method->it)));
         else
             names = (GENERAL_NAMES*)
               (method->d2i(NULL,
                            &p,
-                           ext->value->length));
+                           X509_EXTENSION_get_data(ext)->length));
 
         for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
             /* get a rendering of each name in the set of names */
@@ -932,6 +1007,35 @@ _get_peer_alt_names (X509 *certificate) {
                 PyTuple_SET_ITEM(t, 1, v);
                 break;
 
+            case GEN_RID:
+                t = PyTuple_New(2);
+                if (t == NULL)
+                    goto fail;
+
+                v = PyUnicode_FromString("Registered ID");
+                if (v == NULL) {
+                    Py_DECREF(t);
+                    goto fail;
+                }
+                PyTuple_SET_ITEM(t, 0, v);
+
+                len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
+                if (len < 0) {
+                    Py_DECREF(t);
+                    _setSSLError(NULL, 0, __FILE__, __LINE__);
+                    goto fail;
+                } else if (len >= (int)sizeof(buf)) {
+                    v = PyUnicode_FromString("<INVALID>");
+                } else {
+                    v = PyUnicode_FromStringAndSize(buf, len);
+                }
+                if (v == NULL) {
+                    Py_DECREF(t);
+                    goto fail;
+                }
+                PyTuple_SET_ITEM(t, 1, v);
+                break;
+
             default:
                 /* for everything else, we use the OpenSSL print form */
                 switch (gntype) {
@@ -958,8 +1062,12 @@ _get_peer_alt_names (X509 *certificate) {
                     goto fail;
                 }
                 vptr = strchr(buf, ':');
-                if (vptr == NULL)
+                if (vptr == NULL) {
+                    PyErr_Format(PyExc_ValueError,
+                                 "Invalid value %.200s",
+                                 buf);
                     goto fail;
+                }
                 t = PyTuple_New(2);
                 if (t == NULL)
                     goto fail;
@@ -1073,13 +1181,11 @@ _get_crl_dp(X509 *certificate) {
     int i, j;
     PyObject *lst, *res = NULL;
 
-#if OPENSSL_VERSION_NUMBER < 0x10001000L
-    dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
-#else
+#if OPENSSL_VERSION_NUMBER >= 0x10001000L
     /* Calls x509v3_cache_extensions and sets up crldp */
     X509_check_ca(certificate);
-    dps = certificate->crldp;
 #endif
+    dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
 
     if (dps == NULL)
         return Py_None;
@@ -1321,8 +1427,8 @@ _ssl._test_decode_cert
 [clinic start generated code]*/
 
 static PyObject *
-_ssl__test_decode_cert_impl(PyModuleDef *module, PyObject *path)
-/*[clinic end generated code: output=679e01db282804e9 input=cdeaaf02d4346628]*/
+_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
+/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
 {
     PyObject *retval = NULL;
     X509 *x=NULL;
@@ -1449,14 +1555,13 @@ static PyObject *
 _ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
 /*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
 {
-    SSL_SESSION *sess = SSL_get_session(self->ssl);
     STACK_OF(SSL_CIPHER) *ciphers;
     int i;
     PyObject *res;
 
-    if (!sess || !sess->ciphers)
+    ciphers = SSL_get_ciphers(self->ssl);
+    if (!ciphers)
         Py_RETURN_NONE;
-    ciphers = sess->ciphers;
     res = PyList_New(sk_SSL_CIPHER_num(ciphers));
     if (!res)
         return NULL;
@@ -1565,9 +1670,9 @@ _ssl__SSLSocket_compression_impl(PySSLSocket *self)
     if (self->ssl == NULL)
         Py_RETURN_NONE;
     comp_method = SSL_get_current_compression(self->ssl);
-    if (comp_method == NULL || comp_method->type == NID_undef)
+    if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
         Py_RETURN_NONE;
-    short_name = OBJ_nid2sn(comp_method->type);
+    short_name = OBJ_nid2sn(COMP_get_type(comp_method));
     if (short_name == NULL)
         Py_RETURN_NONE;
     return PyUnicode_DecodeFSDefault(short_name);
@@ -1699,7 +1804,7 @@ PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
     }
 
     /* Guard against closed socket */
-    if (s->sock_fd < 0)
+    if (s->sock_fd == INVALID_SOCKET)
         return SOCKET_HAS_BEEN_CLOSED;
 
     /* Prefer poll, if available, since you can poll() any fd
@@ -1913,6 +2018,10 @@ _ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
         dest = PyBytes_FromStringAndSize(NULL, len);
         if (dest == NULL)
             goto error;
+        if (len == 0) {
+            Py_XDECREF(sock);
+            return dest;
+        }
         mem = PyBytes_AS_STRING(dest);
     }
     else {
@@ -1924,6 +2033,10 @@ _ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
                                 "maximum length can't fit in a C 'int'");
                 goto error;
             }
+            if (len == 0) {
+                count = 0;
+                goto done;
+            }
         }
     }
 
@@ -2015,7 +2128,7 @@ _ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
 
     if (sock != NULL) {
         /* Guard against closed socket */
-        if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
+        if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
             _setSSLError("Underlying socket connection gone",
                          PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
             return NULL;
@@ -2245,8 +2358,8 @@ _ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
     else if (proto_version == PY_SSL_VERSION_SSL2)
         ctx = SSL_CTX_new(SSLv2_method());
 #endif
-    else if (proto_version == PY_SSL_VERSION_SSL23)
-        ctx = SSL_CTX_new(SSLv23_method());
+    else if (proto_version == PY_SSL_VERSION_TLS)
+        ctx = SSL_CTX_new(TLS_method());
     else
         proto_version = -1;
     PySSL_END_ALLOW_THREADS
@@ -2308,8 +2421,9 @@ _ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
 #ifndef OPENSSL_NO_ECDH
     /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
        prime256v1 by default.  This is Apache mod_ssl's initialization
-       policy, so we should be safe. */
-#if defined(SSL_CTX_set_ecdh_auto)
+       policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
+     */
+#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
     SSL_CTX_set_ecdh_auto(self->ctx, 1);
 #else
     {
@@ -2576,10 +2690,12 @@ static PyObject *
 get_verify_flags(PySSLContext *self, void *c)
 {
     X509_STORE *store;
+    X509_VERIFY_PARAM *param;
     unsigned long flags;
 
     store = SSL_CTX_get_cert_store(self->ctx);
-    flags = X509_VERIFY_PARAM_get_flags(store->param);
+    param = X509_STORE_get0_param(store);
+    flags = X509_VERIFY_PARAM_get_flags(param);
     return PyLong_FromUnsignedLong(flags);
 }
 
@@ -2587,22 +2703,24 @@ static int
 set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
 {
     X509_STORE *store;
+    X509_VERIFY_PARAM *param;
     unsigned long new_flags, flags, set, clear;
 
     if (!PyArg_Parse(arg, "k", &new_flags))
         return -1;
     store = SSL_CTX_get_cert_store(self->ctx);
-    flags = X509_VERIFY_PARAM_get_flags(store->param);
+    param = X509_STORE_get0_param(store);
+    flags = X509_VERIFY_PARAM_get_flags(param);
     clear = flags & ~new_flags;
     set = ~flags & new_flags;
     if (clear) {
-        if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
+        if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
             _setSSLError(NULL, 0, __FILE__, __LINE__);
             return -1;
         }
     }
     if (set) {
-        if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
+        if (!X509_VERIFY_PARAM_set_flags(param, set)) {
             _setSSLError(NULL, 0, __FILE__, __LINE__);
             return -1;
         }
@@ -2779,8 +2897,8 @@ _ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
 /*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
 {
     PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
-    pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
-    void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
+    pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
+    void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
     _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
     int r;
 
@@ -2907,8 +3025,9 @@ _add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
             cert = d2i_X509_bio(biobuf, NULL);
         } else {
             cert = PEM_read_bio_X509(biobuf, NULL,
-                                     self->ctx->default_passwd_callback,
-                                     self->ctx->default_passwd_callback_userdata);
+                                     SSL_CTX_get_default_passwd_cb(self->ctx),
+                                     SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
+                                    );
         }
         if (cert == NULL) {
             break;
@@ -3434,25 +3553,24 @@ _ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
 /*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
 {
     X509_STORE *store;
+    STACK_OF(X509_OBJECT) *objs;
     X509_OBJECT *obj;
-    int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
+    int x509 = 0, crl = 0, ca = 0, i;
 
     store = SSL_CTX_get_cert_store(self->ctx);
-    for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
-        obj = sk_X509_OBJECT_value(store->objs, i);
-        switch (obj->type) {
+    objs = X509_STORE_get0_objects(store);
+    for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
+        obj = sk_X509_OBJECT_value(objs, i);
+        switch (X509_OBJECT_get_type(obj)) {
             case X509_LU_X509:
                 x509++;
-                if (X509_check_ca(obj->data.x509)) {
+                if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
                     ca++;
                 }
                 break;
             case X509_LU_CRL:
                 crl++;
                 break;
-            case X509_LU_PKEY:
-                pkey++;
-                break;
             default:
                 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
                  * As far as I can tell they are internal states and never
@@ -3482,6 +3600,7 @@ _ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
 /*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
 {
     X509_STORE *store;
+    STACK_OF(X509_OBJECT) *objs;
     PyObject *ci = NULL, *rlist = NULL;
     int i;
 
@@ -3490,17 +3609,18 @@ _ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
     }
 
     store = SSL_CTX_get_cert_store(self->ctx);
-    for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
+    objs = X509_STORE_get0_objects(store);
+    for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
         X509_OBJECT *obj;
         X509 *cert;
 
-        obj = sk_X509_OBJECT_value(store->objs, i);
-        if (obj->type != X509_LU_X509) {
+        obj = sk_X509_OBJECT_value(objs, i);
+        if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
             /* not a x509 cert */
             continue;
         }
         /* CA for any purpose */
-        cert = obj->data.x509;
+        cert = X509_OBJECT_get0_X509(obj);
         if (!X509_check_ca(cert)) {
             continue;
         }
@@ -3832,8 +3952,8 @@ string.  See RFC 1750.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_RAND_add_impl(PyModuleDef *module, Py_buffer *view, double entropy)
-/*[clinic end generated code: output=0f8d5c8cce328958 input=580c85e6a3a4fe29]*/
+_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
+/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
 {
     const char *buf;
     Py_ssize_t len, written;
@@ -3898,8 +4018,8 @@ Generate n cryptographically strong pseudo-random bytes.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_RAND_bytes_impl(PyModuleDef *module, int n)
-/*[clinic end generated code: output=7d8741bdc1d435f3 input=678ddf2872dfebfc]*/
+_ssl_RAND_bytes_impl(PyObject *module, int n)
+/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
 {
     return PySSL_RAND(n, 0);
 }
@@ -3916,8 +4036,8 @@ if the bytes generated are cryptographically strong.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_RAND_pseudo_bytes_impl(PyModuleDef *module, int n)
-/*[clinic end generated code: output=dd673813107f3875 input=58312bd53f9bbdd0]*/
+_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
+/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
 {
     return PySSL_RAND(n, 1);
 }
@@ -3932,13 +4052,13 @@ using the ssl() function.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_RAND_status_impl(PyModuleDef *module)
-/*[clinic end generated code: output=7f7ef57bc7dd1d1c input=8a774b02d1dc81f3]*/
+_ssl_RAND_status_impl(PyObject *module)
+/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
 {
     return PyLong_FromLong(RAND_status());
 }
 
-#ifdef HAVE_RAND_EGD
+#ifndef OPENSSL_NO_EGD
 /*[clinic input]
 _ssl.RAND_egd
     path: object(converter="PyUnicode_FSConverter")
@@ -3951,8 +4071,8 @@ fails or if it does not provide enough data to seed PRNG.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_RAND_egd_impl(PyModuleDef *module, PyObject *path)
-/*[clinic end generated code: output=8e728e501e28541b input=1aeb7eb948312195]*/
+_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
+/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
 {
     int bytes = RAND_egd(PyBytes_AsString(path));
     Py_DECREF(path);
@@ -3964,7 +4084,7 @@ _ssl_RAND_egd_impl(PyModuleDef *module, PyObject *path)
     }
     return PyLong_FromLong(bytes);
 }
-#endif /* HAVE_RAND_EGD */
+#endif /* OPENSSL_NO_EGD */
 
 
 
@@ -3977,8 +4097,8 @@ The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_get_default_verify_paths_impl(PyModuleDef *module)
-/*[clinic end generated code: output=5a2820ce7e3304d3 input=5210c953d98c3eb5]*/
+_ssl_get_default_verify_paths_impl(PyObject *module)
+/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
 {
     PyObject *ofile_env = NULL;
     PyObject *ofile = NULL;
@@ -4049,8 +4169,8 @@ long name are also matched.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_txt2obj_impl(PyModuleDef *module, const char *txt, int name)
-/*[clinic end generated code: output=2ae2c30531b8809f input=1c1e7d0aa7c48602]*/
+_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
+/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
 {
     PyObject *result = NULL;
     ASN1_OBJECT *obj;
@@ -4074,8 +4194,8 @@ Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_nid2obj_impl(PyModuleDef *module, int nid)
-/*[clinic end generated code: output=8db1df89e44badb8 input=51787a3bee7d8f98]*/
+_ssl_nid2obj_impl(PyObject *module, int nid)
+/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
 {
     PyObject *result = NULL;
     ASN1_OBJECT *obj;
@@ -4193,8 +4313,8 @@ a set of OIDs or the boolean True.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_enum_certificates_impl(PyModuleDef *module, const char *store_name)
-/*[clinic end generated code: output=cc4ebc10b8adacfc input=915f60d70461ea4e]*/
+_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
+/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
 {
     HCERTSTORE hStore = NULL;
     PCCERT_CONTEXT pCertCtx = NULL;
@@ -4281,8 +4401,8 @@ X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
 [clinic start generated code]*/
 
 static PyObject *
-_ssl_enum_crls_impl(PyModuleDef *module, const char *store_name)
-/*[clinic end generated code: output=763490a2aa1c50d5 input=a1f1d7629f1c5d3d]*/
+_ssl_enum_crls_impl(PyObject *module, const char *store_name)
+/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
 {
     HCERTSTORE hStore = NULL;
     PCCRL_CONTEXT pCrlCtx = NULL;
@@ -4364,10 +4484,12 @@ static PyMethodDef PySSL_methods[] = {
 };
 
 
-#ifdef WITH_THREAD
+#ifdef HAVE_OPENSSL_CRYPTO_LOCK
 
 /* an implementation of OpenSSL threading operations in terms
-   of the Python C thread library */
+ * of the Python C thread library
+ * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
+ */
 
 static PyThread_type_lock *_ssl_locks = NULL;
 
@@ -4448,7 +4570,7 @@ static int _setup_ssl_threads(void) {
     return 1;
 }
 
-#endif  /* def HAVE_THREAD */
+#endif  /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
 
 PyDoc_STRVAR(module_doc,
 "Implementation module for SSL socket operations.  See the socket module\n\
@@ -4517,11 +4639,16 @@ PyInit__ssl(void)
     SSL_load_error_strings();
     SSL_library_init();
 #ifdef WITH_THREAD
+#ifdef HAVE_OPENSSL_CRYPTO_LOCK
     /* note that this will start threading if not already started */
     if (!_setup_ssl_threads()) {
         return NULL;
     }
+#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
+    /* OpenSSL 1.1.0 builtin thread support is enabled */
+    _ssl_locks_count++;
 #endif
+#endif  /* WITH_THREAD */
     OpenSSL_add_all_algorithms();
 
     /* Add symbols to module dict */
@@ -4668,7 +4795,9 @@ PyInit__ssl(void)
                             PY_SSL_VERSION_SSL3);
 #endif
     PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
-                            PY_SSL_VERSION_SSL23);
+                            PY_SSL_VERSION_TLS);
+    PyModule_AddIntConstant(m, "PROTOCOL_TLS",
+                            PY_SSL_VERSION_TLS);
     PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
                             PY_SSL_VERSION_TLS1);
 #if HAVE_TLSv1_2
index 3810e94..060a92d 100644 (file)
@@ -249,6 +249,15 @@ test_dict_iteration(PyObject* self)
 }
 
 
+static PyObject*
+dict_hassplittable(PyObject *self, PyObject *arg)
+{
+    if (!PyArg_Parse(arg, "O!:dict_hassplittable", &PyDict_Type, &arg)) {
+        return NULL;
+    }
+    return PyBool_FromLong(_PyDict_HasSplitTable((PyDictObject*)arg));
+}
+
 /* Issue #4701: Check that PyObject_Hash implicitly calls
  *   PyType_Ready if it hasn't already been called
  */
@@ -1830,6 +1839,69 @@ unicode_aswidecharstring(PyObject *self, PyObject *args)
 }
 
 static PyObject *
+unicode_asucs4(PyObject *self, PyObject *args)
+{
+    PyObject *unicode, *result;
+    Py_UCS4 *buffer;
+    int copy_null;
+    Py_ssize_t str_len, buf_len;
+
+    if (!PyArg_ParseTuple(args, "Unp:unicode_asucs4", &unicode, &str_len, &copy_null)) {
+        return NULL;
+    }
+
+    buf_len = str_len + 1;
+    buffer = PyMem_NEW(Py_UCS4, buf_len);
+    if (buffer == NULL) {
+        return PyErr_NoMemory();
+    }
+    memset(buffer, 0, sizeof(Py_UCS4)*buf_len);
+    buffer[str_len] = 0xffffU;
+
+    if (!PyUnicode_AsUCS4(unicode, buffer, buf_len, copy_null)) {
+        PyMem_FREE(buffer);
+        return NULL;
+    }
+
+    result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, buffer, buf_len);
+    PyMem_FREE(buffer);
+    return result;
+}
+
+static PyObject *
+unicode_copycharacters(PyObject *self, PyObject *args)
+{
+    PyObject *from, *to, *to_copy;
+    Py_ssize_t from_start, to_start, how_many, copied;
+
+    if (!PyArg_ParseTuple(args, "UnOnn:unicode_copycharacters", &to, &to_start,
+                          &from, &from_start, &how_many)) {
+        return NULL;
+    }
+
+    if (PyUnicode_READY(to) < 0) {
+        return NULL;
+    }
+
+    if (!(to_copy = PyUnicode_New(PyUnicode_GET_LENGTH(to),
+                                  PyUnicode_MAX_CHAR_VALUE(to)))) {
+        return NULL;
+    }
+    if (PyUnicode_Fill(to_copy, 0, PyUnicode_GET_LENGTH(to_copy), 0U) < 0) {
+        Py_DECREF(to_copy);
+        return NULL;
+    }
+
+    if ((copied = PyUnicode_CopyCharacters(to_copy, to_start, from,
+                                           from_start, how_many)) < 0) {
+        Py_DECREF(to_copy);
+        return NULL;
+    }
+
+    return Py_BuildValue("(Nn)", to_copy, copied);
+}
+
+static PyObject *
 unicode_encodedecimal(PyObject *self, PyObject *args)
 {
     Py_UNICODE *unicode;
@@ -2247,7 +2319,7 @@ test_string_from_format(PyObject *self, PyObject *args)
     result = PyUnicode_FromFormat(FORMAT, (TYPE)1);                 \
     if (result == NULL)                                             \
         return NULL;                                                \
-    if (PyUnicode_CompareWithASCIIString(result, "1")) {     \
+    if (!_PyUnicode_EqualToASCIIString(result, "1")) {              \
         msg = FORMAT " failed at 1";                                \
         goto Fail;                                                  \
     }                                                               \
@@ -3781,7 +3853,7 @@ get_recursion_depth(PyObject *self, PyObject *args)
 {
     PyThreadState *tstate = PyThreadState_GET();
 
-    /* substract one to ignore the frame of the get_recursion_depth() call */
+    /* subtract one to ignore the frame of the get_recursion_depth() call */
     return PyLong_FromLong(tstate->recursion_depth - 1);
 }
 
@@ -3795,6 +3867,7 @@ static PyMethodDef TestMethods[] = {
     {"test_datetime_capi",  test_datetime_capi,              METH_NOARGS},
     {"test_list_api",           (PyCFunction)test_list_api,      METH_NOARGS},
     {"test_dict_iteration",     (PyCFunction)test_dict_iteration,METH_NOARGS},
+    {"dict_hassplittable",      dict_hassplittable,              METH_O},
     {"test_lazy_hash_inheritance",      (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
     {"test_long_api",           (PyCFunction)test_long_api,      METH_NOARGS},
     {"test_xincref_doesnt_leak",(PyCFunction)test_xincref_doesnt_leak,      METH_NOARGS},
@@ -3884,6 +3957,8 @@ static PyMethodDef TestMethods[] = {
     {"test_widechar",           (PyCFunction)test_widechar,      METH_NOARGS},
     {"unicode_aswidechar",      unicode_aswidechar,              METH_VARARGS},
     {"unicode_aswidecharstring",unicode_aswidecharstring,        METH_VARARGS},
+    {"unicode_asucs4",          unicode_asucs4,                  METH_VARARGS},
+    {"unicode_copycharacters",  unicode_copycharacters,          METH_VARARGS},
     {"unicode_encodedecimal",   unicode_encodedecimal,           METH_VARARGS},
     {"unicode_transformdecimaltoascii", unicode_transformdecimaltoascii, METH_VARARGS},
     {"unicode_legacy_string",   unicode_legacy_string,           METH_VARARGS},
index 2005205..41da997 100644 (file)
@@ -248,6 +248,7 @@ PyInit__testmultiphase(PyObject *spec)
 /**** Importing a non-module object ****/
 
 static PyModuleDef def_nonmodule;
+static PyModuleDef def_nonmodule_with_methods;
 
 /* Create a SimpleNamespace(three=3) */
 static PyObject*
@@ -255,7 +256,7 @@ createfunc_nonmodule(PyObject *spec, PyModuleDef *def)
 {
     PyObject *dct, *ns, *three;
 
-    if (def != &def_nonmodule) {
+    if (def != &def_nonmodule && def != &def_nonmodule_with_methods) {
         PyErr_SetString(PyExc_SystemError, "def does not match");
         return NULL;
     }
@@ -291,6 +292,36 @@ PyInit__testmultiphase_nonmodule(PyObject *spec)
     return PyModuleDef_Init(&def_nonmodule);
 }
 
+PyDoc_STRVAR(nonmodule_bar_doc,
+"bar(i,j)\n\
+\n\
+Return the difference of i - j.");
+
+static PyObject *
+nonmodule_bar(PyObject *self, PyObject *args)
+{
+    long i, j;
+    long res;
+    if (!PyArg_ParseTuple(args, "ll:bar", &i, &j))
+        return NULL;
+    res = i - j;
+    return PyLong_FromLong(res);
+}
+
+static PyMethodDef nonmodule_methods[] = {
+    {"bar", nonmodule_bar, METH_VARARGS, nonmodule_bar_doc},
+    {NULL, NULL}           /* sentinel */
+};
+
+static PyModuleDef def_nonmodule_with_methods = TEST_MODULE_DEF(
+    "_testmultiphase_nonmodule_with_methods", slots_create_nonmodule, nonmodule_methods);
+
+PyMODINIT_FUNC
+PyInit__testmultiphase_nonmodule_with_methods(PyObject *spec)
+{
+    return PyModuleDef_Init(&def_nonmodule_with_methods);
+}
+
 /**** Non-ASCII-named modules ****/
 
 static PyModuleDef def_nonascii_latin = { \
index 968181c..0219559 100644 (file)
@@ -45,7 +45,7 @@ lock_dealloc(lockobject *self)
 /* Helper to acquire an interruptible lock with a timeout.  If the lock acquire
  * is interrupted, signal handlers are run, and if they raise an exception,
  * PY_LOCK_INTR is returned.  Otherwise, PY_LOCK_ACQUIRED or PY_LOCK_FAILURE
- * are returned, depending on whether the lock can be acquired withing the
+ * are returned, depending on whether the lock can be acquired within the
  * timeout.
  */
 static PyLockStatus
index cf56fa8..163c87f 100644 (file)
@@ -1779,7 +1779,7 @@ var_perform(VarEvent *ev)
         PyErr_NormalizeException(&exc, &val, &tb);
         *(ev->exc_type) = exc;
         *(ev->exc_val) = val;
-        Py_DECREF(tb);
+        Py_XDECREF(tb);
     }
 
 }
@@ -3175,8 +3175,8 @@ _tkinter._flatten
 [clinic start generated code]*/
 
 static PyObject *
-_tkinter__flatten(PyModuleDef *module, PyObject *item)
-/*[clinic end generated code: output=9505049ec74c3480 input=6b9c12260aa1157f]*/
+_tkinter__flatten(PyObject *module, PyObject *item)
+/*[clinic end generated code: output=cad02a3f97f29862 input=6b9c12260aa1157f]*/
 {
     FlattenContext context;
 
@@ -3220,11 +3220,11 @@ _tkinter.create
 [clinic start generated code]*/
 
 static PyObject *
-_tkinter_create_impl(PyModuleDef *module, const char *screenName,
+_tkinter_create_impl(PyObject *module, const char *screenName,
                      const char *baseName, const char *className,
                      int interactive, int wantobjects, int wantTk, int sync,
                      const char *use)
-/*[clinic end generated code: output=b8847800fc3b27eb input=0d522aad1cb0ca0e]*/
+/*[clinic end generated code: output=e3315607648e6bb4 input=0d522aad1cb0ca0e]*/
 {
     /* XXX baseName is not used anymore;
      * try getting rid of it. */
@@ -3250,8 +3250,8 @@ It should be set to a divisor of the maximum time between frames in an animation
 [clinic start generated code]*/
 
 static PyObject *
-_tkinter_setbusywaitinterval_impl(PyModuleDef *module, int new_val)
-/*[clinic end generated code: output=0b9d7ef7940461ea input=deca1d6f9e6dae47]*/
+_tkinter_setbusywaitinterval_impl(PyObject *module, int new_val)
+/*[clinic end generated code: output=42bf7757dc2d0ab6 input=deca1d6f9e6dae47]*/
 {
     if (new_val < 0) {
         PyErr_SetString(PyExc_ValueError,
@@ -3269,8 +3269,8 @@ Return the current busy-wait interval between successive calls to Tcl_DoOneEvent
 [clinic start generated code]*/
 
 static int
-_tkinter_getbusywaitinterval_impl(PyModuleDef *module)
-/*[clinic end generated code: output=9d09eee026e96971 input=a695878d2d576a84]*/
+_tkinter_getbusywaitinterval_impl(PyObject *module)
+/*[clinic end generated code: output=23b72d552001f5c7 input=a695878d2d576a84]*/
 {
     return Tkinter_busywaitinterval;
 }
index 796ac0f..65bf7a3 100644 (file)
@@ -516,7 +516,7 @@ tracemalloc_realloc(void *ctx, void *ptr, size_t new_size)
 
         if (tracemalloc_add_trace(ptr2, new_size) < 0) {
             /* Memory allocation failed. The error cannot be reported to
-               the caller, because realloc() may already have shrinked the
+               the caller, because realloc() may already have shrunk the
                memory block and so removed bytes.
 
                This case is very unlikely: a hash entry has just been
index 7c99d7e..f9c68d6 100644 (file)
@@ -22,8 +22,8 @@ Return the number of weak references to 'object'.
 [clinic start generated code]*/
 
 static Py_ssize_t
-_weakref_getweakrefcount_impl(PyModuleDef *module, PyObject *object)
-/*[clinic end generated code: output=6a6ad0b98285e468 input=cedb69711b6a2507]*/
+_weakref_getweakrefcount_impl(PyObject *module, PyObject *object)
+/*[clinic end generated code: output=301806d59558ff3e input=cedb69711b6a2507]*/
 {
     PyWeakReference **list;
 
@@ -35,6 +35,46 @@ _weakref_getweakrefcount_impl(PyModuleDef *module, PyObject *object)
 }
 
 
+static int
+is_dead_weakref(PyObject *value)
+{
+    if (!PyWeakref_Check(value)) {
+        PyErr_SetString(PyExc_TypeError, "not a weakref");
+        return -1;
+    }
+    return PyWeakref_GET_OBJECT(value) == Py_None;
+}
+
+/*[clinic input]
+
+_weakref._remove_dead_weakref -> object
+
+  dct: object(subclass_of='&PyDict_Type')
+  key: object
+  /
+
+Atomically remove key from dict if it points to a dead weakref.
+[clinic start generated code]*/
+
+static PyObject *
+_weakref__remove_dead_weakref_impl(PyObject *module, PyObject *dct,
+                                   PyObject *key)
+/*[clinic end generated code: output=d9ff53061fcb875c input=19fc91f257f96a1d]*/
+{
+    if (_PyDict_DelItemIf(dct, key, is_dead_weakref) < 0) {
+        if (PyErr_ExceptionMatches(PyExc_KeyError))
+            /* This function is meant to allow safe weak-value dicts
+               with GC in another thread (see issue #28427), so it's
+               ok if the key doesn't exist anymore.
+               */
+            PyErr_Clear();
+        else
+            return NULL;
+    }
+    Py_RETURN_NONE;
+}
+
+
 PyDoc_STRVAR(weakref_getweakrefs__doc__,
 "getweakrefs(object) -- return a list of all weak reference objects\n"
 "that point to 'object'.");
@@ -88,6 +128,7 @@ weakref_proxy(PyObject *self, PyObject *args)
 static PyMethodDef
 weakref_functions[] =  {
     _WEAKREF_GETWEAKREFCOUNT_METHODDEF
+    _WEAKREF__REMOVE_DEAD_WEAKREF_METHODDEF
     {"getweakrefs",     weakref_getweakrefs,            METH_O,
      weakref_getweakrefs__doc__},
     {"proxy",           weakref_proxy,                  METH_VARARGS,
index 3e7f187..edc6cf4 100644 (file)
@@ -368,8 +368,8 @@ Close handle.
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_CloseHandle_impl(PyModuleDef *module, HANDLE handle)
-/*[clinic end generated code: output=0548595c71cb4bf7 input=7f0e4ac36e0352b8]*/
+_winapi_CloseHandle_impl(PyObject *module, HANDLE handle)
+/*[clinic end generated code: output=7ad37345f07bd782 input=7f0e4ac36e0352b8]*/
 {
     BOOL success;
 
@@ -391,9 +391,9 @@ _winapi.ConnectNamedPipe
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_ConnectNamedPipe_impl(PyModuleDef *module, HANDLE handle,
+_winapi_ConnectNamedPipe_impl(PyObject *module, HANDLE handle,
                               int use_overlapped)
-/*[clinic end generated code: output=fed3b165d1bca95a input=edc83da007ebf3be]*/
+/*[clinic end generated code: output=335a0e7086800671 input=edc83da007ebf3be]*/
 {
     BOOL success;
     OverlappedObject *overlapped = NULL;
@@ -443,12 +443,12 @@ _winapi.CreateFile -> HANDLE
 [clinic start generated code]*/
 
 static HANDLE
-_winapi_CreateFile_impl(PyModuleDef *module, LPCTSTR file_name,
+_winapi_CreateFile_impl(PyObject *module, LPCTSTR file_name,
                         DWORD desired_access, DWORD share_mode,
                         LPSECURITY_ATTRIBUTES security_attributes,
                         DWORD creation_disposition,
                         DWORD flags_and_attributes, HANDLE template_file)
-/*[clinic end generated code: output=c6e1d78f8affd10c input=6423c3e40372dbd5]*/
+/*[clinic end generated code: output=417ddcebfc5a3d53 input=6423c3e40372dbd5]*/
 {
     HANDLE handle;
 
@@ -474,9 +474,9 @@ _winapi.CreateJunction
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_CreateJunction_impl(PyModuleDef *module, LPWSTR src_path,
+_winapi_CreateJunction_impl(PyObject *module, LPWSTR src_path,
                             LPWSTR dst_path)
-/*[clinic end generated code: output=eccae9364e46f6da input=8cd1f9964b6e3d36]*/
+/*[clinic end generated code: output=66b7eb746e1dfa25 input=8cd1f9964b6e3d36]*/
 {
     /* Privilege adjustment */
     HANDLE token = NULL;
@@ -617,12 +617,12 @@ _winapi.CreateNamedPipe -> HANDLE
 [clinic start generated code]*/
 
 static HANDLE
-_winapi_CreateNamedPipe_impl(PyModuleDef *module, LPCTSTR name,
-                             DWORD open_mode, DWORD pipe_mode,
-                             DWORD max_instances, DWORD out_buffer_size,
-                             DWORD in_buffer_size, DWORD default_timeout,
+_winapi_CreateNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD open_mode,
+                             DWORD pipe_mode, DWORD max_instances,
+                             DWORD out_buffer_size, DWORD in_buffer_size,
+                             DWORD default_timeout,
                              LPSECURITY_ATTRIBUTES security_attributes)
-/*[clinic end generated code: output=44ca2a06a219b523 input=5a73530b84d8bc37]*/
+/*[clinic end generated code: output=80f8c07346a94fbc input=5a73530b84d8bc37]*/
 {
     HANDLE handle;
 
@@ -653,9 +653,8 @@ Returns a 2-tuple of handles, to the read and write ends of the pipe.
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_CreatePipe_impl(PyModuleDef *module, PyObject *pipe_attrs,
-                        DWORD size)
-/*[clinic end generated code: output=fef99f3b4222bc78 input=c4f2cfa56ef68d90]*/
+_winapi_CreatePipe_impl(PyObject *module, PyObject *pipe_attrs, DWORD size)
+/*[clinic end generated code: output=1c4411d8699f0925 input=c4f2cfa56ef68d90]*/
 {
     HANDLE read_pipe;
     HANDLE write_pipe;
@@ -814,13 +813,13 @@ process ID, and thread ID.
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_CreateProcess_impl(PyModuleDef *module, Py_UNICODE *application_name,
+_winapi_CreateProcess_impl(PyObject *module, Py_UNICODE *application_name,
                            Py_UNICODE *command_line, PyObject *proc_attrs,
                            PyObject *thread_attrs, BOOL inherit_handles,
                            DWORD creation_flags, PyObject *env_mapping,
                            Py_UNICODE *current_directory,
                            PyObject *startup_info)
-/*[clinic end generated code: output=874bb350ff9ed4ef input=4a43b05038d639bb]*/
+/*[clinic end generated code: output=4652a33aff4b0ae1 input=4a43b05038d639bb]*/
 {
     BOOL result;
     PROCESS_INFORMATION pi;
@@ -900,13 +899,12 @@ through both handles.
 [clinic start generated code]*/
 
 static HANDLE
-_winapi_DuplicateHandle_impl(PyModuleDef *module,
-                             HANDLE source_process_handle,
+_winapi_DuplicateHandle_impl(PyObject *module, HANDLE source_process_handle,
                              HANDLE source_handle,
                              HANDLE target_process_handle,
                              DWORD desired_access, BOOL inherit_handle,
                              DWORD options)
-/*[clinic end generated code: output=0799515b68b5237b input=b933e3f2356a8c12]*/
+/*[clinic end generated code: output=ad9711397b5dcd4e input=b933e3f2356a8c12]*/
 {
     HANDLE target_handle;
     BOOL result;
@@ -940,8 +938,8 @@ _winapi.ExitProcess
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_ExitProcess_impl(PyModuleDef *module, UINT ExitCode)
-/*[clinic end generated code: output=25f3b499c24cedc8 input=4f05466a9406c558]*/
+_winapi_ExitProcess_impl(PyObject *module, UINT ExitCode)
+/*[clinic end generated code: output=a387deb651175301 input=4f05466a9406c558]*/
 {
     #if defined(Py_DEBUG)
         SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|
@@ -961,8 +959,8 @@ Return a handle object for the current process.
 [clinic start generated code]*/
 
 static HANDLE
-_winapi_GetCurrentProcess_impl(PyModuleDef *module)
-/*[clinic end generated code: output=be29ac3ad5f8291e input=b213403fd4b96b41]*/
+_winapi_GetCurrentProcess_impl(PyObject *module)
+/*[clinic end generated code: output=ddeb4dd2ffadf344 input=b213403fd4b96b41]*/
 {
     return GetCurrentProcess();
 }
@@ -977,8 +975,8 @@ Return the termination status of the specified process.
 [clinic start generated code]*/
 
 static DWORD
-_winapi_GetExitCodeProcess_impl(PyModuleDef *module, HANDLE process)
-/*[clinic end generated code: output=0b10f0848a410f65 input=61b6bfc7dc2ee374]*/
+_winapi_GetExitCodeProcess_impl(PyObject *module, HANDLE process)
+/*[clinic end generated code: output=b4620bdf2bccf36b input=61b6bfc7dc2ee374]*/
 {
     DWORD exit_code;
     BOOL result;
@@ -998,8 +996,8 @@ _winapi.GetLastError -> DWORD
 [clinic start generated code]*/
 
 static DWORD
-_winapi_GetLastError_impl(PyModuleDef *module)
-/*[clinic end generated code: output=0ea00d8e67bdd056 input=62d47fb9bce038ba]*/
+_winapi_GetLastError_impl(PyObject *module)
+/*[clinic end generated code: output=8585b827cb1a92c5 input=62d47fb9bce038ba]*/
 {
     return GetLastError();
 }
@@ -1021,8 +1019,8 @@ of the current process.
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_GetModuleFileName_impl(PyModuleDef *module, HMODULE module_handle)
-/*[clinic end generated code: output=90063dc63bdbfa18 input=6d66ff7deca5d11f]*/
+_winapi_GetModuleFileName_impl(PyObject *module, HMODULE module_handle)
+/*[clinic end generated code: output=85b4b728c5160306 input=6d66ff7deca5d11f]*/
 {
     BOOL result;
     WCHAR filename[MAX_PATH];
@@ -1049,8 +1047,8 @@ The integer associated with the handle object is returned.
 [clinic start generated code]*/
 
 static HANDLE
-_winapi_GetStdHandle_impl(PyModuleDef *module, DWORD std_handle)
-/*[clinic end generated code: output=5f5ca28b28c6fad2 input=07016b06a2fc8826]*/
+_winapi_GetStdHandle_impl(PyObject *module, DWORD std_handle)
+/*[clinic end generated code: output=0e613001e73ab614 input=07016b06a2fc8826]*/
 {
     HANDLE handle;
 
@@ -1071,8 +1069,8 @@ Return the version number of the current operating system.
 [clinic start generated code]*/
 
 static long
-_winapi_GetVersion_impl(PyModuleDef *module)
-/*[clinic end generated code: output=95a2f8ad3b948ca8 input=e21dff8d0baeded2]*/
+_winapi_GetVersion_impl(PyObject *module)
+/*[clinic end generated code: output=e41f0db5a3b82682 input=e21dff8d0baeded2]*/
 /* Disable deprecation warnings about GetVersionEx as the result is
    being passed straight through to the caller, who is responsible for
    using it correctly. */
@@ -1095,9 +1093,9 @@ _winapi.OpenProcess -> HANDLE
 [clinic start generated code]*/
 
 static HANDLE
-_winapi_OpenProcess_impl(PyModuleDef *module, DWORD desired_access,
+_winapi_OpenProcess_impl(PyObject *module, DWORD desired_access,
                          BOOL inherit_handle, DWORD process_id)
-/*[clinic end generated code: output=6bc52eda82a3d226 input=ec98c4cf4ea2ec36]*/
+/*[clinic end generated code: output=b42b6b81ea5a0fc3 input=ec98c4cf4ea2ec36]*/
 {
     HANDLE handle;
 
@@ -1119,8 +1117,8 @@ _winapi.PeekNamedPipe
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_PeekNamedPipe_impl(PyModuleDef *module, HANDLE handle, int size)
-/*[clinic end generated code: output=e6c908e2fb63c798 input=c7aa53bfbce69d70]*/
+_winapi_PeekNamedPipe_impl(PyObject *module, HANDLE handle, int size)
+/*[clinic end generated code: output=d0c3e29e49d323dd input=c7aa53bfbce69d70]*/
 {
     PyObject *buf = NULL;
     DWORD nread, navail, nleft;
@@ -1167,9 +1165,9 @@ _winapi.ReadFile
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_ReadFile_impl(PyModuleDef *module, HANDLE handle, int size,
+_winapi_ReadFile_impl(PyObject *module, HANDLE handle, int size,
                       int use_overlapped)
-/*[clinic end generated code: output=d7695db4db97b135 input=8dd810194e86ac7d]*/
+/*[clinic end generated code: output=492029ca98161d84 input=8dd810194e86ac7d]*/
 {
     DWORD nread;
     PyObject *buf;
@@ -1229,11 +1227,11 @@ _winapi.SetNamedPipeHandleState
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_SetNamedPipeHandleState_impl(PyModuleDef *module, HANDLE named_pipe,
+_winapi_SetNamedPipeHandleState_impl(PyObject *module, HANDLE named_pipe,
                                      PyObject *mode,
                                      PyObject *max_collection_count,
                                      PyObject *collect_data_timeout)
-/*[clinic end generated code: output=25aa3c28dee223ce input=9142d72163d0faa6]*/
+/*[clinic end generated code: output=f2129d222cbfa095 input=9142d72163d0faa6]*/
 {
     PyObject *oArgs[3] = {mode, max_collection_count, collect_data_timeout};
     DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
@@ -1268,9 +1266,9 @@ Terminate the specified process and all of its threads.
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_TerminateProcess_impl(PyModuleDef *module, HANDLE handle,
+_winapi_TerminateProcess_impl(PyObject *module, HANDLE handle,
                               UINT exit_code)
-/*[clinic end generated code: output=937c1bb6219aca8b input=d6bc0aa1ee3bb4df]*/
+/*[clinic end generated code: output=f4e99ac3f0b1f34a input=d6bc0aa1ee3bb4df]*/
 {
     BOOL result;
 
@@ -1291,8 +1289,8 @@ _winapi.WaitNamedPipe
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_WaitNamedPipe_impl(PyModuleDef *module, LPCTSTR name, DWORD timeout)
-/*[clinic end generated code: output=5bca5e02f448c9d7 input=36fc781291b1862c]*/
+_winapi_WaitNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD timeout)
+/*[clinic end generated code: output=c2866f4439b1fe38 input=36fc781291b1862c]*/
 {
     BOOL success;
 
@@ -1316,10 +1314,9 @@ _winapi.WaitForMultipleObjects
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_WaitForMultipleObjects_impl(PyModuleDef *module,
-                                    PyObject *handle_seq, BOOL wait_flag,
-                                    DWORD milliseconds)
-/*[clinic end generated code: output=acb440728d06d130 input=36f76ca057cd28a0]*/
+_winapi_WaitForMultipleObjects_impl(PyObject *module, PyObject *handle_seq,
+                                    BOOL wait_flag, DWORD milliseconds)
+/*[clinic end generated code: output=295e3f00b8e45899 input=36f76ca057cd28a0]*/
 {
     DWORD result;
     HANDLE handles[MAXIMUM_WAIT_OBJECTS];
@@ -1393,9 +1390,9 @@ in milliseconds.
 [clinic start generated code]*/
 
 static long
-_winapi_WaitForSingleObject_impl(PyModuleDef *module, HANDLE handle,
+_winapi_WaitForSingleObject_impl(PyObject *module, HANDLE handle,
                                  DWORD milliseconds)
-/*[clinic end generated code: output=34ae40c269749c48 input=443d1ab076edc7b1]*/
+/*[clinic end generated code: output=3c4715d8f1b39859 input=443d1ab076edc7b1]*/
 {
     DWORD result;
 
@@ -1420,9 +1417,9 @@ _winapi.WriteFile
 [clinic start generated code]*/
 
 static PyObject *
-_winapi_WriteFile_impl(PyModuleDef *module, HANDLE handle, PyObject *buffer,
+_winapi_WriteFile_impl(PyObject *module, HANDLE handle, PyObject *buffer,
                        int use_overlapped)
-/*[clinic end generated code: output=65e70ea41f4d2a1d input=51846a5af52053fd]*/
+/*[clinic end generated code: output=2ca80f6bf3fa92e3 input=51846a5af52053fd]*/
 {
     Py_buffer _buf, *buf;
     DWORD len, written;
index f73c599..a4966b4 100644 (file)
@@ -745,8 +745,10 @@ array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
     np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
     if (np == NULL)
         return NULL;
-    memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
-           (ihigh-ilow) * a->ob_descr->itemsize);
+    if (ihigh > ilow) {
+        memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
+               (ihigh-ilow) * a->ob_descr->itemsize);
+    }
     return (PyObject *)np;
 }
 
@@ -804,9 +806,13 @@ array_concat(arrayobject *a, PyObject *bb)
     if (np == NULL) {
         return NULL;
     }
-    memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
-    memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
-           b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
+    if (Py_SIZE(a) > 0) {
+        memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
+    }
+    if (Py_SIZE(b) > 0) {
+        memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
+               b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
+    }
     return (PyObject *)np;
 #undef b
 }
@@ -826,7 +832,7 @@ array_repeat(arrayobject *a, Py_ssize_t n)
     np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
     if (np == NULL)
         return NULL;
-    if (n == 0)
+    if (size == 0)
         return (PyObject *)np;
     oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
     newbytes = oldbytes * n;
@@ -985,8 +991,10 @@ array_do_extend(arrayobject *self, PyObject *bb)
     size = oldsize + Py_SIZE(b);
     if (array_resize(self, size) == -1)
         return -1;
-    memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
-        b->ob_item, bbsize * b->ob_descr->itemsize);
+    if (bbsize > 0) {
+        memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
+            b->ob_item, bbsize * b->ob_descr->itemsize);
+    }
 
     return 0;
 #undef b
@@ -1268,7 +1276,7 @@ array_array_buffer_info_impl(arrayobject *self)
     }
     PyTuple_SET_ITEM(retval, 0, v);
 
-    v = PyLong_FromLong((long)(Py_SIZE(self)));
+    v = PyLong_FromSsize_t(Py_SIZE(self));
     if (v == NULL) {
         Py_DECREF(retval);
         return NULL;
@@ -1938,11 +1946,11 @@ Internal. Used for pickling support.
 [clinic start generated code]*/
 
 static PyObject *
-array__array_reconstructor_impl(PyModuleDef *module, PyTypeObject *arraytype,
+array__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype,
                                 int typecode,
                                 enum machine_format_code mformat_code,
                                 PyObject *items)
-/*[clinic end generated code: output=6ecbf0e8e4d92ab9 input=2464dc8f4c7736b5]*/
+/*[clinic end generated code: output=e05263141ba28365 input=2464dc8f4c7736b5]*/
 {
     PyObject *converted_items;
     PyObject *result;
index 306937e..1e131d2 100644 (file)
@@ -407,9 +407,9 @@ Return the value of sample index from the fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_getsample_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_getsample_impl(PyObject *module, Py_buffer *fragment, int width,
                        Py_ssize_t index)
-/*[clinic end generated code: output=3995e189fdc8ec16 input=88edbe2871393549]*/
+/*[clinic end generated code: output=8fe1b1775134f39a input=88edbe2871393549]*/
 {
     int val;
 
@@ -434,8 +434,8 @@ Return the maximum of the absolute value of all samples in a fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_max_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=85047ee1001f2305 input=32bea5ea0ac8c223]*/
+audioop_max_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=e6c5952714f1c3f0 input=32bea5ea0ac8c223]*/
 {
     Py_ssize_t i;
     unsigned int absval, max = 0;
@@ -462,8 +462,8 @@ Return the minimum and maximum values of all samples in the sound fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_minmax_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=ae8f5513c64fd569 input=89848e9b927a0696]*/
+audioop_minmax_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=473fda66b15c836e input=89848e9b927a0696]*/
 {
     Py_ssize_t i;
     /* -1 trick below is needed on Windows to support -0x80000000 without
@@ -491,8 +491,8 @@ Return the average over all samples in the fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_avg_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=7fccd645c95f4860 input=1114493c7611334d]*/
+audioop_avg_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=4410a4c12c3586e6 input=1114493c7611334d]*/
 {
     Py_ssize_t i;
     int avg;
@@ -520,8 +520,8 @@ Return the root-mean-square of the fragment, i.e. sqrt(sum(S_i^2)/n).
 [clinic start generated code]*/
 
 static PyObject *
-audioop_rms_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=7b398702c81b709d input=4cc57c6c94219d78]*/
+audioop_rms_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=1e7871c826445698 input=4cc57c6c94219d78]*/
 {
     Py_ssize_t i;
     unsigned int res;
@@ -594,9 +594,9 @@ Try to match reference as well as possible to a portion of fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_findfit_impl(PyModuleDef *module, Py_buffer *fragment,
+audioop_findfit_impl(PyObject *module, Py_buffer *fragment,
                      Py_buffer *reference)
-/*[clinic end generated code: output=609eedf5d823d6dd input=62c305605e183c9a]*/
+/*[clinic end generated code: output=5752306d83cbbada input=62c305605e183c9a]*/
 {
     const short *cp1, *cp2;
     Py_ssize_t len1, len2;
@@ -663,9 +663,9 @@ Return a factor F such that rms(add(fragment, mul(reference, -F))) is minimal.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_findfactor_impl(PyModuleDef *module, Py_buffer *fragment,
+audioop_findfactor_impl(PyObject *module, Py_buffer *fragment,
                         Py_buffer *reference)
-/*[clinic end generated code: output=5566a8c55de54f99 input=816680301d012b21]*/
+/*[clinic end generated code: output=14ea95652c1afcf8 input=816680301d012b21]*/
 {
     const short *cp1, *cp2;
     Py_ssize_t len;
@@ -705,9 +705,9 @@ Search fragment for a slice of specified number of samples with maximum energy.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_findmax_impl(PyModuleDef *module, Py_buffer *fragment,
+audioop_findmax_impl(PyObject *module, Py_buffer *fragment,
                      Py_ssize_t length)
-/*[clinic end generated code: output=01fe796fad2573bb input=2f304801ed42383c]*/
+/*[clinic end generated code: output=f008128233523040 input=2f304801ed42383c]*/
 {
     const short *cp1;
     Py_ssize_t len1;
@@ -759,8 +759,8 @@ Return the average peak-peak value over all samples in the fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_avgpp_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=06c8380fd6e34207 input=0b3cceeae420a7d9]*/
+audioop_avgpp_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=269596b0d5ae0b2b input=0b3cceeae420a7d9]*/
 {
     Py_ssize_t i;
     int prevval, prevextremevalid = 0, prevextreme = 0;
@@ -816,8 +816,8 @@ Return the maximum peak-peak value in the sound fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_maxpp_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=c300c0bd7e8535c0 input=671a13e1518f80a1]*/
+audioop_maxpp_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=5b918ed5dbbdb978 input=671a13e1518f80a1]*/
 {
     Py_ssize_t i;
     int prevval, prevextremevalid = 0, prevextreme = 0;
@@ -869,8 +869,8 @@ Return the number of zero crossings in the fragment passed as an argument.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_cross_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=99e6572d7d7cdbf1 input=b1b3f15b83f6b41a]*/
+audioop_cross_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=5938dcdd74a1f431 input=b1b3f15b83f6b41a]*/
 {
     Py_ssize_t i;
     int prevval;
@@ -900,9 +900,9 @@ Return a fragment that has all samples in the original fragment multiplied by th
 [clinic start generated code]*/
 
 static PyObject *
-audioop_mul_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_mul_impl(PyObject *module, Py_buffer *fragment, int width,
                  double factor)
-/*[clinic end generated code: output=1c7c31191ac86b10 input=c726667baa157d3c]*/
+/*[clinic end generated code: output=6cd48fe796da0ea4 input=c726667baa157d3c]*/
 {
     signed char *ncp;
     Py_ssize_t i;
@@ -942,9 +942,9 @@ Convert a stereo fragment to a mono fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_tomono_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_tomono_impl(PyObject *module, Py_buffer *fragment, int width,
                     double lfactor, double rfactor)
-/*[clinic end generated code: output=553f547c5e29e3b6 input=c4ec949b3f4dddfa]*/
+/*[clinic end generated code: output=235c8277216d4e4e input=c4ec949b3f4dddfa]*/
 {
     signed char *cp, *ncp;
     Py_ssize_t len, i;
@@ -991,9 +991,9 @@ Generate a stereo fragment from a mono fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_tostereo_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_tostereo_impl(PyObject *module, Py_buffer *fragment, int width,
                       double lfactor, double rfactor)
-/*[clinic end generated code: output=697bb6ba41e9dd2c input=27b6395ebfdff37a]*/
+/*[clinic end generated code: output=046f13defa5f1595 input=27b6395ebfdff37a]*/
 {
     signed char *ncp;
     Py_ssize_t i;
@@ -1039,9 +1039,9 @@ Return a fragment which is the addition of the two samples passed as parameters.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_add_impl(PyModuleDef *module, Py_buffer *fragment1,
+audioop_add_impl(PyObject *module, Py_buffer *fragment1,
                  Py_buffer *fragment2, int width)
-/*[clinic end generated code: output=fe6c12f143e0b027 input=4a8d4bae4c1605c7]*/
+/*[clinic end generated code: output=60140af4d1aab6f2 input=4a8d4bae4c1605c7]*/
 {
     signed char *ncp;
     Py_ssize_t i;
@@ -1098,9 +1098,8 @@ Return a fragment that is the original fragment with a bias added to each sample
 [clinic start generated code]*/
 
 static PyObject *
-audioop_bias_impl(PyModuleDef *module, Py_buffer *fragment, int width,
-                  int bias)
-/*[clinic end generated code: output=ac1f4dda20a01c26 input=2b5cce5c3bb4838c]*/
+audioop_bias_impl(PyObject *module, Py_buffer *fragment, int width, int bias)
+/*[clinic end generated code: output=6e0aa8f68f045093 input=2b5cce5c3bb4838c]*/
 {
     signed char *ncp;
     Py_ssize_t i;
@@ -1158,8 +1157,8 @@ Reverse the samples in a fragment and returns the modified fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_reverse_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=6ec3c91337f5925e input=668f890cf9f9d225]*/
+audioop_reverse_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=b44135698418da14 input=668f890cf9f9d225]*/
 {
     unsigned char *ncp;
     Py_ssize_t i;
@@ -1191,8 +1190,8 @@ Convert big-endian samples to little-endian and vice versa.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_byteswap_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=bfe4aa584b7a3f5b input=fae7611ceffa5c82]*/
+audioop_byteswap_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=50838a9e4b87cd4d input=fae7611ceffa5c82]*/
 {
     unsigned char *ncp;
     Py_ssize_t i;
@@ -1226,9 +1225,9 @@ Convert samples between 1-, 2-, 3- and 4-byte formats.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_lin2lin_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_lin2lin_impl(PyObject *module, Py_buffer *fragment, int width,
                      int newwidth)
-/*[clinic end generated code: output=cb6ca950d1df9898 input=5ce08c8aa2f24d96]*/
+/*[clinic end generated code: output=17b14109248f1d99 input=5ce08c8aa2f24d96]*/
 {
     unsigned char *ncp;
     Py_ssize_t i, j;
@@ -1284,10 +1283,10 @@ Convert the frame rate of the input fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_ratecv_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_ratecv_impl(PyObject *module, Py_buffer *fragment, int width,
                     int nchannels, int inrate, int outrate, PyObject *state,
                     int weightA, int weightB)
-/*[clinic end generated code: output=59e1787bfa49b9d9 input=aff3acdc94476191]*/
+/*[clinic end generated code: output=624038e843243139 input=aff3acdc94476191]*/
 {
     char *cp, *ncp;
     Py_ssize_t len;
@@ -1465,8 +1464,8 @@ Convert samples in the audio fragment to u-LAW encoding.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_lin2ulaw_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=26263cc877c5e1bc input=2450d1b870b6bac2]*/
+audioop_lin2ulaw_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=14fb62b16fe8ea8e input=2450d1b870b6bac2]*/
 {
     unsigned char *ncp;
     Py_ssize_t i;
@@ -1498,8 +1497,8 @@ Convert sound fragments in u-LAW encoding to linearly encoded sound fragments.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_ulaw2lin_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=9864cb34e3a1d876 input=45d53ddce5be7d06]*/
+audioop_ulaw2lin_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=378356b047521ba2 input=45d53ddce5be7d06]*/
 {
     unsigned char *cp;
     signed char *ncp;
@@ -1538,8 +1537,8 @@ Convert samples in the audio fragment to a-LAW encoding.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_lin2alaw_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=d5bf14bd0fe6fdcd input=ffb1ef8bb39da945]*/
+audioop_lin2alaw_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=d076f130121a82f0 input=ffb1ef8bb39da945]*/
 {
     unsigned char *ncp;
     Py_ssize_t i;
@@ -1571,8 +1570,8 @@ Convert sound fragments in a-LAW encoding to linearly encoded sound fragments.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_alaw2lin_impl(PyModuleDef *module, Py_buffer *fragment, int width)
-/*[clinic end generated code: output=d2b604ddd036e1cd input=4140626046cd1772]*/
+audioop_alaw2lin_impl(PyObject *module, Py_buffer *fragment, int width)
+/*[clinic end generated code: output=85c365ec559df647 input=4140626046cd1772]*/
 {
     unsigned char *cp;
     signed char *ncp;
@@ -1613,9 +1612,9 @@ Convert samples to 4 bit Intel/DVI ADPCM encoding.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_lin2adpcm_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_lin2adpcm_impl(PyObject *module, Py_buffer *fragment, int width,
                        PyObject *state)
-/*[clinic end generated code: output=93f0996f592b5ce5 input=12919d549b90c90a]*/
+/*[clinic end generated code: output=cc19f159f16c6793 input=12919d549b90c90a]*/
 {
     signed char *ncp;
     Py_ssize_t i;
@@ -1741,9 +1740,9 @@ Decode an Intel/DVI ADPCM coded fragment to a linear fragment.
 [clinic start generated code]*/
 
 static PyObject *
-audioop_adpcm2lin_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_adpcm2lin_impl(PyObject *module, Py_buffer *fragment, int width,
                        PyObject *state)
-/*[clinic end generated code: output=236cf6dc2c829181 input=f5221144f5ca9ef0]*/
+/*[clinic end generated code: output=3440ea105acb3456 input=f5221144f5ca9ef0]*/
 {
     signed char *cp;
     signed char *ncp;
index d920d23..125c1cb 100644 (file)
@@ -253,8 +253,8 @@ Decode a line of uuencoded data.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_a2b_uu_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=5779f39b0b48459f input=7cafeaf73df63d1c]*/
+binascii_a2b_uu_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=e027f8e0b0598742 input=7cafeaf73df63d1c]*/
 {
     unsigned char *ascii_data, *bin_data;
     int leftbits = 0;
@@ -339,8 +339,8 @@ Uuencode line of data.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_b2a_uu_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=181021b69bb9a414 input=00fdf458ce8b465b]*/
+binascii_b2a_uu_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=0070670e52e4aa6b input=00fdf458ce8b465b]*/
 {
     unsigned char *ascii_data, *bin_data;
     int leftbits = 0;
@@ -426,8 +426,8 @@ Decode a line of base64 data.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_a2b_base64_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=3e351b702bed56d2 input=5872acf6e1cac243]*/
+binascii_a2b_base64_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=0628223f19fd3f9b input=5872acf6e1cac243]*/
 {
     unsigned char *ascii_data, *bin_data;
     int leftbits = 0;
@@ -534,8 +534,8 @@ Base64-code line of data.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_b2a_base64_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=3cd61fbee2913285 input=14ec4e47371174a9]*/
+binascii_b2a_base64_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=4d96663170778dc3 input=14ec4e47371174a9]*/
 {
     unsigned char *ascii_data, *bin_data;
     int leftbits = 0;
@@ -601,8 +601,8 @@ Decode .hqx coding.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_a2b_hqx_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=60bcdbbd28b105cd input=0d914c680e0eed55]*/
+binascii_a2b_hqx_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=4d6d8c54d54ea1c1 input=0d914c680e0eed55]*/
 {
     unsigned char *ascii_data, *bin_data;
     int leftbits = 0;
@@ -684,8 +684,8 @@ Binhex RLE-code binary data.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_rlecode_hqx_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=0905da344dbf0648 input=e1f1712447a82b09]*/
+binascii_rlecode_hqx_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=393d79338f5f5629 input=e1f1712447a82b09]*/
 {
     unsigned char *in_data, *out_data;
     PyObject *rv;
@@ -748,8 +748,8 @@ Encode .hqx data.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_b2a_hqx_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=5a987810d5e3cdbb input=9596ebe019fe12ba]*/
+binascii_b2a_hqx_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=d0aa5a704bc9f7de input=9596ebe019fe12ba]*/
 {
     unsigned char *ascii_data, *bin_data;
     int leftbits = 0;
@@ -805,8 +805,8 @@ Decode hexbin RLE-coded string.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_rledecode_hqx_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=f7afd89b789946ab input=54cdd49fc014402c]*/
+binascii_rledecode_hqx_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=9826619565de1c6c input=54cdd49fc014402c]*/
 {
     unsigned char *in_data, *out_data;
     unsigned char in_byte, in_repeat;
@@ -915,12 +915,12 @@ binascii.crc_hqx -> unsigned_int
     crc: unsigned_int(bitwise=True)
     /
 
-Compute hqx CRC incrementally.
+Compute CRC-CCITT incrementally.
 [clinic start generated code]*/
 
 static unsigned int
-binascii_crc_hqx_impl(PyModuleDef *module, Py_buffer *data, unsigned int crc)
-/*[clinic end generated code: output=167c2dac62625717 input=add8c53712ccceda]*/
+binascii_crc_hqx_impl(PyObject *module, Py_buffer *data, unsigned int crc)
+/*[clinic end generated code: output=8ec2a78590d19170 input=f18240ff8c705b79]*/
 {
     unsigned char *bin_data;
     Py_ssize_t len;
@@ -1067,8 +1067,8 @@ Compute CRC-32 incrementally.
 [clinic start generated code]*/
 
 static unsigned int
-binascii_crc32_impl(PyModuleDef *module, Py_buffer *data, unsigned int crc)
-/*[clinic end generated code: output=620a961643393c4f input=bbe340bc99d25aa8]*/
+binascii_crc32_impl(PyObject *module, Py_buffer *data, unsigned int crc)
+/*[clinic end generated code: output=52cf59056a78593b input=bbe340bc99d25aa8]*/
 
 #ifdef USE_ZLIB_CRC32
 /* This was taken from zlibmodule.c PyZlib_crc32 (but is PY_SSIZE_T_CLEAN) */
@@ -1115,8 +1115,8 @@ available as "hexlify()".
 [clinic start generated code]*/
 
 static PyObject *
-binascii_b2a_hex_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=179318922c2f8fda input=96423cfa299ff3b1]*/
+binascii_b2a_hex_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=92fec1a95c9897a0 input=96423cfa299ff3b1]*/
 {
     return _Py_strhex_bytes((const char *)data->buf, data->len);
 }
@@ -1130,8 +1130,8 @@ The return value is a bytes object.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_hexlify_impl(PyModuleDef *module, Py_buffer *data)
-/*[clinic end generated code: output=6098440091fb61dc input=2e3afae7f083f061]*/
+binascii_hexlify_impl(PyObject *module, Py_buffer *data)
+/*[clinic end generated code: output=749e95e53c14880c input=2e3afae7f083f061]*/
 {
     return _Py_strhex_bytes((const char *)data->buf, data->len);
 }
@@ -1164,8 +1164,8 @@ This function is also available as "unhexlify()".
 [clinic start generated code]*/
 
 static PyObject *
-binascii_a2b_hex_impl(PyModuleDef *module, Py_buffer *hexstr)
-/*[clinic end generated code: output=d61da452b5c6d290 input=9e1e7f2f94db24fd]*/
+binascii_a2b_hex_impl(PyObject *module, Py_buffer *hexstr)
+/*[clinic end generated code: output=0cc1a139af0eeecb input=9e1e7f2f94db24fd]*/
 {
     char* argbuf;
     Py_ssize_t arglen;
@@ -1218,8 +1218,8 @@ hexstr must contain an even number of hex digits (upper or lower case).
 [clinic start generated code]*/
 
 static PyObject *
-binascii_unhexlify_impl(PyModuleDef *module, Py_buffer *hexstr)
-/*[clinic end generated code: output=17cec7544499803e input=dd8c012725f462da]*/
+binascii_unhexlify_impl(PyObject *module, Py_buffer *hexstr)
+/*[clinic end generated code: output=51a64c06c79629e3 input=dd8c012725f462da]*/
 {
     return binascii_a2b_hex_impl(module, hexstr);
 }
@@ -1250,8 +1250,8 @@ Decode a string of qp-encoded data.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_a2b_qp_impl(PyModuleDef *module, Py_buffer *data, int header)
-/*[clinic end generated code: output=a44ef88270352114 input=5187a0d3d8e54f3b]*/
+binascii_a2b_qp_impl(PyObject *module, Py_buffer *data, int header)
+/*[clinic end generated code: output=e99f7846cfb9bc53 input=5187a0d3d8e54f3b]*/
 {
     Py_ssize_t in, out;
     char ch;
@@ -1290,7 +1290,8 @@ binascii_a2b_qp_impl(PyModuleDef *module, Py_buffer *data, int header)
                 odata[out++] = '=';
                 in++;
             }
-            else if (((ascii_data[in] >= 'A' && ascii_data[in] <= 'F') ||
+            else if ((in + 1 < datalen) &&
+                     ((ascii_data[in] >= 'A' && ascii_data[in] <= 'F') ||
                       (ascii_data[in] >= 'a' && ascii_data[in] <= 'f') ||
                       (ascii_data[in] >= '0' && ascii_data[in] <= '9')) &&
                      ((ascii_data[in+1] >= 'A' && ascii_data[in+1] <= 'F') ||
@@ -1356,9 +1357,9 @@ are both encoded.  When quotetabs is set, space and tabs are encoded.
 [clinic start generated code]*/
 
 static PyObject *
-binascii_b2a_qp_impl(PyModuleDef *module, Py_buffer *data, int quotetabs,
+binascii_b2a_qp_impl(PyObject *module, Py_buffer *data, int quotetabs,
                      int istext, int header)
-/*[clinic end generated code: output=a87ca9ccb94e2a9f input=7f2a9aaa008e92b2]*/
+/*[clinic end generated code: output=e9884472ebb1a94c input=7f2a9aaa008e92b2]*/
 {
     Py_ssize_t in, out;
     unsigned char *databuf, *odata;
@@ -1383,11 +1384,13 @@ binascii_b2a_qp_impl(PyModuleDef *module, Py_buffer *data, int quotetabs,
     /* First, scan to see how many characters need to be encoded */
     in = 0;
     while (in < datalen) {
+        Py_ssize_t delta = 0;
         if ((databuf[in] > 126) ||
             (databuf[in] == '=') ||
             (header && databuf[in] == '_') ||
             ((databuf[in] == '.') && (linelen == 0) &&
-             (databuf[in+1] == '\n' || databuf[in+1] == '\r' || databuf[in+1] == 0)) ||
+             (in + 1 == datalen || databuf[in+1] == '\n' ||
+              databuf[in+1] == '\r' || databuf[in+1] == 0)) ||
             (!istext && ((databuf[in] == '\r') || (databuf[in] == '\n'))) ||
             ((databuf[in] == '\t' || databuf[in] == ' ') && (in + 1 == datalen)) ||
             ((databuf[in] < 33) &&
@@ -1397,12 +1400,12 @@ binascii_b2a_qp_impl(PyModuleDef *module, Py_buffer *data, int quotetabs,
             if ((linelen + 3) >= MAXLINESIZE) {
                 linelen = 0;
                 if (crlf)
-                    odatalen += 3;
+                    delta += 3;
                 else
-                    odatalen += 2;
+                    delta += 2;
             }
             linelen += 3;
-            odatalen += 3;
+            delta += 3;
             in++;
         }
         else {
@@ -1414,11 +1417,11 @@ binascii_b2a_qp_impl(PyModuleDef *module, Py_buffer *data, int quotetabs,
                 linelen = 0;
                 /* Protect against whitespace on end of line */
                 if (in && ((databuf[in-1] == ' ') || (databuf[in-1] == '\t')))
-                    odatalen += 2;
+                    delta += 2;
                 if (crlf)
-                    odatalen += 2;
+                    delta += 2;
                 else
-                    odatalen += 1;
+                    delta += 1;
                 if (databuf[in] == '\r')
                     in += 2;
                 else
@@ -1430,15 +1433,20 @@ binascii_b2a_qp_impl(PyModuleDef *module, Py_buffer *data, int quotetabs,
                     (linelen + 1) >= MAXLINESIZE) {
                     linelen = 0;
                     if (crlf)
-                        odatalen += 3;
+                        delta += 3;
                     else
-                        odatalen += 2;
+                        delta += 2;
                 }
                 linelen++;
-                odatalen++;
+                delta++;
                 in++;
             }
         }
+        if (PY_SSIZE_T_MAX - delta < odatalen) {
+            PyErr_NoMemory();
+            return NULL;
+        }
+        odatalen += delta;
     }
 
     /* We allocate the output same size as input, this is overkill.
@@ -1458,13 +1466,13 @@ binascii_b2a_qp_impl(PyModuleDef *module, Py_buffer *data, int quotetabs,
             (databuf[in] == '=') ||
             (header && databuf[in] == '_') ||
             ((databuf[in] == '.') && (linelen == 0) &&
-             (databuf[in+1] == '\n' || databuf[in+1] == '\r' || databuf[in+1] == 0)) ||
+             (in + 1 == datalen || databuf[in+1] == '\n' ||
+              databuf[in+1] == '\r' || databuf[in+1] == 0)) ||
             (!istext && ((databuf[in] == '\r') || (databuf[in] == '\n'))) ||
             ((databuf[in] == '\t' || databuf[in] == ' ') && (in + 1 == datalen)) ||
             ((databuf[in] < 33) &&
              (databuf[in] != '\r') && (databuf[in] != '\n') &&
-             (quotetabs ||
-            (!quotetabs && ((databuf[in] != '\t') && (databuf[in] != ' '))))))
+             (quotetabs || ((databuf[in] != '\t') && (databuf[in] != ' ')))))
         {
             if ((linelen + 3 )>= MAXLINESIZE) {
                 odata[out++] = '=';
index e1cdb2c..f5c8421 100644 (file)
@@ -1847,8 +1847,8 @@ _multibytecodec.__create_codec
 [clinic start generated code]*/
 
 static PyObject *
-_multibytecodec___create_codec(PyModuleDef *module, PyObject *arg)
-/*[clinic end generated code: output=fbe74f6510640163 input=6840b2a6b183fcfa]*/
+_multibytecodec___create_codec(PyObject *module, PyObject *arg)
+/*[clinic end generated code: output=cfa3dce8260e809d input=6840b2a6b183fcfa]*/
 {
     MultibyteCodecObject *self;
     MultibyteCodec *codec;
index e94be11..af06c6d 100644 (file)
@@ -25,10 +25,10 @@ PyDoc_STRVAR(_codecs_lookup__doc__,
     {"lookup", (PyCFunction)_codecs_lookup, METH_O, _codecs_lookup__doc__},
 
 static PyObject *
-_codecs_lookup_impl(PyModuleDef *module, const char *encoding);
+_codecs_lookup_impl(PyObject *module, const char *encoding);
 
 static PyObject *
-_codecs_lookup(PyModuleDef *module, PyObject *arg)
+_codecs_lookup(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     const char *encoding;
@@ -57,11 +57,11 @@ PyDoc_STRVAR(_codecs_encode__doc__,
     {"encode", (PyCFunction)_codecs_encode, METH_VARARGS|METH_KEYWORDS, _codecs_encode__doc__},
 
 static PyObject *
-_codecs_encode_impl(PyModuleDef *module, PyObject *obj, const char *encoding,
+_codecs_encode_impl(PyObject *module, PyObject *obj, const char *encoding,
                     const char *errors);
 
 static PyObject *
-_codecs_encode(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_codecs_encode(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"obj", "encoding", "errors", NULL};
@@ -94,11 +94,11 @@ PyDoc_STRVAR(_codecs_decode__doc__,
     {"decode", (PyCFunction)_codecs_decode, METH_VARARGS|METH_KEYWORDS, _codecs_decode__doc__},
 
 static PyObject *
-_codecs_decode_impl(PyModuleDef *module, PyObject *obj, const char *encoding,
+_codecs_decode_impl(PyObject *module, PyObject *obj, const char *encoding,
                     const char *errors);
 
 static PyObject *
-_codecs_decode(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_codecs_decode(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"obj", "encoding", "errors", NULL};
@@ -125,10 +125,10 @@ PyDoc_STRVAR(_codecs__forget_codec__doc__,
     {"_forget_codec", (PyCFunction)_codecs__forget_codec, METH_O, _codecs__forget_codec__doc__},
 
 static PyObject *
-_codecs__forget_codec_impl(PyModuleDef *module, const char *encoding);
+_codecs__forget_codec_impl(PyObject *module, const char *encoding);
 
 static PyObject *
-_codecs__forget_codec(PyModuleDef *module, PyObject *arg)
+_codecs__forget_codec(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     const char *encoding;
@@ -150,11 +150,11 @@ PyDoc_STRVAR(_codecs_escape_decode__doc__,
     {"escape_decode", (PyCFunction)_codecs_escape_decode, METH_VARARGS, _codecs_escape_decode__doc__},
 
 static PyObject *
-_codecs_escape_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_escape_decode_impl(PyObject *module, Py_buffer *data,
                            const char *errors);
 
 static PyObject *
-_codecs_escape_decode(PyModuleDef *module, PyObject *args)
+_codecs_escape_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -182,11 +182,11 @@ PyDoc_STRVAR(_codecs_escape_encode__doc__,
     {"escape_encode", (PyCFunction)_codecs_escape_encode, METH_VARARGS, _codecs_escape_encode__doc__},
 
 static PyObject *
-_codecs_escape_encode_impl(PyModuleDef *module, PyObject *data,
+_codecs_escape_encode_impl(PyObject *module, PyObject *data,
                            const char *errors);
 
 static PyObject *
-_codecs_escape_encode(PyModuleDef *module, PyObject *args)
+_codecs_escape_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *data;
@@ -210,11 +210,11 @@ PyDoc_STRVAR(_codecs_unicode_internal_decode__doc__,
     {"unicode_internal_decode", (PyCFunction)_codecs_unicode_internal_decode, METH_VARARGS, _codecs_unicode_internal_decode__doc__},
 
 static PyObject *
-_codecs_unicode_internal_decode_impl(PyModuleDef *module, PyObject *obj,
+_codecs_unicode_internal_decode_impl(PyObject *module, PyObject *obj,
                                      const char *errors);
 
 static PyObject *
-_codecs_unicode_internal_decode(PyModuleDef *module, PyObject *args)
+_codecs_unicode_internal_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *obj;
@@ -238,11 +238,11 @@ PyDoc_STRVAR(_codecs_utf_7_decode__doc__,
     {"utf_7_decode", (PyCFunction)_codecs_utf_7_decode, METH_VARARGS, _codecs_utf_7_decode__doc__},
 
 static PyObject *
-_codecs_utf_7_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_7_decode_impl(PyObject *module, Py_buffer *data,
                           const char *errors, int final);
 
 static PyObject *
-_codecs_utf_7_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_7_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -271,11 +271,11 @@ PyDoc_STRVAR(_codecs_utf_8_decode__doc__,
     {"utf_8_decode", (PyCFunction)_codecs_utf_8_decode, METH_VARARGS, _codecs_utf_8_decode__doc__},
 
 static PyObject *
-_codecs_utf_8_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_8_decode_impl(PyObject *module, Py_buffer *data,
                           const char *errors, int final);
 
 static PyObject *
-_codecs_utf_8_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_8_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -304,11 +304,11 @@ PyDoc_STRVAR(_codecs_utf_16_decode__doc__,
     {"utf_16_decode", (PyCFunction)_codecs_utf_16_decode, METH_VARARGS, _codecs_utf_16_decode__doc__},
 
 static PyObject *
-_codecs_utf_16_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_16_decode_impl(PyObject *module, Py_buffer *data,
                            const char *errors, int final);
 
 static PyObject *
-_codecs_utf_16_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_16_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -337,11 +337,11 @@ PyDoc_STRVAR(_codecs_utf_16_le_decode__doc__,
     {"utf_16_le_decode", (PyCFunction)_codecs_utf_16_le_decode, METH_VARARGS, _codecs_utf_16_le_decode__doc__},
 
 static PyObject *
-_codecs_utf_16_le_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_16_le_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int final);
 
 static PyObject *
-_codecs_utf_16_le_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_16_le_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -370,11 +370,11 @@ PyDoc_STRVAR(_codecs_utf_16_be_decode__doc__,
     {"utf_16_be_decode", (PyCFunction)_codecs_utf_16_be_decode, METH_VARARGS, _codecs_utf_16_be_decode__doc__},
 
 static PyObject *
-_codecs_utf_16_be_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_16_be_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int final);
 
 static PyObject *
-_codecs_utf_16_be_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_16_be_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -404,11 +404,11 @@ PyDoc_STRVAR(_codecs_utf_16_ex_decode__doc__,
     {"utf_16_ex_decode", (PyCFunction)_codecs_utf_16_ex_decode, METH_VARARGS, _codecs_utf_16_ex_decode__doc__},
 
 static PyObject *
-_codecs_utf_16_ex_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_16_ex_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int byteorder, int final);
 
 static PyObject *
-_codecs_utf_16_ex_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_16_ex_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -438,11 +438,11 @@ PyDoc_STRVAR(_codecs_utf_32_decode__doc__,
     {"utf_32_decode", (PyCFunction)_codecs_utf_32_decode, METH_VARARGS, _codecs_utf_32_decode__doc__},
 
 static PyObject *
-_codecs_utf_32_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_32_decode_impl(PyObject *module, Py_buffer *data,
                            const char *errors, int final);
 
 static PyObject *
-_codecs_utf_32_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_32_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -471,11 +471,11 @@ PyDoc_STRVAR(_codecs_utf_32_le_decode__doc__,
     {"utf_32_le_decode", (PyCFunction)_codecs_utf_32_le_decode, METH_VARARGS, _codecs_utf_32_le_decode__doc__},
 
 static PyObject *
-_codecs_utf_32_le_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_32_le_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int final);
 
 static PyObject *
-_codecs_utf_32_le_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_32_le_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -504,11 +504,11 @@ PyDoc_STRVAR(_codecs_utf_32_be_decode__doc__,
     {"utf_32_be_decode", (PyCFunction)_codecs_utf_32_be_decode, METH_VARARGS, _codecs_utf_32_be_decode__doc__},
 
 static PyObject *
-_codecs_utf_32_be_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_32_be_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int final);
 
 static PyObject *
-_codecs_utf_32_be_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_32_be_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -538,11 +538,11 @@ PyDoc_STRVAR(_codecs_utf_32_ex_decode__doc__,
     {"utf_32_ex_decode", (PyCFunction)_codecs_utf_32_ex_decode, METH_VARARGS, _codecs_utf_32_ex_decode__doc__},
 
 static PyObject *
-_codecs_utf_32_ex_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_utf_32_ex_decode_impl(PyObject *module, Py_buffer *data,
                               const char *errors, int byteorder, int final);
 
 static PyObject *
-_codecs_utf_32_ex_decode(PyModuleDef *module, PyObject *args)
+_codecs_utf_32_ex_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -572,11 +572,11 @@ PyDoc_STRVAR(_codecs_unicode_escape_decode__doc__,
     {"unicode_escape_decode", (PyCFunction)_codecs_unicode_escape_decode, METH_VARARGS, _codecs_unicode_escape_decode__doc__},
 
 static PyObject *
-_codecs_unicode_escape_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_unicode_escape_decode_impl(PyObject *module, Py_buffer *data,
                                    const char *errors);
 
 static PyObject *
-_codecs_unicode_escape_decode(PyModuleDef *module, PyObject *args)
+_codecs_unicode_escape_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -604,11 +604,11 @@ PyDoc_STRVAR(_codecs_raw_unicode_escape_decode__doc__,
     {"raw_unicode_escape_decode", (PyCFunction)_codecs_raw_unicode_escape_decode, METH_VARARGS, _codecs_raw_unicode_escape_decode__doc__},
 
 static PyObject *
-_codecs_raw_unicode_escape_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_raw_unicode_escape_decode_impl(PyObject *module, Py_buffer *data,
                                        const char *errors);
 
 static PyObject *
-_codecs_raw_unicode_escape_decode(PyModuleDef *module, PyObject *args)
+_codecs_raw_unicode_escape_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -636,11 +636,11 @@ PyDoc_STRVAR(_codecs_latin_1_decode__doc__,
     {"latin_1_decode", (PyCFunction)_codecs_latin_1_decode, METH_VARARGS, _codecs_latin_1_decode__doc__},
 
 static PyObject *
-_codecs_latin_1_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_latin_1_decode_impl(PyObject *module, Py_buffer *data,
                             const char *errors);
 
 static PyObject *
-_codecs_latin_1_decode(PyModuleDef *module, PyObject *args)
+_codecs_latin_1_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -668,11 +668,11 @@ PyDoc_STRVAR(_codecs_ascii_decode__doc__,
     {"ascii_decode", (PyCFunction)_codecs_ascii_decode, METH_VARARGS, _codecs_ascii_decode__doc__},
 
 static PyObject *
-_codecs_ascii_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_ascii_decode_impl(PyObject *module, Py_buffer *data,
                           const char *errors);
 
 static PyObject *
-_codecs_ascii_decode(PyModuleDef *module, PyObject *args)
+_codecs_ascii_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -700,11 +700,11 @@ PyDoc_STRVAR(_codecs_charmap_decode__doc__,
     {"charmap_decode", (PyCFunction)_codecs_charmap_decode, METH_VARARGS, _codecs_charmap_decode__doc__},
 
 static PyObject *
-_codecs_charmap_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_charmap_decode_impl(PyObject *module, Py_buffer *data,
                             const char *errors, PyObject *mapping);
 
 static PyObject *
-_codecs_charmap_decode(PyModuleDef *module, PyObject *args)
+_codecs_charmap_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -735,11 +735,11 @@ PyDoc_STRVAR(_codecs_mbcs_decode__doc__,
     {"mbcs_decode", (PyCFunction)_codecs_mbcs_decode, METH_VARARGS, _codecs_mbcs_decode__doc__},
 
 static PyObject *
-_codecs_mbcs_decode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_mbcs_decode_impl(PyObject *module, Py_buffer *data,
                          const char *errors, int final);
 
 static PyObject *
-_codecs_mbcs_decode(PyModuleDef *module, PyObject *args)
+_codecs_mbcs_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -772,11 +772,11 @@ PyDoc_STRVAR(_codecs_code_page_decode__doc__,
     {"code_page_decode", (PyCFunction)_codecs_code_page_decode, METH_VARARGS, _codecs_code_page_decode__doc__},
 
 static PyObject *
-_codecs_code_page_decode_impl(PyModuleDef *module, int codepage,
+_codecs_code_page_decode_impl(PyObject *module, int codepage,
                               Py_buffer *data, const char *errors, int final);
 
 static PyObject *
-_codecs_code_page_decode(PyModuleDef *module, PyObject *args)
+_codecs_code_page_decode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int codepage;
@@ -808,11 +808,11 @@ PyDoc_STRVAR(_codecs_readbuffer_encode__doc__,
     {"readbuffer_encode", (PyCFunction)_codecs_readbuffer_encode, METH_VARARGS, _codecs_readbuffer_encode__doc__},
 
 static PyObject *
-_codecs_readbuffer_encode_impl(PyModuleDef *module, Py_buffer *data,
+_codecs_readbuffer_encode_impl(PyObject *module, Py_buffer *data,
                                const char *errors);
 
 static PyObject *
-_codecs_readbuffer_encode(PyModuleDef *module, PyObject *args)
+_codecs_readbuffer_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -840,11 +840,11 @@ PyDoc_STRVAR(_codecs_unicode_internal_encode__doc__,
     {"unicode_internal_encode", (PyCFunction)_codecs_unicode_internal_encode, METH_VARARGS, _codecs_unicode_internal_encode__doc__},
 
 static PyObject *
-_codecs_unicode_internal_encode_impl(PyModuleDef *module, PyObject *obj,
+_codecs_unicode_internal_encode_impl(PyObject *module, PyObject *obj,
                                      const char *errors);
 
 static PyObject *
-_codecs_unicode_internal_encode(PyModuleDef *module, PyObject *args)
+_codecs_unicode_internal_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *obj;
@@ -868,11 +868,11 @@ PyDoc_STRVAR(_codecs_utf_7_encode__doc__,
     {"utf_7_encode", (PyCFunction)_codecs_utf_7_encode, METH_VARARGS, _codecs_utf_7_encode__doc__},
 
 static PyObject *
-_codecs_utf_7_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_7_encode_impl(PyObject *module, PyObject *str,
                           const char *errors);
 
 static PyObject *
-_codecs_utf_7_encode(PyModuleDef *module, PyObject *args)
+_codecs_utf_7_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -896,11 +896,11 @@ PyDoc_STRVAR(_codecs_utf_8_encode__doc__,
     {"utf_8_encode", (PyCFunction)_codecs_utf_8_encode, METH_VARARGS, _codecs_utf_8_encode__doc__},
 
 static PyObject *
-_codecs_utf_8_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_8_encode_impl(PyObject *module, PyObject *str,
                           const char *errors);
 
 static PyObject *
-_codecs_utf_8_encode(PyModuleDef *module, PyObject *args)
+_codecs_utf_8_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -924,11 +924,11 @@ PyDoc_STRVAR(_codecs_utf_16_encode__doc__,
     {"utf_16_encode", (PyCFunction)_codecs_utf_16_encode, METH_VARARGS, _codecs_utf_16_encode__doc__},
 
 static PyObject *
-_codecs_utf_16_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_16_encode_impl(PyObject *module, PyObject *str,
                            const char *errors, int byteorder);
 
 static PyObject *
-_codecs_utf_16_encode(PyModuleDef *module, PyObject *args)
+_codecs_utf_16_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -953,11 +953,11 @@ PyDoc_STRVAR(_codecs_utf_16_le_encode__doc__,
     {"utf_16_le_encode", (PyCFunction)_codecs_utf_16_le_encode, METH_VARARGS, _codecs_utf_16_le_encode__doc__},
 
 static PyObject *
-_codecs_utf_16_le_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_16_le_encode_impl(PyObject *module, PyObject *str,
                               const char *errors);
 
 static PyObject *
-_codecs_utf_16_le_encode(PyModuleDef *module, PyObject *args)
+_codecs_utf_16_le_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -981,11 +981,11 @@ PyDoc_STRVAR(_codecs_utf_16_be_encode__doc__,
     {"utf_16_be_encode", (PyCFunction)_codecs_utf_16_be_encode, METH_VARARGS, _codecs_utf_16_be_encode__doc__},
 
 static PyObject *
-_codecs_utf_16_be_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_16_be_encode_impl(PyObject *module, PyObject *str,
                               const char *errors);
 
 static PyObject *
-_codecs_utf_16_be_encode(PyModuleDef *module, PyObject *args)
+_codecs_utf_16_be_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1009,11 +1009,11 @@ PyDoc_STRVAR(_codecs_utf_32_encode__doc__,
     {"utf_32_encode", (PyCFunction)_codecs_utf_32_encode, METH_VARARGS, _codecs_utf_32_encode__doc__},
 
 static PyObject *
-_codecs_utf_32_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_32_encode_impl(PyObject *module, PyObject *str,
                            const char *errors, int byteorder);
 
 static PyObject *
-_codecs_utf_32_encode(PyModuleDef *module, PyObject *args)
+_codecs_utf_32_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1038,11 +1038,11 @@ PyDoc_STRVAR(_codecs_utf_32_le_encode__doc__,
     {"utf_32_le_encode", (PyCFunction)_codecs_utf_32_le_encode, METH_VARARGS, _codecs_utf_32_le_encode__doc__},
 
 static PyObject *
-_codecs_utf_32_le_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_32_le_encode_impl(PyObject *module, PyObject *str,
                               const char *errors);
 
 static PyObject *
-_codecs_utf_32_le_encode(PyModuleDef *module, PyObject *args)
+_codecs_utf_32_le_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1066,11 +1066,11 @@ PyDoc_STRVAR(_codecs_utf_32_be_encode__doc__,
     {"utf_32_be_encode", (PyCFunction)_codecs_utf_32_be_encode, METH_VARARGS, _codecs_utf_32_be_encode__doc__},
 
 static PyObject *
-_codecs_utf_32_be_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_utf_32_be_encode_impl(PyObject *module, PyObject *str,
                               const char *errors);
 
 static PyObject *
-_codecs_utf_32_be_encode(PyModuleDef *module, PyObject *args)
+_codecs_utf_32_be_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1094,11 +1094,11 @@ PyDoc_STRVAR(_codecs_unicode_escape_encode__doc__,
     {"unicode_escape_encode", (PyCFunction)_codecs_unicode_escape_encode, METH_VARARGS, _codecs_unicode_escape_encode__doc__},
 
 static PyObject *
-_codecs_unicode_escape_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_unicode_escape_encode_impl(PyObject *module, PyObject *str,
                                    const char *errors);
 
 static PyObject *
-_codecs_unicode_escape_encode(PyModuleDef *module, PyObject *args)
+_codecs_unicode_escape_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1122,11 +1122,11 @@ PyDoc_STRVAR(_codecs_raw_unicode_escape_encode__doc__,
     {"raw_unicode_escape_encode", (PyCFunction)_codecs_raw_unicode_escape_encode, METH_VARARGS, _codecs_raw_unicode_escape_encode__doc__},
 
 static PyObject *
-_codecs_raw_unicode_escape_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_raw_unicode_escape_encode_impl(PyObject *module, PyObject *str,
                                        const char *errors);
 
 static PyObject *
-_codecs_raw_unicode_escape_encode(PyModuleDef *module, PyObject *args)
+_codecs_raw_unicode_escape_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1150,11 +1150,11 @@ PyDoc_STRVAR(_codecs_latin_1_encode__doc__,
     {"latin_1_encode", (PyCFunction)_codecs_latin_1_encode, METH_VARARGS, _codecs_latin_1_encode__doc__},
 
 static PyObject *
-_codecs_latin_1_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_latin_1_encode_impl(PyObject *module, PyObject *str,
                             const char *errors);
 
 static PyObject *
-_codecs_latin_1_encode(PyModuleDef *module, PyObject *args)
+_codecs_latin_1_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1178,11 +1178,11 @@ PyDoc_STRVAR(_codecs_ascii_encode__doc__,
     {"ascii_encode", (PyCFunction)_codecs_ascii_encode, METH_VARARGS, _codecs_ascii_encode__doc__},
 
 static PyObject *
-_codecs_ascii_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_ascii_encode_impl(PyObject *module, PyObject *str,
                           const char *errors);
 
 static PyObject *
-_codecs_ascii_encode(PyModuleDef *module, PyObject *args)
+_codecs_ascii_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1206,11 +1206,11 @@ PyDoc_STRVAR(_codecs_charmap_encode__doc__,
     {"charmap_encode", (PyCFunction)_codecs_charmap_encode, METH_VARARGS, _codecs_charmap_encode__doc__},
 
 static PyObject *
-_codecs_charmap_encode_impl(PyModuleDef *module, PyObject *str,
+_codecs_charmap_encode_impl(PyObject *module, PyObject *str,
                             const char *errors, PyObject *mapping);
 
 static PyObject *
-_codecs_charmap_encode(PyModuleDef *module, PyObject *args)
+_codecs_charmap_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1235,10 +1235,10 @@ PyDoc_STRVAR(_codecs_charmap_build__doc__,
     {"charmap_build", (PyCFunction)_codecs_charmap_build, METH_O, _codecs_charmap_build__doc__},
 
 static PyObject *
-_codecs_charmap_build_impl(PyModuleDef *module, PyObject *map);
+_codecs_charmap_build_impl(PyObject *module, PyObject *map);
 
 static PyObject *
-_codecs_charmap_build(PyModuleDef *module, PyObject *arg)
+_codecs_charmap_build(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *map;
@@ -1262,11 +1262,10 @@ PyDoc_STRVAR(_codecs_mbcs_encode__doc__,
     {"mbcs_encode", (PyCFunction)_codecs_mbcs_encode, METH_VARARGS, _codecs_mbcs_encode__doc__},
 
 static PyObject *
-_codecs_mbcs_encode_impl(PyModuleDef *module, PyObject *str,
-                         const char *errors);
+_codecs_mbcs_encode_impl(PyObject *module, PyObject *str, const char *errors);
 
 static PyObject *
-_codecs_mbcs_encode(PyModuleDef *module, PyObject *args)
+_codecs_mbcs_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *str;
@@ -1294,11 +1293,11 @@ PyDoc_STRVAR(_codecs_code_page_encode__doc__,
     {"code_page_encode", (PyCFunction)_codecs_code_page_encode, METH_VARARGS, _codecs_code_page_encode__doc__},
 
 static PyObject *
-_codecs_code_page_encode_impl(PyModuleDef *module, int code_page,
-                              PyObject *str, const char *errors);
+_codecs_code_page_encode_impl(PyObject *module, int code_page, PyObject *str,
+                              const char *errors);
 
 static PyObject *
-_codecs_code_page_encode(PyModuleDef *module, PyObject *args)
+_codecs_code_page_encode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int code_page;
@@ -1330,11 +1329,11 @@ PyDoc_STRVAR(_codecs_register_error__doc__,
     {"register_error", (PyCFunction)_codecs_register_error, METH_VARARGS, _codecs_register_error__doc__},
 
 static PyObject *
-_codecs_register_error_impl(PyModuleDef *module, const char *errors,
+_codecs_register_error_impl(PyObject *module, const char *errors,
                             PyObject *handler);
 
 static PyObject *
-_codecs_register_error(PyModuleDef *module, PyObject *args)
+_codecs_register_error(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     const char *errors;
@@ -1362,10 +1361,10 @@ PyDoc_STRVAR(_codecs_lookup_error__doc__,
     {"lookup_error", (PyCFunction)_codecs_lookup_error, METH_O, _codecs_lookup_error__doc__},
 
 static PyObject *
-_codecs_lookup_error_impl(PyModuleDef *module, const char *name);
+_codecs_lookup_error_impl(PyObject *module, const char *name);
 
 static PyObject *
-_codecs_lookup_error(PyModuleDef *module, PyObject *arg)
+_codecs_lookup_error(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     const char *name;
@@ -1393,4 +1392,4 @@ exit:
 #ifndef _CODECS_CODE_PAGE_ENCODE_METHODDEF
     #define _CODECS_CODE_PAGE_ENCODE_METHODDEF
 #endif /* !defined(_CODECS_CODE_PAGE_ENCODE_METHODDEF) */
-/*[clinic end generated code: output=9c9967048027c1c7 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=42fed94e2ab765ba input=a9049054013a1b77]*/
index b8ec31e..a3c371c 100644 (file)
@@ -17,10 +17,10 @@ PyDoc_STRVAR(crypt_crypt__doc__,
     {"crypt", (PyCFunction)crypt_crypt, METH_VARARGS, crypt_crypt__doc__},
 
 static PyObject *
-crypt_crypt_impl(PyModuleDef *module, const char *word, const char *salt);
+crypt_crypt_impl(PyObject *module, const char *word, const char *salt);
 
 static PyObject *
-crypt_crypt(PyModuleDef *module, PyObject *args)
+crypt_crypt(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     const char *word;
@@ -34,4 +34,4 @@ crypt_crypt(PyModuleDef *module, PyObject *args)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=22c295c9bce018c4 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=e0493a9691537690 input=a9049054013a1b77]*/
index 8474e02..49cbceb 100644 (file)
@@ -119,11 +119,11 @@ PyDoc_STRVAR(dbmopen__doc__,
     {"open", (PyCFunction)dbmopen, METH_VARARGS, dbmopen__doc__},
 
 static PyObject *
-dbmopen_impl(PyModuleDef *module, const char *filename, const char *flags,
+dbmopen_impl(PyObject *module, const char *filename, const char *flags,
              int mode);
 
 static PyObject *
-dbmopen(PyModuleDef *module, PyObject *args)
+dbmopen(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     const char *filename;
@@ -138,4 +138,4 @@ dbmopen(PyModuleDef *module, PyObject *args)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=1d92e81b28c558d0 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=fff12f168cdf8b43 input=a9049054013a1b77]*/
index 110ad9a..2d87cfc 100644 (file)
@@ -231,11 +231,10 @@ PyDoc_STRVAR(dbmopen__doc__,
     {"open", (PyCFunction)dbmopen, METH_VARARGS, dbmopen__doc__},
 
 static PyObject *
-dbmopen_impl(PyModuleDef *module, const char *name, const char *flags,
-             int mode);
+dbmopen_impl(PyObject *module, const char *name, const char *flags, int mode);
 
 static PyObject *
-dbmopen(PyModuleDef *module, PyObject *args)
+dbmopen(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     const char *name;
@@ -250,4 +249,4 @@ dbmopen(PyModuleDef *module, PyObject *args)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=d3d8d871bcccb68a input=a9049054013a1b77]*/
+/*[clinic end generated code: output=9ac7a89858a9765f input=a9049054013a1b77]*/
index 59d9d51..f8d38ea 100644 (file)
@@ -163,10 +163,10 @@ PyDoc_STRVAR(_lzma_is_check_supported__doc__,
     {"is_check_supported", (PyCFunction)_lzma_is_check_supported, METH_O, _lzma_is_check_supported__doc__},
 
 static PyObject *
-_lzma_is_check_supported_impl(PyModuleDef *module, int check_id);
+_lzma_is_check_supported_impl(PyObject *module, int check_id);
 
 static PyObject *
-_lzma_is_check_supported(PyModuleDef *module, PyObject *arg)
+_lzma_is_check_supported(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int check_id;
@@ -191,10 +191,10 @@ PyDoc_STRVAR(_lzma__encode_filter_properties__doc__,
     {"_encode_filter_properties", (PyCFunction)_lzma__encode_filter_properties, METH_O, _lzma__encode_filter_properties__doc__},
 
 static PyObject *
-_lzma__encode_filter_properties_impl(PyModuleDef *module, lzma_filter filter);
+_lzma__encode_filter_properties_impl(PyObject *module, lzma_filter filter);
 
 static PyObject *
-_lzma__encode_filter_properties(PyModuleDef *module, PyObject *arg)
+_lzma__encode_filter_properties(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     lzma_filter filter = {LZMA_VLI_UNKNOWN, NULL};
@@ -223,11 +223,11 @@ PyDoc_STRVAR(_lzma__decode_filter_properties__doc__,
     {"_decode_filter_properties", (PyCFunction)_lzma__decode_filter_properties, METH_VARARGS, _lzma__decode_filter_properties__doc__},
 
 static PyObject *
-_lzma__decode_filter_properties_impl(PyModuleDef *module, lzma_vli filter_id,
+_lzma__decode_filter_properties_impl(PyObject *module, lzma_vli filter_id,
                                      Py_buffer *encoded_props);
 
 static PyObject *
-_lzma__decode_filter_properties(PyModuleDef *module, PyObject *args)
+_lzma__decode_filter_properties(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     lzma_vli filter_id;
@@ -245,4 +245,4 @@ exit:
 
     return return_value;
 }
-/*[clinic end generated code: output=2d3e0842be3d3fe1 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=fada06020fd318cc input=a9049054013a1b77]*/
index 196a2ee..a5f6442 100644 (file)
@@ -12,10 +12,10 @@ PyDoc_STRVAR(_opcode_stack_effect__doc__,
     {"stack_effect", (PyCFunction)_opcode_stack_effect, METH_VARARGS, _opcode_stack_effect__doc__},
 
 static int
-_opcode_stack_effect_impl(PyModuleDef *module, int opcode, PyObject *oparg);
+_opcode_stack_effect_impl(PyObject *module, int opcode, PyObject *oparg);
 
 static PyObject *
-_opcode_stack_effect(PyModuleDef *module, PyObject *args)
+_opcode_stack_effect(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int opcode;
@@ -33,4 +33,4 @@ _opcode_stack_effect(PyModuleDef *module, PyObject *args)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=8ee7cb735705e8b3 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=984d6de140303d10 input=a9049054013a1b77]*/
index ab4d205..bd12d2a 100644 (file)
@@ -380,11 +380,11 @@ PyDoc_STRVAR(_pickle_dump__doc__,
     {"dump", (PyCFunction)_pickle_dump, METH_VARARGS|METH_KEYWORDS, _pickle_dump__doc__},
 
 static PyObject *
-_pickle_dump_impl(PyModuleDef *module, PyObject *obj, PyObject *file,
+_pickle_dump_impl(PyObject *module, PyObject *obj, PyObject *file,
                   PyObject *protocol, int fix_imports);
 
 static PyObject *
-_pickle_dump(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_pickle_dump(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"obj", "file", "protocol", "fix_imports", NULL};
@@ -424,11 +424,11 @@ PyDoc_STRVAR(_pickle_dumps__doc__,
     {"dumps", (PyCFunction)_pickle_dumps, METH_VARARGS|METH_KEYWORDS, _pickle_dumps__doc__},
 
 static PyObject *
-_pickle_dumps_impl(PyModuleDef *module, PyObject *obj, PyObject *protocol,
+_pickle_dumps_impl(PyObject *module, PyObject *obj, PyObject *protocol,
                    int fix_imports);
 
 static PyObject *
-_pickle_dumps(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_pickle_dumps(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"obj", "protocol", "fix_imports", NULL};
@@ -478,11 +478,11 @@ PyDoc_STRVAR(_pickle_load__doc__,
     {"load", (PyCFunction)_pickle_load, METH_VARARGS|METH_KEYWORDS, _pickle_load__doc__},
 
 static PyObject *
-_pickle_load_impl(PyModuleDef *module, PyObject *file, int fix_imports,
+_pickle_load_impl(PyObject *module, PyObject *file, int fix_imports,
                   const char *encoding, const char *errors);
 
 static PyObject *
-_pickle_load(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_pickle_load(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"file", "fix_imports", "encoding", "errors", NULL};
@@ -524,11 +524,11 @@ PyDoc_STRVAR(_pickle_loads__doc__,
     {"loads", (PyCFunction)_pickle_loads, METH_VARARGS|METH_KEYWORDS, _pickle_loads__doc__},
 
 static PyObject *
-_pickle_loads_impl(PyModuleDef *module, PyObject *data, int fix_imports,
+_pickle_loads_impl(PyObject *module, PyObject *data, int fix_imports,
                    const char *encoding, const char *errors);
 
 static PyObject *
-_pickle_loads(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_pickle_loads(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"data", "fix_imports", "encoding", "errors", NULL};
@@ -545,4 +545,4 @@ _pickle_loads(PyModuleDef *module, PyObject *args, PyObject *kwargs)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=a7169d4fbbeef827 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=93657e55d6a748af input=a9049054013a1b77]*/
index 6de4708..3281717 100644 (file)
@@ -11,10 +11,10 @@ PyDoc_STRVAR(_sre_getcodesize__doc__,
     {"getcodesize", (PyCFunction)_sre_getcodesize, METH_NOARGS, _sre_getcodesize__doc__},
 
 static int
-_sre_getcodesize_impl(PyModuleDef *module);
+_sre_getcodesize_impl(PyObject *module);
 
 static PyObject *
-_sre_getcodesize(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_sre_getcodesize(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     int _return_value;
@@ -37,10 +37,10 @@ PyDoc_STRVAR(_sre_getlower__doc__,
     {"getlower", (PyCFunction)_sre_getlower, METH_VARARGS, _sre_getlower__doc__},
 
 static int
-_sre_getlower_impl(PyModuleDef *module, int character, int flags);
+_sre_getlower_impl(PyObject *module, int character, int flags);
 
 static PyObject *
-_sre_getlower(PyModuleDef *module, PyObject *args)
+_sre_getlower(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int character;
@@ -406,12 +406,12 @@ PyDoc_STRVAR(_sre_compile__doc__,
     {"compile", (PyCFunction)_sre_compile, METH_VARARGS|METH_KEYWORDS, _sre_compile__doc__},
 
 static PyObject *
-_sre_compile_impl(PyModuleDef *module, PyObject *pattern, int flags,
+_sre_compile_impl(PyObject *module, PyObject *pattern, int flags,
                   PyObject *code, Py_ssize_t groups, PyObject *groupindex,
                   PyObject *indexgroup);
 
 static PyObject *
-_sre_compile(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_sre_compile(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"pattern", "flags", "code", "groups", "groupindex", "indexgroup", NULL};
@@ -690,4 +690,4 @@ _sre_SRE_Scanner_search(ScannerObject *self, PyObject *Py_UNUSED(ignored))
 {
     return _sre_SRE_Scanner_search_impl(self);
 }
-/*[clinic end generated code: output=d1d73ab2c5008bd4 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=a4ce9e5b748ce532 input=a9049054013a1b77]*/
index 4dbc5d0..852e365 100644 (file)
@@ -28,10 +28,10 @@ PyDoc_STRVAR(_ssl__test_decode_cert__doc__,
     {"_test_decode_cert", (PyCFunction)_ssl__test_decode_cert, METH_O, _ssl__test_decode_cert__doc__},
 
 static PyObject *
-_ssl__test_decode_cert_impl(PyModuleDef *module, PyObject *path);
+_ssl__test_decode_cert_impl(PyObject *module, PyObject *path);
 
 static PyObject *
-_ssl__test_decode_cert(PyModuleDef *module, PyObject *arg)
+_ssl__test_decode_cert(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *path;
@@ -795,10 +795,10 @@ PyDoc_STRVAR(_ssl_RAND_add__doc__,
     {"RAND_add", (PyCFunction)_ssl_RAND_add, METH_VARARGS, _ssl_RAND_add__doc__},
 
 static PyObject *
-_ssl_RAND_add_impl(PyModuleDef *module, Py_buffer *view, double entropy);
+_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy);
 
 static PyObject *
-_ssl_RAND_add(PyModuleDef *module, PyObject *args)
+_ssl_RAND_add(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer view = {NULL, NULL};
@@ -827,10 +827,10 @@ PyDoc_STRVAR(_ssl_RAND_bytes__doc__,
     {"RAND_bytes", (PyCFunction)_ssl_RAND_bytes, METH_O, _ssl_RAND_bytes__doc__},
 
 static PyObject *
-_ssl_RAND_bytes_impl(PyModuleDef *module, int n);
+_ssl_RAND_bytes_impl(PyObject *module, int n);
 
 static PyObject *
-_ssl_RAND_bytes(PyModuleDef *module, PyObject *arg)
+_ssl_RAND_bytes(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int n;
@@ -856,10 +856,10 @@ PyDoc_STRVAR(_ssl_RAND_pseudo_bytes__doc__,
     {"RAND_pseudo_bytes", (PyCFunction)_ssl_RAND_pseudo_bytes, METH_O, _ssl_RAND_pseudo_bytes__doc__},
 
 static PyObject *
-_ssl_RAND_pseudo_bytes_impl(PyModuleDef *module, int n);
+_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n);
 
 static PyObject *
-_ssl_RAND_pseudo_bytes(PyModuleDef *module, PyObject *arg)
+_ssl_RAND_pseudo_bytes(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int n;
@@ -885,15 +885,15 @@ PyDoc_STRVAR(_ssl_RAND_status__doc__,
     {"RAND_status", (PyCFunction)_ssl_RAND_status, METH_NOARGS, _ssl_RAND_status__doc__},
 
 static PyObject *
-_ssl_RAND_status_impl(PyModuleDef *module);
+_ssl_RAND_status_impl(PyObject *module);
 
 static PyObject *
-_ssl_RAND_status(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_ssl_RAND_status(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return _ssl_RAND_status_impl(module);
 }
 
-#if defined(HAVE_RAND_EGD)
+#if !defined(OPENSSL_NO_EGD)
 
 PyDoc_STRVAR(_ssl_RAND_egd__doc__,
 "RAND_egd($module, path, /)\n"
@@ -908,10 +908,10 @@ PyDoc_STRVAR(_ssl_RAND_egd__doc__,
     {"RAND_egd", (PyCFunction)_ssl_RAND_egd, METH_O, _ssl_RAND_egd__doc__},
 
 static PyObject *
-_ssl_RAND_egd_impl(PyModuleDef *module, PyObject *path);
+_ssl_RAND_egd_impl(PyObject *module, PyObject *path);
 
 static PyObject *
-_ssl_RAND_egd(PyModuleDef *module, PyObject *arg)
+_ssl_RAND_egd(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *path;
@@ -924,7 +924,7 @@ exit:
     return return_value;
 }
 
-#endif /* defined(HAVE_RAND_EGD) */
+#endif /* !defined(OPENSSL_NO_EGD) */
 
 PyDoc_STRVAR(_ssl_get_default_verify_paths__doc__,
 "get_default_verify_paths($module, /)\n"
@@ -938,10 +938,10 @@ PyDoc_STRVAR(_ssl_get_default_verify_paths__doc__,
     {"get_default_verify_paths", (PyCFunction)_ssl_get_default_verify_paths, METH_NOARGS, _ssl_get_default_verify_paths__doc__},
 
 static PyObject *
-_ssl_get_default_verify_paths_impl(PyModuleDef *module);
+_ssl_get_default_verify_paths_impl(PyObject *module);
 
 static PyObject *
-_ssl_get_default_verify_paths(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_ssl_get_default_verify_paths(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return _ssl_get_default_verify_paths_impl(module);
 }
@@ -959,10 +959,10 @@ PyDoc_STRVAR(_ssl_txt2obj__doc__,
     {"txt2obj", (PyCFunction)_ssl_txt2obj, METH_VARARGS|METH_KEYWORDS, _ssl_txt2obj__doc__},
 
 static PyObject *
-_ssl_txt2obj_impl(PyModuleDef *module, const char *txt, int name);
+_ssl_txt2obj_impl(PyObject *module, const char *txt, int name);
 
 static PyObject *
-_ssl_txt2obj(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_ssl_txt2obj(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"txt", "name", NULL};
@@ -988,10 +988,10 @@ PyDoc_STRVAR(_ssl_nid2obj__doc__,
     {"nid2obj", (PyCFunction)_ssl_nid2obj, METH_O, _ssl_nid2obj__doc__},
 
 static PyObject *
-_ssl_nid2obj_impl(PyModuleDef *module, int nid);
+_ssl_nid2obj_impl(PyObject *module, int nid);
 
 static PyObject *
-_ssl_nid2obj(PyModuleDef *module, PyObject *arg)
+_ssl_nid2obj(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int nid;
@@ -1022,10 +1022,10 @@ PyDoc_STRVAR(_ssl_enum_certificates__doc__,
     {"enum_certificates", (PyCFunction)_ssl_enum_certificates, METH_VARARGS|METH_KEYWORDS, _ssl_enum_certificates__doc__},
 
 static PyObject *
-_ssl_enum_certificates_impl(PyModuleDef *module, const char *store_name);
+_ssl_enum_certificates_impl(PyObject *module, const char *store_name);
 
 static PyObject *
-_ssl_enum_certificates(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_ssl_enum_certificates(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"store_name", NULL};
@@ -1059,10 +1059,10 @@ PyDoc_STRVAR(_ssl_enum_crls__doc__,
     {"enum_crls", (PyCFunction)_ssl_enum_crls, METH_VARARGS|METH_KEYWORDS, _ssl_enum_crls__doc__},
 
 static PyObject *
-_ssl_enum_crls_impl(PyModuleDef *module, const char *store_name);
+_ssl_enum_crls_impl(PyObject *module, const char *store_name);
 
 static PyObject *
-_ssl_enum_crls(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_ssl_enum_crls(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"store_name", NULL};
@@ -1102,4 +1102,4 @@ exit:
 #ifndef _SSL_ENUM_CRLS_METHODDEF
     #define _SSL_ENUM_CRLS_METHODDEF
 #endif /* !defined(_SSL_ENUM_CRLS_METHODDEF) */
-/*[clinic end generated code: output=a14999cb565a69a2 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=6fb10594d8351dc5 input=a9049054013a1b77]*/
index 7917dec..77af083 100644 (file)
@@ -532,13 +532,13 @@ PyDoc_STRVAR(_tkinter_create__doc__,
     {"create", (PyCFunction)_tkinter_create, METH_VARARGS, _tkinter_create__doc__},
 
 static PyObject *
-_tkinter_create_impl(PyModuleDef *module, const char *screenName,
+_tkinter_create_impl(PyObject *module, const char *screenName,
                      const char *baseName, const char *className,
                      int interactive, int wantobjects, int wantTk, int sync,
                      const char *use);
 
 static PyObject *
-_tkinter_create(PyModuleDef *module, PyObject *args)
+_tkinter_create(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     const char *screenName = NULL;
@@ -571,10 +571,10 @@ PyDoc_STRVAR(_tkinter_setbusywaitinterval__doc__,
     {"setbusywaitinterval", (PyCFunction)_tkinter_setbusywaitinterval, METH_O, _tkinter_setbusywaitinterval__doc__},
 
 static PyObject *
-_tkinter_setbusywaitinterval_impl(PyModuleDef *module, int new_val);
+_tkinter_setbusywaitinterval_impl(PyObject *module, int new_val);
 
 static PyObject *
-_tkinter_setbusywaitinterval(PyModuleDef *module, PyObject *arg)
+_tkinter_setbusywaitinterval(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int new_val;
@@ -597,10 +597,10 @@ PyDoc_STRVAR(_tkinter_getbusywaitinterval__doc__,
     {"getbusywaitinterval", (PyCFunction)_tkinter_getbusywaitinterval, METH_NOARGS, _tkinter_getbusywaitinterval__doc__},
 
 static int
-_tkinter_getbusywaitinterval_impl(PyModuleDef *module);
+_tkinter_getbusywaitinterval_impl(PyObject *module);
 
 static PyObject *
-_tkinter_getbusywaitinterval(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_tkinter_getbusywaitinterval(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     int _return_value;
@@ -621,4 +621,4 @@ exit:
 #ifndef _TKINTER_TKAPP_DELETEFILEHANDLER_METHODDEF
     #define _TKINTER_TKAPP_DELETEFILEHANDLER_METHODDEF
 #endif /* !defined(_TKINTER_TKAPP_DELETEFILEHANDLER_METHODDEF) */
-/*[clinic end generated code: output=6dd667b91cf8addd input=a9049054013a1b77]*/
+/*[clinic end generated code: output=f9057c8bf288633d input=a9049054013a1b77]*/
index 87c701c..2d93679 100644 (file)
@@ -12,10 +12,10 @@ PyDoc_STRVAR(_weakref_getweakrefcount__doc__,
     {"getweakrefcount", (PyCFunction)_weakref_getweakrefcount, METH_O, _weakref_getweakrefcount__doc__},
 
 static Py_ssize_t
-_weakref_getweakrefcount_impl(PyModuleDef *module, PyObject *object);
+_weakref_getweakrefcount_impl(PyObject *module, PyObject *object);
 
 static PyObject *
-_weakref_getweakrefcount(PyModuleDef *module, PyObject *object)
+_weakref_getweakrefcount(PyObject *module, PyObject *object)
 {
     PyObject *return_value = NULL;
     Py_ssize_t _return_value;
@@ -28,4 +28,33 @@ _weakref_getweakrefcount(PyModuleDef *module, PyObject *object)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=4da9aade63eed77f input=a9049054013a1b77]*/
+
+PyDoc_STRVAR(_weakref__remove_dead_weakref__doc__,
+"_remove_dead_weakref($module, dct, key, /)\n"
+"--\n"
+"\n"
+"Atomically remove key from dict if it points to a dead weakref.");
+
+#define _WEAKREF__REMOVE_DEAD_WEAKREF_METHODDEF    \
+    {"_remove_dead_weakref", (PyCFunction)_weakref__remove_dead_weakref, METH_VARARGS, _weakref__remove_dead_weakref__doc__},
+
+static PyObject *
+_weakref__remove_dead_weakref_impl(PyObject *module, PyObject *dct,
+                                   PyObject *key);
+
+static PyObject *
+_weakref__remove_dead_weakref(PyObject *module, PyObject *args)
+{
+    PyObject *return_value = NULL;
+    PyObject *dct;
+    PyObject *key;
+
+    if (!PyArg_ParseTuple(args, "O!O:_remove_dead_weakref",
+        &PyDict_Type, &dct, &key))
+        goto exit;
+    return_value = _weakref__remove_dead_weakref_impl(module, dct, key);
+
+exit:
+    return return_value;
+}
+/*[clinic end generated code: output=5764cb64a6f66ffd input=a9049054013a1b77]*/
index 34518e8..ac38d37 100644 (file)
@@ -71,10 +71,10 @@ PyDoc_STRVAR(_winapi_CloseHandle__doc__,
     {"CloseHandle", (PyCFunction)_winapi_CloseHandle, METH_O, _winapi_CloseHandle__doc__},
 
 static PyObject *
-_winapi_CloseHandle_impl(PyModuleDef *module, HANDLE handle);
+_winapi_CloseHandle_impl(PyObject *module, HANDLE handle);
 
 static PyObject *
-_winapi_CloseHandle(PyModuleDef *module, PyObject *arg)
+_winapi_CloseHandle(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     HANDLE handle;
@@ -96,11 +96,11 @@ PyDoc_STRVAR(_winapi_ConnectNamedPipe__doc__,
     {"ConnectNamedPipe", (PyCFunction)_winapi_ConnectNamedPipe, METH_VARARGS|METH_KEYWORDS, _winapi_ConnectNamedPipe__doc__},
 
 static PyObject *
-_winapi_ConnectNamedPipe_impl(PyModuleDef *module, HANDLE handle,
+_winapi_ConnectNamedPipe_impl(PyObject *module, HANDLE handle,
                               int use_overlapped);
 
 static PyObject *
-_winapi_ConnectNamedPipe(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_winapi_ConnectNamedPipe(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"handle", "overlapped", NULL};
@@ -127,14 +127,14 @@ PyDoc_STRVAR(_winapi_CreateFile__doc__,
     {"CreateFile", (PyCFunction)_winapi_CreateFile, METH_VARARGS, _winapi_CreateFile__doc__},
 
 static HANDLE
-_winapi_CreateFile_impl(PyModuleDef *module, LPCTSTR file_name,
+_winapi_CreateFile_impl(PyObject *module, LPCTSTR file_name,
                         DWORD desired_access, DWORD share_mode,
                         LPSECURITY_ATTRIBUTES security_attributes,
                         DWORD creation_disposition,
                         DWORD flags_and_attributes, HANDLE template_file);
 
 static PyObject *
-_winapi_CreateFile(PyModuleDef *module, PyObject *args)
+_winapi_CreateFile(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     LPCTSTR file_name;
@@ -169,11 +169,11 @@ PyDoc_STRVAR(_winapi_CreateJunction__doc__,
     {"CreateJunction", (PyCFunction)_winapi_CreateJunction, METH_VARARGS, _winapi_CreateJunction__doc__},
 
 static PyObject *
-_winapi_CreateJunction_impl(PyModuleDef *module, LPWSTR src_path,
+_winapi_CreateJunction_impl(PyObject *module, LPWSTR src_path,
                             LPWSTR dst_path);
 
 static PyObject *
-_winapi_CreateJunction(PyModuleDef *module, PyObject *args)
+_winapi_CreateJunction(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     LPWSTR src_path;
@@ -199,14 +199,14 @@ PyDoc_STRVAR(_winapi_CreateNamedPipe__doc__,
     {"CreateNamedPipe", (PyCFunction)_winapi_CreateNamedPipe, METH_VARARGS, _winapi_CreateNamedPipe__doc__},
 
 static HANDLE
-_winapi_CreateNamedPipe_impl(PyModuleDef *module, LPCTSTR name,
-                             DWORD open_mode, DWORD pipe_mode,
-                             DWORD max_instances, DWORD out_buffer_size,
-                             DWORD in_buffer_size, DWORD default_timeout,
+_winapi_CreateNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD open_mode,
+                             DWORD pipe_mode, DWORD max_instances,
+                             DWORD out_buffer_size, DWORD in_buffer_size,
+                             DWORD default_timeout,
                              LPSECURITY_ATTRIBUTES security_attributes);
 
 static PyObject *
-_winapi_CreateNamedPipe(PyModuleDef *module, PyObject *args)
+_winapi_CreateNamedPipe(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     LPCTSTR name;
@@ -248,11 +248,10 @@ PyDoc_STRVAR(_winapi_CreatePipe__doc__,
     {"CreatePipe", (PyCFunction)_winapi_CreatePipe, METH_VARARGS, _winapi_CreatePipe__doc__},
 
 static PyObject *
-_winapi_CreatePipe_impl(PyModuleDef *module, PyObject *pipe_attrs,
-                        DWORD size);
+_winapi_CreatePipe_impl(PyObject *module, PyObject *pipe_attrs, DWORD size);
 
 static PyObject *
-_winapi_CreatePipe(PyModuleDef *module, PyObject *args)
+_winapi_CreatePipe(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *pipe_attrs;
@@ -287,7 +286,7 @@ PyDoc_STRVAR(_winapi_CreateProcess__doc__,
     {"CreateProcess", (PyCFunction)_winapi_CreateProcess, METH_VARARGS, _winapi_CreateProcess__doc__},
 
 static PyObject *
-_winapi_CreateProcess_impl(PyModuleDef *module, Py_UNICODE *application_name,
+_winapi_CreateProcess_impl(PyObject *module, Py_UNICODE *application_name,
                            Py_UNICODE *command_line, PyObject *proc_attrs,
                            PyObject *thread_attrs, BOOL inherit_handles,
                            DWORD creation_flags, PyObject *env_mapping,
@@ -295,7 +294,7 @@ _winapi_CreateProcess_impl(PyModuleDef *module, Py_UNICODE *application_name,
                            PyObject *startup_info);
 
 static PyObject *
-_winapi_CreateProcess(PyModuleDef *module, PyObject *args)
+_winapi_CreateProcess(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_UNICODE *application_name;
@@ -333,15 +332,14 @@ PyDoc_STRVAR(_winapi_DuplicateHandle__doc__,
     {"DuplicateHandle", (PyCFunction)_winapi_DuplicateHandle, METH_VARARGS, _winapi_DuplicateHandle__doc__},
 
 static HANDLE
-_winapi_DuplicateHandle_impl(PyModuleDef *module,
-                             HANDLE source_process_handle,
+_winapi_DuplicateHandle_impl(PyObject *module, HANDLE source_process_handle,
                              HANDLE source_handle,
                              HANDLE target_process_handle,
                              DWORD desired_access, BOOL inherit_handle,
                              DWORD options);
 
 static PyObject *
-_winapi_DuplicateHandle(PyModuleDef *module, PyObject *args)
+_winapi_DuplicateHandle(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HANDLE source_process_handle;
@@ -375,10 +373,10 @@ PyDoc_STRVAR(_winapi_ExitProcess__doc__,
     {"ExitProcess", (PyCFunction)_winapi_ExitProcess, METH_O, _winapi_ExitProcess__doc__},
 
 static PyObject *
-_winapi_ExitProcess_impl(PyModuleDef *module, UINT ExitCode);
+_winapi_ExitProcess_impl(PyObject *module, UINT ExitCode);
 
 static PyObject *
-_winapi_ExitProcess(PyModuleDef *module, PyObject *arg)
+_winapi_ExitProcess(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     UINT ExitCode;
@@ -401,10 +399,10 @@ PyDoc_STRVAR(_winapi_GetCurrentProcess__doc__,
     {"GetCurrentProcess", (PyCFunction)_winapi_GetCurrentProcess, METH_NOARGS, _winapi_GetCurrentProcess__doc__},
 
 static HANDLE
-_winapi_GetCurrentProcess_impl(PyModuleDef *module);
+_winapi_GetCurrentProcess_impl(PyObject *module);
 
 static PyObject *
-_winapi_GetCurrentProcess(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_winapi_GetCurrentProcess(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     HANDLE _return_value;
@@ -430,10 +428,10 @@ PyDoc_STRVAR(_winapi_GetExitCodeProcess__doc__,
     {"GetExitCodeProcess", (PyCFunction)_winapi_GetExitCodeProcess, METH_O, _winapi_GetExitCodeProcess__doc__},
 
 static DWORD
-_winapi_GetExitCodeProcess_impl(PyModuleDef *module, HANDLE process);
+_winapi_GetExitCodeProcess_impl(PyObject *module, HANDLE process);
 
 static PyObject *
-_winapi_GetExitCodeProcess(PyModuleDef *module, PyObject *arg)
+_winapi_GetExitCodeProcess(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     HANDLE process;
@@ -459,10 +457,10 @@ PyDoc_STRVAR(_winapi_GetLastError__doc__,
     {"GetLastError", (PyCFunction)_winapi_GetLastError, METH_NOARGS, _winapi_GetLastError__doc__},
 
 static DWORD
-_winapi_GetLastError_impl(PyModuleDef *module);
+_winapi_GetLastError_impl(PyObject *module);
 
 static PyObject *
-_winapi_GetLastError(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_winapi_GetLastError(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     DWORD _return_value;
@@ -493,10 +491,10 @@ PyDoc_STRVAR(_winapi_GetModuleFileName__doc__,
     {"GetModuleFileName", (PyCFunction)_winapi_GetModuleFileName, METH_O, _winapi_GetModuleFileName__doc__},
 
 static PyObject *
-_winapi_GetModuleFileName_impl(PyModuleDef *module, HMODULE module_handle);
+_winapi_GetModuleFileName_impl(PyObject *module, HMODULE module_handle);
 
 static PyObject *
-_winapi_GetModuleFileName(PyModuleDef *module, PyObject *arg)
+_winapi_GetModuleFileName(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     HMODULE module_handle;
@@ -524,10 +522,10 @@ PyDoc_STRVAR(_winapi_GetStdHandle__doc__,
     {"GetStdHandle", (PyCFunction)_winapi_GetStdHandle, METH_O, _winapi_GetStdHandle__doc__},
 
 static HANDLE
-_winapi_GetStdHandle_impl(PyModuleDef *module, DWORD std_handle);
+_winapi_GetStdHandle_impl(PyObject *module, DWORD std_handle);
 
 static PyObject *
-_winapi_GetStdHandle(PyModuleDef *module, PyObject *arg)
+_winapi_GetStdHandle(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     DWORD std_handle;
@@ -556,10 +554,10 @@ PyDoc_STRVAR(_winapi_GetVersion__doc__,
     {"GetVersion", (PyCFunction)_winapi_GetVersion, METH_NOARGS, _winapi_GetVersion__doc__},
 
 static long
-_winapi_GetVersion_impl(PyModuleDef *module);
+_winapi_GetVersion_impl(PyObject *module);
 
 static PyObject *
-_winapi_GetVersion(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_winapi_GetVersion(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     long _return_value;
@@ -582,11 +580,11 @@ PyDoc_STRVAR(_winapi_OpenProcess__doc__,
     {"OpenProcess", (PyCFunction)_winapi_OpenProcess, METH_VARARGS, _winapi_OpenProcess__doc__},
 
 static HANDLE
-_winapi_OpenProcess_impl(PyModuleDef *module, DWORD desired_access,
+_winapi_OpenProcess_impl(PyObject *module, DWORD desired_access,
                          BOOL inherit_handle, DWORD process_id);
 
 static PyObject *
-_winapi_OpenProcess(PyModuleDef *module, PyObject *args)
+_winapi_OpenProcess(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     DWORD desired_access;
@@ -617,10 +615,10 @@ PyDoc_STRVAR(_winapi_PeekNamedPipe__doc__,
     {"PeekNamedPipe", (PyCFunction)_winapi_PeekNamedPipe, METH_VARARGS, _winapi_PeekNamedPipe__doc__},
 
 static PyObject *
-_winapi_PeekNamedPipe_impl(PyModuleDef *module, HANDLE handle, int size);
+_winapi_PeekNamedPipe_impl(PyObject *module, HANDLE handle, int size);
 
 static PyObject *
-_winapi_PeekNamedPipe(PyModuleDef *module, PyObject *args)
+_winapi_PeekNamedPipe(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HANDLE handle;
@@ -644,11 +642,11 @@ PyDoc_STRVAR(_winapi_ReadFile__doc__,
     {"ReadFile", (PyCFunction)_winapi_ReadFile, METH_VARARGS|METH_KEYWORDS, _winapi_ReadFile__doc__},
 
 static PyObject *
-_winapi_ReadFile_impl(PyModuleDef *module, HANDLE handle, int size,
+_winapi_ReadFile_impl(PyObject *module, HANDLE handle, int size,
                       int use_overlapped);
 
 static PyObject *
-_winapi_ReadFile(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_winapi_ReadFile(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"handle", "size", "overlapped", NULL};
@@ -675,13 +673,13 @@ PyDoc_STRVAR(_winapi_SetNamedPipeHandleState__doc__,
     {"SetNamedPipeHandleState", (PyCFunction)_winapi_SetNamedPipeHandleState, METH_VARARGS, _winapi_SetNamedPipeHandleState__doc__},
 
 static PyObject *
-_winapi_SetNamedPipeHandleState_impl(PyModuleDef *module, HANDLE named_pipe,
+_winapi_SetNamedPipeHandleState_impl(PyObject *module, HANDLE named_pipe,
                                      PyObject *mode,
                                      PyObject *max_collection_count,
                                      PyObject *collect_data_timeout);
 
 static PyObject *
-_winapi_SetNamedPipeHandleState(PyModuleDef *module, PyObject *args)
+_winapi_SetNamedPipeHandleState(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HANDLE named_pipe;
@@ -708,11 +706,11 @@ PyDoc_STRVAR(_winapi_TerminateProcess__doc__,
     {"TerminateProcess", (PyCFunction)_winapi_TerminateProcess, METH_VARARGS, _winapi_TerminateProcess__doc__},
 
 static PyObject *
-_winapi_TerminateProcess_impl(PyModuleDef *module, HANDLE handle,
+_winapi_TerminateProcess_impl(PyObject *module, HANDLE handle,
                               UINT exit_code);
 
 static PyObject *
-_winapi_TerminateProcess(PyModuleDef *module, PyObject *args)
+_winapi_TerminateProcess(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HANDLE handle;
@@ -736,10 +734,10 @@ PyDoc_STRVAR(_winapi_WaitNamedPipe__doc__,
     {"WaitNamedPipe", (PyCFunction)_winapi_WaitNamedPipe, METH_VARARGS, _winapi_WaitNamedPipe__doc__},
 
 static PyObject *
-_winapi_WaitNamedPipe_impl(PyModuleDef *module, LPCTSTR name, DWORD timeout);
+_winapi_WaitNamedPipe_impl(PyObject *module, LPCTSTR name, DWORD timeout);
 
 static PyObject *
-_winapi_WaitNamedPipe(PyModuleDef *module, PyObject *args)
+_winapi_WaitNamedPipe(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     LPCTSTR name;
@@ -764,12 +762,11 @@ PyDoc_STRVAR(_winapi_WaitForMultipleObjects__doc__,
     {"WaitForMultipleObjects", (PyCFunction)_winapi_WaitForMultipleObjects, METH_VARARGS, _winapi_WaitForMultipleObjects__doc__},
 
 static PyObject *
-_winapi_WaitForMultipleObjects_impl(PyModuleDef *module,
-                                    PyObject *handle_seq, BOOL wait_flag,
-                                    DWORD milliseconds);
+_winapi_WaitForMultipleObjects_impl(PyObject *module, PyObject *handle_seq,
+                                    BOOL wait_flag, DWORD milliseconds);
 
 static PyObject *
-_winapi_WaitForMultipleObjects(PyModuleDef *module, PyObject *args)
+_winapi_WaitForMultipleObjects(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *handle_seq;
@@ -799,11 +796,11 @@ PyDoc_STRVAR(_winapi_WaitForSingleObject__doc__,
     {"WaitForSingleObject", (PyCFunction)_winapi_WaitForSingleObject, METH_VARARGS, _winapi_WaitForSingleObject__doc__},
 
 static long
-_winapi_WaitForSingleObject_impl(PyModuleDef *module, HANDLE handle,
+_winapi_WaitForSingleObject_impl(PyObject *module, HANDLE handle,
                                  DWORD milliseconds);
 
 static PyObject *
-_winapi_WaitForSingleObject(PyModuleDef *module, PyObject *args)
+_winapi_WaitForSingleObject(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HANDLE handle;
@@ -831,11 +828,11 @@ PyDoc_STRVAR(_winapi_WriteFile__doc__,
     {"WriteFile", (PyCFunction)_winapi_WriteFile, METH_VARARGS|METH_KEYWORDS, _winapi_WriteFile__doc__},
 
 static PyObject *
-_winapi_WriteFile_impl(PyModuleDef *module, HANDLE handle, PyObject *buffer,
+_winapi_WriteFile_impl(PyObject *module, HANDLE handle, PyObject *buffer,
                        int use_overlapped);
 
 static PyObject *
-_winapi_WriteFile(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_winapi_WriteFile(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"handle", "buffer", "overlapped", NULL};
@@ -851,4 +848,4 @@ _winapi_WriteFile(PyModuleDef *module, PyObject *args, PyObject *kwargs)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=98771c6584056d19 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=a4c4b2a9fcb0bea1 input=a9049054013a1b77]*/
index fdf247e..0c7061a 100644 (file)
@@ -438,13 +438,13 @@ PyDoc_STRVAR(array__array_reconstructor__doc__,
     {"_array_reconstructor", (PyCFunction)array__array_reconstructor, METH_VARARGS, array__array_reconstructor__doc__},
 
 static PyObject *
-array__array_reconstructor_impl(PyModuleDef *module, PyTypeObject *arraytype,
+array__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype,
                                 int typecode,
                                 enum machine_format_code mformat_code,
                                 PyObject *items);
 
 static PyObject *
-array__array_reconstructor(PyModuleDef *module, PyObject *args)
+array__array_reconstructor(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyTypeObject *arraytype;
@@ -496,4 +496,4 @@ PyDoc_STRVAR(array_arrayiterator___setstate____doc__,
 
 #define ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF    \
     {"__setstate__", (PyCFunction)array_arrayiterator___setstate__, METH_O, array_arrayiterator___setstate____doc__},
-/*[clinic end generated code: output=d2e82c65ea841cfc input=a9049054013a1b77]*/
+/*[clinic end generated code: output=305df3f5796039e4 input=a9049054013a1b77]*/
index 3ee2966..62e313b 100644 (file)
@@ -12,11 +12,11 @@ PyDoc_STRVAR(audioop_getsample__doc__,
     {"getsample", (PyCFunction)audioop_getsample, METH_VARARGS, audioop_getsample__doc__},
 
 static PyObject *
-audioop_getsample_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_getsample_impl(PyObject *module, Py_buffer *fragment, int width,
                        Py_ssize_t index);
 
 static PyObject *
-audioop_getsample(PyModuleDef *module, PyObject *args)
+audioop_getsample(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -46,10 +46,10 @@ PyDoc_STRVAR(audioop_max__doc__,
     {"max", (PyCFunction)audioop_max, METH_VARARGS, audioop_max__doc__},
 
 static PyObject *
-audioop_max_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_max_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_max(PyModuleDef *module, PyObject *args)
+audioop_max(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -78,10 +78,10 @@ PyDoc_STRVAR(audioop_minmax__doc__,
     {"minmax", (PyCFunction)audioop_minmax, METH_VARARGS, audioop_minmax__doc__},
 
 static PyObject *
-audioop_minmax_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_minmax_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_minmax(PyModuleDef *module, PyObject *args)
+audioop_minmax(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -110,10 +110,10 @@ PyDoc_STRVAR(audioop_avg__doc__,
     {"avg", (PyCFunction)audioop_avg, METH_VARARGS, audioop_avg__doc__},
 
 static PyObject *
-audioop_avg_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_avg_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_avg(PyModuleDef *module, PyObject *args)
+audioop_avg(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -142,10 +142,10 @@ PyDoc_STRVAR(audioop_rms__doc__,
     {"rms", (PyCFunction)audioop_rms, METH_VARARGS, audioop_rms__doc__},
 
 static PyObject *
-audioop_rms_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_rms_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_rms(PyModuleDef *module, PyObject *args)
+audioop_rms(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -174,11 +174,11 @@ PyDoc_STRVAR(audioop_findfit__doc__,
     {"findfit", (PyCFunction)audioop_findfit, METH_VARARGS, audioop_findfit__doc__},
 
 static PyObject *
-audioop_findfit_impl(PyModuleDef *module, Py_buffer *fragment,
+audioop_findfit_impl(PyObject *module, Py_buffer *fragment,
                      Py_buffer *reference);
 
 static PyObject *
-audioop_findfit(PyModuleDef *module, PyObject *args)
+audioop_findfit(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -210,11 +210,11 @@ PyDoc_STRVAR(audioop_findfactor__doc__,
     {"findfactor", (PyCFunction)audioop_findfactor, METH_VARARGS, audioop_findfactor__doc__},
 
 static PyObject *
-audioop_findfactor_impl(PyModuleDef *module, Py_buffer *fragment,
+audioop_findfactor_impl(PyObject *module, Py_buffer *fragment,
                         Py_buffer *reference);
 
 static PyObject *
-audioop_findfactor(PyModuleDef *module, PyObject *args)
+audioop_findfactor(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -246,11 +246,11 @@ PyDoc_STRVAR(audioop_findmax__doc__,
     {"findmax", (PyCFunction)audioop_findmax, METH_VARARGS, audioop_findmax__doc__},
 
 static PyObject *
-audioop_findmax_impl(PyModuleDef *module, Py_buffer *fragment,
+audioop_findmax_impl(PyObject *module, Py_buffer *fragment,
                      Py_ssize_t length);
 
 static PyObject *
-audioop_findmax(PyModuleDef *module, PyObject *args)
+audioop_findmax(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -279,10 +279,10 @@ PyDoc_STRVAR(audioop_avgpp__doc__,
     {"avgpp", (PyCFunction)audioop_avgpp, METH_VARARGS, audioop_avgpp__doc__},
 
 static PyObject *
-audioop_avgpp_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_avgpp_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_avgpp(PyModuleDef *module, PyObject *args)
+audioop_avgpp(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -311,10 +311,10 @@ PyDoc_STRVAR(audioop_maxpp__doc__,
     {"maxpp", (PyCFunction)audioop_maxpp, METH_VARARGS, audioop_maxpp__doc__},
 
 static PyObject *
-audioop_maxpp_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_maxpp_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_maxpp(PyModuleDef *module, PyObject *args)
+audioop_maxpp(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -343,10 +343,10 @@ PyDoc_STRVAR(audioop_cross__doc__,
     {"cross", (PyCFunction)audioop_cross, METH_VARARGS, audioop_cross__doc__},
 
 static PyObject *
-audioop_cross_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_cross_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_cross(PyModuleDef *module, PyObject *args)
+audioop_cross(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -375,11 +375,11 @@ PyDoc_STRVAR(audioop_mul__doc__,
     {"mul", (PyCFunction)audioop_mul, METH_VARARGS, audioop_mul__doc__},
 
 static PyObject *
-audioop_mul_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_mul_impl(PyObject *module, Py_buffer *fragment, int width,
                  double factor);
 
 static PyObject *
-audioop_mul(PyModuleDef *module, PyObject *args)
+audioop_mul(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -409,11 +409,11 @@ PyDoc_STRVAR(audioop_tomono__doc__,
     {"tomono", (PyCFunction)audioop_tomono, METH_VARARGS, audioop_tomono__doc__},
 
 static PyObject *
-audioop_tomono_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_tomono_impl(PyObject *module, Py_buffer *fragment, int width,
                     double lfactor, double rfactor);
 
 static PyObject *
-audioop_tomono(PyModuleDef *module, PyObject *args)
+audioop_tomono(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -444,11 +444,11 @@ PyDoc_STRVAR(audioop_tostereo__doc__,
     {"tostereo", (PyCFunction)audioop_tostereo, METH_VARARGS, audioop_tostereo__doc__},
 
 static PyObject *
-audioop_tostereo_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_tostereo_impl(PyObject *module, Py_buffer *fragment, int width,
                       double lfactor, double rfactor);
 
 static PyObject *
-audioop_tostereo(PyModuleDef *module, PyObject *args)
+audioop_tostereo(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -479,11 +479,11 @@ PyDoc_STRVAR(audioop_add__doc__,
     {"add", (PyCFunction)audioop_add, METH_VARARGS, audioop_add__doc__},
 
 static PyObject *
-audioop_add_impl(PyModuleDef *module, Py_buffer *fragment1,
+audioop_add_impl(PyObject *module, Py_buffer *fragment1,
                  Py_buffer *fragment2, int width);
 
 static PyObject *
-audioop_add(PyModuleDef *module, PyObject *args)
+audioop_add(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment1 = {NULL, NULL};
@@ -516,11 +516,10 @@ PyDoc_STRVAR(audioop_bias__doc__,
     {"bias", (PyCFunction)audioop_bias, METH_VARARGS, audioop_bias__doc__},
 
 static PyObject *
-audioop_bias_impl(PyModuleDef *module, Py_buffer *fragment, int width,
-                  int bias);
+audioop_bias_impl(PyObject *module, Py_buffer *fragment, int width, int bias);
 
 static PyObject *
-audioop_bias(PyModuleDef *module, PyObject *args)
+audioop_bias(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -550,10 +549,10 @@ PyDoc_STRVAR(audioop_reverse__doc__,
     {"reverse", (PyCFunction)audioop_reverse, METH_VARARGS, audioop_reverse__doc__},
 
 static PyObject *
-audioop_reverse_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_reverse_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_reverse(PyModuleDef *module, PyObject *args)
+audioop_reverse(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -582,10 +581,10 @@ PyDoc_STRVAR(audioop_byteswap__doc__,
     {"byteswap", (PyCFunction)audioop_byteswap, METH_VARARGS, audioop_byteswap__doc__},
 
 static PyObject *
-audioop_byteswap_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_byteswap_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_byteswap(PyModuleDef *module, PyObject *args)
+audioop_byteswap(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -614,11 +613,11 @@ PyDoc_STRVAR(audioop_lin2lin__doc__,
     {"lin2lin", (PyCFunction)audioop_lin2lin, METH_VARARGS, audioop_lin2lin__doc__},
 
 static PyObject *
-audioop_lin2lin_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_lin2lin_impl(PyObject *module, Py_buffer *fragment, int width,
                      int newwidth);
 
 static PyObject *
-audioop_lin2lin(PyModuleDef *module, PyObject *args)
+audioop_lin2lin(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -649,12 +648,12 @@ PyDoc_STRVAR(audioop_ratecv__doc__,
     {"ratecv", (PyCFunction)audioop_ratecv, METH_VARARGS, audioop_ratecv__doc__},
 
 static PyObject *
-audioop_ratecv_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_ratecv_impl(PyObject *module, Py_buffer *fragment, int width,
                     int nchannels, int inrate, int outrate, PyObject *state,
                     int weightA, int weightB);
 
 static PyObject *
-audioop_ratecv(PyModuleDef *module, PyObject *args)
+audioop_ratecv(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -689,10 +688,10 @@ PyDoc_STRVAR(audioop_lin2ulaw__doc__,
     {"lin2ulaw", (PyCFunction)audioop_lin2ulaw, METH_VARARGS, audioop_lin2ulaw__doc__},
 
 static PyObject *
-audioop_lin2ulaw_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_lin2ulaw_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_lin2ulaw(PyModuleDef *module, PyObject *args)
+audioop_lin2ulaw(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -721,10 +720,10 @@ PyDoc_STRVAR(audioop_ulaw2lin__doc__,
     {"ulaw2lin", (PyCFunction)audioop_ulaw2lin, METH_VARARGS, audioop_ulaw2lin__doc__},
 
 static PyObject *
-audioop_ulaw2lin_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_ulaw2lin_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_ulaw2lin(PyModuleDef *module, PyObject *args)
+audioop_ulaw2lin(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -753,10 +752,10 @@ PyDoc_STRVAR(audioop_lin2alaw__doc__,
     {"lin2alaw", (PyCFunction)audioop_lin2alaw, METH_VARARGS, audioop_lin2alaw__doc__},
 
 static PyObject *
-audioop_lin2alaw_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_lin2alaw_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_lin2alaw(PyModuleDef *module, PyObject *args)
+audioop_lin2alaw(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -785,10 +784,10 @@ PyDoc_STRVAR(audioop_alaw2lin__doc__,
     {"alaw2lin", (PyCFunction)audioop_alaw2lin, METH_VARARGS, audioop_alaw2lin__doc__},
 
 static PyObject *
-audioop_alaw2lin_impl(PyModuleDef *module, Py_buffer *fragment, int width);
+audioop_alaw2lin_impl(PyObject *module, Py_buffer *fragment, int width);
 
 static PyObject *
-audioop_alaw2lin(PyModuleDef *module, PyObject *args)
+audioop_alaw2lin(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -817,11 +816,11 @@ PyDoc_STRVAR(audioop_lin2adpcm__doc__,
     {"lin2adpcm", (PyCFunction)audioop_lin2adpcm, METH_VARARGS, audioop_lin2adpcm__doc__},
 
 static PyObject *
-audioop_lin2adpcm_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_lin2adpcm_impl(PyObject *module, Py_buffer *fragment, int width,
                        PyObject *state);
 
 static PyObject *
-audioop_lin2adpcm(PyModuleDef *module, PyObject *args)
+audioop_lin2adpcm(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -851,11 +850,11 @@ PyDoc_STRVAR(audioop_adpcm2lin__doc__,
     {"adpcm2lin", (PyCFunction)audioop_adpcm2lin, METH_VARARGS, audioop_adpcm2lin__doc__},
 
 static PyObject *
-audioop_adpcm2lin_impl(PyModuleDef *module, Py_buffer *fragment, int width,
+audioop_adpcm2lin_impl(PyObject *module, Py_buffer *fragment, int width,
                        PyObject *state);
 
 static PyObject *
-audioop_adpcm2lin(PyModuleDef *module, PyObject *args)
+audioop_adpcm2lin(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer fragment = {NULL, NULL};
@@ -874,4 +873,4 @@ exit:
 
     return return_value;
 }
-/*[clinic end generated code: output=a076e1b213a8727b input=a9049054013a1b77]*/
+/*[clinic end generated code: output=385fb09fa21a62c0 input=a9049054013a1b77]*/
index e348bee..6ace4d5 100644 (file)
@@ -12,10 +12,10 @@ PyDoc_STRVAR(binascii_a2b_uu__doc__,
     {"a2b_uu", (PyCFunction)binascii_a2b_uu, METH_O, binascii_a2b_uu__doc__},
 
 static PyObject *
-binascii_a2b_uu_impl(PyModuleDef *module, Py_buffer *data);
+binascii_a2b_uu_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_a2b_uu(PyModuleDef *module, PyObject *arg)
+binascii_a2b_uu(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -42,10 +42,10 @@ PyDoc_STRVAR(binascii_b2a_uu__doc__,
     {"b2a_uu", (PyCFunction)binascii_b2a_uu, METH_O, binascii_b2a_uu__doc__},
 
 static PyObject *
-binascii_b2a_uu_impl(PyModuleDef *module, Py_buffer *data);
+binascii_b2a_uu_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_b2a_uu(PyModuleDef *module, PyObject *arg)
+binascii_b2a_uu(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -72,10 +72,10 @@ PyDoc_STRVAR(binascii_a2b_base64__doc__,
     {"a2b_base64", (PyCFunction)binascii_a2b_base64, METH_O, binascii_a2b_base64__doc__},
 
 static PyObject *
-binascii_a2b_base64_impl(PyModuleDef *module, Py_buffer *data);
+binascii_a2b_base64_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_a2b_base64(PyModuleDef *module, PyObject *arg)
+binascii_a2b_base64(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -102,10 +102,10 @@ PyDoc_STRVAR(binascii_b2a_base64__doc__,
     {"b2a_base64", (PyCFunction)binascii_b2a_base64, METH_O, binascii_b2a_base64__doc__},
 
 static PyObject *
-binascii_b2a_base64_impl(PyModuleDef *module, Py_buffer *data);
+binascii_b2a_base64_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_b2a_base64(PyModuleDef *module, PyObject *arg)
+binascii_b2a_base64(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -132,10 +132,10 @@ PyDoc_STRVAR(binascii_a2b_hqx__doc__,
     {"a2b_hqx", (PyCFunction)binascii_a2b_hqx, METH_O, binascii_a2b_hqx__doc__},
 
 static PyObject *
-binascii_a2b_hqx_impl(PyModuleDef *module, Py_buffer *data);
+binascii_a2b_hqx_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_a2b_hqx(PyModuleDef *module, PyObject *arg)
+binascii_a2b_hqx(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -162,10 +162,10 @@ PyDoc_STRVAR(binascii_rlecode_hqx__doc__,
     {"rlecode_hqx", (PyCFunction)binascii_rlecode_hqx, METH_O, binascii_rlecode_hqx__doc__},
 
 static PyObject *
-binascii_rlecode_hqx_impl(PyModuleDef *module, Py_buffer *data);
+binascii_rlecode_hqx_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_rlecode_hqx(PyModuleDef *module, PyObject *arg)
+binascii_rlecode_hqx(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -192,10 +192,10 @@ PyDoc_STRVAR(binascii_b2a_hqx__doc__,
     {"b2a_hqx", (PyCFunction)binascii_b2a_hqx, METH_O, binascii_b2a_hqx__doc__},
 
 static PyObject *
-binascii_b2a_hqx_impl(PyModuleDef *module, Py_buffer *data);
+binascii_b2a_hqx_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_b2a_hqx(PyModuleDef *module, PyObject *arg)
+binascii_b2a_hqx(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -222,10 +222,10 @@ PyDoc_STRVAR(binascii_rledecode_hqx__doc__,
     {"rledecode_hqx", (PyCFunction)binascii_rledecode_hqx, METH_O, binascii_rledecode_hqx__doc__},
 
 static PyObject *
-binascii_rledecode_hqx_impl(PyModuleDef *module, Py_buffer *data);
+binascii_rledecode_hqx_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_rledecode_hqx(PyModuleDef *module, PyObject *arg)
+binascii_rledecode_hqx(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -246,16 +246,16 @@ PyDoc_STRVAR(binascii_crc_hqx__doc__,
 "crc_hqx($module, data, crc, /)\n"
 "--\n"
 "\n"
-"Compute hqx CRC incrementally.");
+"Compute CRC-CCITT incrementally.");
 
 #define BINASCII_CRC_HQX_METHODDEF    \
     {"crc_hqx", (PyCFunction)binascii_crc_hqx, METH_VARARGS, binascii_crc_hqx__doc__},
 
 static unsigned int
-binascii_crc_hqx_impl(PyModuleDef *module, Py_buffer *data, unsigned int crc);
+binascii_crc_hqx_impl(PyObject *module, Py_buffer *data, unsigned int crc);
 
 static PyObject *
-binascii_crc_hqx(PyModuleDef *module, PyObject *args)
+binascii_crc_hqx(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -288,10 +288,10 @@ PyDoc_STRVAR(binascii_crc32__doc__,
     {"crc32", (PyCFunction)binascii_crc32, METH_VARARGS, binascii_crc32__doc__},
 
 static unsigned int
-binascii_crc32_impl(PyModuleDef *module, Py_buffer *data, unsigned int crc);
+binascii_crc32_impl(PyObject *module, Py_buffer *data, unsigned int crc);
 
 static PyObject *
-binascii_crc32(PyModuleDef *module, PyObject *args)
+binascii_crc32(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -327,10 +327,10 @@ PyDoc_STRVAR(binascii_b2a_hex__doc__,
     {"b2a_hex", (PyCFunction)binascii_b2a_hex, METH_O, binascii_b2a_hex__doc__},
 
 static PyObject *
-binascii_b2a_hex_impl(PyModuleDef *module, Py_buffer *data);
+binascii_b2a_hex_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_b2a_hex(PyModuleDef *module, PyObject *arg)
+binascii_b2a_hex(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -359,10 +359,10 @@ PyDoc_STRVAR(binascii_hexlify__doc__,
     {"hexlify", (PyCFunction)binascii_hexlify, METH_O, binascii_hexlify__doc__},
 
 static PyObject *
-binascii_hexlify_impl(PyModuleDef *module, Py_buffer *data);
+binascii_hexlify_impl(PyObject *module, Py_buffer *data);
 
 static PyObject *
-binascii_hexlify(PyModuleDef *module, PyObject *arg)
+binascii_hexlify(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -392,10 +392,10 @@ PyDoc_STRVAR(binascii_a2b_hex__doc__,
     {"a2b_hex", (PyCFunction)binascii_a2b_hex, METH_O, binascii_a2b_hex__doc__},
 
 static PyObject *
-binascii_a2b_hex_impl(PyModuleDef *module, Py_buffer *hexstr);
+binascii_a2b_hex_impl(PyObject *module, Py_buffer *hexstr);
 
 static PyObject *
-binascii_a2b_hex(PyModuleDef *module, PyObject *arg)
+binascii_a2b_hex(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer hexstr = {NULL, NULL};
@@ -424,10 +424,10 @@ PyDoc_STRVAR(binascii_unhexlify__doc__,
     {"unhexlify", (PyCFunction)binascii_unhexlify, METH_O, binascii_unhexlify__doc__},
 
 static PyObject *
-binascii_unhexlify_impl(PyModuleDef *module, Py_buffer *hexstr);
+binascii_unhexlify_impl(PyObject *module, Py_buffer *hexstr);
 
 static PyObject *
-binascii_unhexlify(PyModuleDef *module, PyObject *arg)
+binascii_unhexlify(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_buffer hexstr = {NULL, NULL};
@@ -454,10 +454,10 @@ PyDoc_STRVAR(binascii_a2b_qp__doc__,
     {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS|METH_KEYWORDS, binascii_a2b_qp__doc__},
 
 static PyObject *
-binascii_a2b_qp_impl(PyModuleDef *module, Py_buffer *data, int header);
+binascii_a2b_qp_impl(PyObject *module, Py_buffer *data, int header);
 
 static PyObject *
-binascii_a2b_qp(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+binascii_a2b_qp(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"data", "header", NULL};
@@ -491,11 +491,11 @@ PyDoc_STRVAR(binascii_b2a_qp__doc__,
     {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS|METH_KEYWORDS, binascii_b2a_qp__doc__},
 
 static PyObject *
-binascii_b2a_qp_impl(PyModuleDef *module, Py_buffer *data, int quotetabs,
+binascii_b2a_qp_impl(PyObject *module, Py_buffer *data, int quotetabs,
                      int istext, int header);
 
 static PyObject *
-binascii_b2a_qp(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+binascii_b2a_qp(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"data", "quotetabs", "istext", "header", NULL};
@@ -516,4 +516,4 @@ exit:
 
     return return_value;
 }
-/*[clinic end generated code: output=b1a3cbf7660ebaa5 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=6d70d5edd9373d92 input=a9049054013a1b77]*/
index 7d61649..a255353 100644 (file)
@@ -12,10 +12,10 @@ PyDoc_STRVAR(cmath_acos__doc__,
     {"acos", (PyCFunction)cmath_acos, METH_O, cmath_acos__doc__},
 
 static Py_complex
-cmath_acos_impl(PyModuleDef *module, Py_complex z);
+cmath_acos_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_acos(PyModuleDef *module, PyObject *arg)
+cmath_acos(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -53,10 +53,10 @@ PyDoc_STRVAR(cmath_acosh__doc__,
     {"acosh", (PyCFunction)cmath_acosh, METH_O, cmath_acosh__doc__},
 
 static Py_complex
-cmath_acosh_impl(PyModuleDef *module, Py_complex z);
+cmath_acosh_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_acosh(PyModuleDef *module, PyObject *arg)
+cmath_acosh(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -94,10 +94,10 @@ PyDoc_STRVAR(cmath_asin__doc__,
     {"asin", (PyCFunction)cmath_asin, METH_O, cmath_asin__doc__},
 
 static Py_complex
-cmath_asin_impl(PyModuleDef *module, Py_complex z);
+cmath_asin_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_asin(PyModuleDef *module, PyObject *arg)
+cmath_asin(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -135,10 +135,10 @@ PyDoc_STRVAR(cmath_asinh__doc__,
     {"asinh", (PyCFunction)cmath_asinh, METH_O, cmath_asinh__doc__},
 
 static Py_complex
-cmath_asinh_impl(PyModuleDef *module, Py_complex z);
+cmath_asinh_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_asinh(PyModuleDef *module, PyObject *arg)
+cmath_asinh(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -176,10 +176,10 @@ PyDoc_STRVAR(cmath_atan__doc__,
     {"atan", (PyCFunction)cmath_atan, METH_O, cmath_atan__doc__},
 
 static Py_complex
-cmath_atan_impl(PyModuleDef *module, Py_complex z);
+cmath_atan_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_atan(PyModuleDef *module, PyObject *arg)
+cmath_atan(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -217,10 +217,10 @@ PyDoc_STRVAR(cmath_atanh__doc__,
     {"atanh", (PyCFunction)cmath_atanh, METH_O, cmath_atanh__doc__},
 
 static Py_complex
-cmath_atanh_impl(PyModuleDef *module, Py_complex z);
+cmath_atanh_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_atanh(PyModuleDef *module, PyObject *arg)
+cmath_atanh(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -258,10 +258,10 @@ PyDoc_STRVAR(cmath_cos__doc__,
     {"cos", (PyCFunction)cmath_cos, METH_O, cmath_cos__doc__},
 
 static Py_complex
-cmath_cos_impl(PyModuleDef *module, Py_complex z);
+cmath_cos_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_cos(PyModuleDef *module, PyObject *arg)
+cmath_cos(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -299,10 +299,10 @@ PyDoc_STRVAR(cmath_cosh__doc__,
     {"cosh", (PyCFunction)cmath_cosh, METH_O, cmath_cosh__doc__},
 
 static Py_complex
-cmath_cosh_impl(PyModuleDef *module, Py_complex z);
+cmath_cosh_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_cosh(PyModuleDef *module, PyObject *arg)
+cmath_cosh(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -340,10 +340,10 @@ PyDoc_STRVAR(cmath_exp__doc__,
     {"exp", (PyCFunction)cmath_exp, METH_O, cmath_exp__doc__},
 
 static Py_complex
-cmath_exp_impl(PyModuleDef *module, Py_complex z);
+cmath_exp_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_exp(PyModuleDef *module, PyObject *arg)
+cmath_exp(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -381,10 +381,10 @@ PyDoc_STRVAR(cmath_log10__doc__,
     {"log10", (PyCFunction)cmath_log10, METH_O, cmath_log10__doc__},
 
 static Py_complex
-cmath_log10_impl(PyModuleDef *module, Py_complex z);
+cmath_log10_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_log10(PyModuleDef *module, PyObject *arg)
+cmath_log10(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -422,10 +422,10 @@ PyDoc_STRVAR(cmath_sin__doc__,
     {"sin", (PyCFunction)cmath_sin, METH_O, cmath_sin__doc__},
 
 static Py_complex
-cmath_sin_impl(PyModuleDef *module, Py_complex z);
+cmath_sin_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_sin(PyModuleDef *module, PyObject *arg)
+cmath_sin(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -463,10 +463,10 @@ PyDoc_STRVAR(cmath_sinh__doc__,
     {"sinh", (PyCFunction)cmath_sinh, METH_O, cmath_sinh__doc__},
 
 static Py_complex
-cmath_sinh_impl(PyModuleDef *module, Py_complex z);
+cmath_sinh_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_sinh(PyModuleDef *module, PyObject *arg)
+cmath_sinh(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -504,10 +504,10 @@ PyDoc_STRVAR(cmath_sqrt__doc__,
     {"sqrt", (PyCFunction)cmath_sqrt, METH_O, cmath_sqrt__doc__},
 
 static Py_complex
-cmath_sqrt_impl(PyModuleDef *module, Py_complex z);
+cmath_sqrt_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_sqrt(PyModuleDef *module, PyObject *arg)
+cmath_sqrt(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -545,10 +545,10 @@ PyDoc_STRVAR(cmath_tan__doc__,
     {"tan", (PyCFunction)cmath_tan, METH_O, cmath_tan__doc__},
 
 static Py_complex
-cmath_tan_impl(PyModuleDef *module, Py_complex z);
+cmath_tan_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_tan(PyModuleDef *module, PyObject *arg)
+cmath_tan(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -586,10 +586,10 @@ PyDoc_STRVAR(cmath_tanh__doc__,
     {"tanh", (PyCFunction)cmath_tanh, METH_O, cmath_tanh__doc__},
 
 static Py_complex
-cmath_tanh_impl(PyModuleDef *module, Py_complex z);
+cmath_tanh_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_tanh(PyModuleDef *module, PyObject *arg)
+cmath_tanh(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -629,10 +629,10 @@ PyDoc_STRVAR(cmath_log__doc__,
     {"log", (PyCFunction)cmath_log, METH_VARARGS, cmath_log__doc__},
 
 static PyObject *
-cmath_log_impl(PyModuleDef *module, Py_complex x, PyObject *y_obj);
+cmath_log_impl(PyObject *module, Py_complex x, PyObject *y_obj);
 
 static PyObject *
-cmath_log(PyModuleDef *module, PyObject *args)
+cmath_log(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_complex x;
@@ -657,10 +657,10 @@ PyDoc_STRVAR(cmath_phase__doc__,
     {"phase", (PyCFunction)cmath_phase, METH_O, cmath_phase__doc__},
 
 static PyObject *
-cmath_phase_impl(PyModuleDef *module, Py_complex z);
+cmath_phase_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_phase(PyModuleDef *module, PyObject *arg)
+cmath_phase(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -685,10 +685,10 @@ PyDoc_STRVAR(cmath_polar__doc__,
     {"polar", (PyCFunction)cmath_polar, METH_O, cmath_polar__doc__},
 
 static PyObject *
-cmath_polar_impl(PyModuleDef *module, Py_complex z);
+cmath_polar_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_polar(PyModuleDef *module, PyObject *arg)
+cmath_polar(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -711,10 +711,10 @@ PyDoc_STRVAR(cmath_rect__doc__,
     {"rect", (PyCFunction)cmath_rect, METH_VARARGS, cmath_rect__doc__},
 
 static PyObject *
-cmath_rect_impl(PyModuleDef *module, double r, double phi);
+cmath_rect_impl(PyObject *module, double r, double phi);
 
 static PyObject *
-cmath_rect(PyModuleDef *module, PyObject *args)
+cmath_rect(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     double r;
@@ -739,10 +739,10 @@ PyDoc_STRVAR(cmath_isfinite__doc__,
     {"isfinite", (PyCFunction)cmath_isfinite, METH_O, cmath_isfinite__doc__},
 
 static PyObject *
-cmath_isfinite_impl(PyModuleDef *module, Py_complex z);
+cmath_isfinite_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_isfinite(PyModuleDef *module, PyObject *arg)
+cmath_isfinite(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -765,10 +765,10 @@ PyDoc_STRVAR(cmath_isnan__doc__,
     {"isnan", (PyCFunction)cmath_isnan, METH_O, cmath_isnan__doc__},
 
 static PyObject *
-cmath_isnan_impl(PyModuleDef *module, Py_complex z);
+cmath_isnan_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_isnan(PyModuleDef *module, PyObject *arg)
+cmath_isnan(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -791,10 +791,10 @@ PyDoc_STRVAR(cmath_isinf__doc__,
     {"isinf", (PyCFunction)cmath_isinf, METH_O, cmath_isinf__doc__},
 
 static PyObject *
-cmath_isinf_impl(PyModuleDef *module, Py_complex z);
+cmath_isinf_impl(PyObject *module, Py_complex z);
 
 static PyObject *
-cmath_isinf(PyModuleDef *module, PyObject *arg)
+cmath_isinf(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_complex z;
@@ -832,11 +832,11 @@ PyDoc_STRVAR(cmath_isclose__doc__,
     {"isclose", (PyCFunction)cmath_isclose, METH_VARARGS|METH_KEYWORDS, cmath_isclose__doc__},
 
 static int
-cmath_isclose_impl(PyModuleDef *module, Py_complex a, Py_complex b,
+cmath_isclose_impl(PyObject *module, Py_complex a, Py_complex b,
                    double rel_tol, double abs_tol);
 
 static PyObject *
-cmath_isclose(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+cmath_isclose(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"a", "b", "rel_tol", "abs_tol", NULL};
@@ -857,4 +857,4 @@ cmath_isclose(PyModuleDef *module, PyObject *args, PyObject *kwargs)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=229e9c48c9d27362 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=732194029b7fb1e7 input=a9049054013a1b77]*/
index d9a1517..67660eb 100644 (file)
@@ -22,10 +22,10 @@ PyDoc_STRVAR(fcntl_fcntl__doc__,
     {"fcntl", (PyCFunction)fcntl_fcntl, METH_VARARGS, fcntl_fcntl__doc__},
 
 static PyObject *
-fcntl_fcntl_impl(PyModuleDef *module, int fd, int code, PyObject *arg);
+fcntl_fcntl_impl(PyObject *module, int fd, int code, PyObject *arg);
 
 static PyObject *
-fcntl_fcntl(PyModuleDef *module, PyObject *args)
+fcntl_fcntl(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -78,11 +78,11 @@ PyDoc_STRVAR(fcntl_ioctl__doc__,
     {"ioctl", (PyCFunction)fcntl_ioctl, METH_VARARGS, fcntl_ioctl__doc__},
 
 static PyObject *
-fcntl_ioctl_impl(PyModuleDef *module, int fd, unsigned int code,
+fcntl_ioctl_impl(PyObject *module, int fd, unsigned int code,
                  PyObject *ob_arg, int mutate_arg);
 
 static PyObject *
-fcntl_ioctl(PyModuleDef *module, PyObject *args)
+fcntl_ioctl(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -112,10 +112,10 @@ PyDoc_STRVAR(fcntl_flock__doc__,
     {"flock", (PyCFunction)fcntl_flock, METH_VARARGS, fcntl_flock__doc__},
 
 static PyObject *
-fcntl_flock_impl(PyModuleDef *module, int fd, int code);
+fcntl_flock_impl(PyObject *module, int fd, int code);
 
 static PyObject *
-fcntl_flock(PyModuleDef *module, PyObject *args)
+fcntl_flock(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -161,11 +161,11 @@ PyDoc_STRVAR(fcntl_lockf__doc__,
     {"lockf", (PyCFunction)fcntl_lockf, METH_VARARGS, fcntl_lockf__doc__},
 
 static PyObject *
-fcntl_lockf_impl(PyModuleDef *module, int fd, int code, PyObject *lenobj,
+fcntl_lockf_impl(PyObject *module, int fd, int code, PyObject *lenobj,
                  PyObject *startobj, int whence);
 
 static PyObject *
-fcntl_lockf(PyModuleDef *module, PyObject *args)
+fcntl_lockf(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -182,4 +182,4 @@ fcntl_lockf(PyModuleDef *module, PyObject *args)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=b7d6e8fc2ad09c48 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=97b1306b864c01c8 input=a9049054013a1b77]*/
index eb5b59d..2c47a42 100644 (file)
@@ -14,10 +14,10 @@ PyDoc_STRVAR(grp_getgrgid__doc__,
     {"getgrgid", (PyCFunction)grp_getgrgid, METH_VARARGS|METH_KEYWORDS, grp_getgrgid__doc__},
 
 static PyObject *
-grp_getgrgid_impl(PyModuleDef *module, PyObject *id);
+grp_getgrgid_impl(PyObject *module, PyObject *id);
 
 static PyObject *
-grp_getgrgid(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+grp_getgrgid(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"id", NULL};
@@ -44,10 +44,10 @@ PyDoc_STRVAR(grp_getgrnam__doc__,
     {"getgrnam", (PyCFunction)grp_getgrnam, METH_VARARGS|METH_KEYWORDS, grp_getgrnam__doc__},
 
 static PyObject *
-grp_getgrnam_impl(PyModuleDef *module, PyObject *name);
+grp_getgrnam_impl(PyObject *module, PyObject *name);
 
 static PyObject *
-grp_getgrnam(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+grp_getgrnam(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"name", NULL};
@@ -75,11 +75,11 @@ PyDoc_STRVAR(grp_getgrall__doc__,
     {"getgrall", (PyCFunction)grp_getgrall, METH_NOARGS, grp_getgrall__doc__},
 
 static PyObject *
-grp_getgrall_impl(PyModuleDef *module);
+grp_getgrall_impl(PyObject *module);
 
 static PyObject *
-grp_getgrall(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+grp_getgrall(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return grp_getgrall_impl(module);
 }
-/*[clinic end generated code: output=5191c25600afb1bd input=a9049054013a1b77]*/
+/*[clinic end generated code: output=bee09feefc54a2cb input=a9049054013a1b77]*/
index f5a3117..0bd958a 100644 (file)
@@ -75,10 +75,10 @@ PyDoc_STRVAR(_md5_md5__doc__,
     {"md5", (PyCFunction)_md5_md5, METH_VARARGS|METH_KEYWORDS, _md5_md5__doc__},
 
 static PyObject *
-_md5_md5_impl(PyModuleDef *module, PyObject *string);
+_md5_md5_impl(PyObject *module, PyObject *string);
 
 static PyObject *
-_md5_md5(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_md5_md5(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"string", NULL};
@@ -92,4 +92,4 @@ _md5_md5(PyModuleDef *module, PyObject *args, PyObject *kwargs)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=0f803ded701aca54 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=4cd3cc96e35563d2 input=a9049054013a1b77]*/
index 9ef702a..b3521d8 100644 (file)
@@ -30,11 +30,10 @@ PyDoc_STRVAR(os_stat__doc__,
     {"stat", (PyCFunction)os_stat, METH_VARARGS|METH_KEYWORDS, os_stat__doc__},
 
 static PyObject *
-os_stat_impl(PyModuleDef *module, path_t *path, int dir_fd,
-             int follow_symlinks);
+os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks);
 
 static PyObject *
-os_stat(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_stat(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "dir_fd", "follow_symlinks", NULL};
@@ -67,10 +66,10 @@ PyDoc_STRVAR(os_lstat__doc__,
     {"lstat", (PyCFunction)os_lstat, METH_VARARGS|METH_KEYWORDS, os_lstat__doc__},
 
 static PyObject *
-os_lstat_impl(PyModuleDef *module, path_t *path, int dir_fd);
+os_lstat_impl(PyObject *module, path_t *path, int dir_fd);
 
 static PyObject *
-os_lstat(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_lstat(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "dir_fd", NULL};
@@ -97,7 +96,7 @@ PyDoc_STRVAR(os_access__doc__,
 "Use the real uid/gid to test for access to a path.\n"
 "\n"
 "  path\n"
-"    Path to be tested; can be string, bytes, or open-file-descriptor int.\n"
+"    Path to be tested; can be string or bytes\n"
 "  mode\n"
 "    Operating-system mode bitfield.  Can be F_OK to test existence,\n"
 "    or the inclusive-OR of R_OK, W_OK, and X_OK.\n"
@@ -125,15 +124,15 @@ PyDoc_STRVAR(os_access__doc__,
     {"access", (PyCFunction)os_access, METH_VARARGS|METH_KEYWORDS, os_access__doc__},
 
 static int
-os_access_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd,
+os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
                int effective_ids, int follow_symlinks);
 
 static PyObject *
-os_access(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_access(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "mode", "dir_fd", "effective_ids", "follow_symlinks", NULL};
-    path_t path = PATH_T_INITIALIZE("access", "path", 0, 1);
+    path_t path = PATH_T_INITIALIZE("access", "path", 0, 0);
     int mode;
     int dir_fd = DEFAULT_DIR_FD;
     int effective_ids = 0;
@@ -170,10 +169,10 @@ PyDoc_STRVAR(os_ttyname__doc__,
     {"ttyname", (PyCFunction)os_ttyname, METH_O, os_ttyname__doc__},
 
 static char *
-os_ttyname_impl(PyModuleDef *module, int fd);
+os_ttyname_impl(PyObject *module, int fd);
 
 static PyObject *
-os_ttyname(PyModuleDef *module, PyObject *arg)
+os_ttyname(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -204,10 +203,10 @@ PyDoc_STRVAR(os_ctermid__doc__,
     {"ctermid", (PyCFunction)os_ctermid, METH_NOARGS, os_ctermid__doc__},
 
 static PyObject *
-os_ctermid_impl(PyModuleDef *module);
+os_ctermid_impl(PyObject *module);
 
 static PyObject *
-os_ctermid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_ctermid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_ctermid_impl(module);
 }
@@ -228,10 +227,10 @@ PyDoc_STRVAR(os_chdir__doc__,
     {"chdir", (PyCFunction)os_chdir, METH_VARARGS|METH_KEYWORDS, os_chdir__doc__},
 
 static PyObject *
-os_chdir_impl(PyModuleDef *module, path_t *path);
+os_chdir_impl(PyObject *module, path_t *path);
 
 static PyObject *
-os_chdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_chdir(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", NULL};
@@ -264,10 +263,10 @@ PyDoc_STRVAR(os_fchdir__doc__,
     {"fchdir", (PyCFunction)os_fchdir, METH_VARARGS|METH_KEYWORDS, os_fchdir__doc__},
 
 static PyObject *
-os_fchdir_impl(PyModuleDef *module, int fd);
+os_fchdir_impl(PyObject *module, int fd);
 
 static PyObject *
-os_fchdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_fchdir(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"fd", NULL};
@@ -314,11 +313,11 @@ PyDoc_STRVAR(os_chmod__doc__,
     {"chmod", (PyCFunction)os_chmod, METH_VARARGS|METH_KEYWORDS, os_chmod__doc__},
 
 static PyObject *
-os_chmod_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd,
+os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
               int follow_symlinks);
 
 static PyObject *
-os_chmod(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_chmod(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "mode", "dir_fd", "follow_symlinks", NULL};
@@ -353,10 +352,10 @@ PyDoc_STRVAR(os_fchmod__doc__,
     {"fchmod", (PyCFunction)os_fchmod, METH_VARARGS|METH_KEYWORDS, os_fchmod__doc__},
 
 static PyObject *
-os_fchmod_impl(PyModuleDef *module, int fd, int mode);
+os_fchmod_impl(PyObject *module, int fd, int mode);
 
 static PyObject *
-os_fchmod(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_fchmod(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"fd", "mode", NULL};
@@ -389,10 +388,10 @@ PyDoc_STRVAR(os_lchmod__doc__,
     {"lchmod", (PyCFunction)os_lchmod, METH_VARARGS|METH_KEYWORDS, os_lchmod__doc__},
 
 static PyObject *
-os_lchmod_impl(PyModuleDef *module, path_t *path, int mode);
+os_lchmod_impl(PyObject *module, path_t *path, int mode);
 
 static PyObject *
-os_lchmod(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_lchmod(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "mode", NULL};
@@ -431,11 +430,11 @@ PyDoc_STRVAR(os_chflags__doc__,
     {"chflags", (PyCFunction)os_chflags, METH_VARARGS|METH_KEYWORDS, os_chflags__doc__},
 
 static PyObject *
-os_chflags_impl(PyModuleDef *module, path_t *path, unsigned long flags,
+os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
                 int follow_symlinks);
 
 static PyObject *
-os_chflags(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_chflags(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "flags", "follow_symlinks", NULL};
@@ -472,10 +471,10 @@ PyDoc_STRVAR(os_lchflags__doc__,
     {"lchflags", (PyCFunction)os_lchflags, METH_VARARGS|METH_KEYWORDS, os_lchflags__doc__},
 
 static PyObject *
-os_lchflags_impl(PyModuleDef *module, path_t *path, unsigned long flags);
+os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags);
 
 static PyObject *
-os_lchflags(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_lchflags(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "flags", NULL};
@@ -508,10 +507,10 @@ PyDoc_STRVAR(os_chroot__doc__,
     {"chroot", (PyCFunction)os_chroot, METH_VARARGS|METH_KEYWORDS, os_chroot__doc__},
 
 static PyObject *
-os_chroot_impl(PyModuleDef *module, path_t *path);
+os_chroot_impl(PyObject *module, path_t *path);
 
 static PyObject *
-os_chroot(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_chroot(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", NULL};
@@ -543,10 +542,10 @@ PyDoc_STRVAR(os_fsync__doc__,
     {"fsync", (PyCFunction)os_fsync, METH_VARARGS|METH_KEYWORDS, os_fsync__doc__},
 
 static PyObject *
-os_fsync_impl(PyModuleDef *module, int fd);
+os_fsync_impl(PyObject *module, int fd);
 
 static PyObject *
-os_fsync(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_fsync(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"fd", NULL};
@@ -575,10 +574,10 @@ PyDoc_STRVAR(os_sync__doc__,
     {"sync", (PyCFunction)os_sync, METH_NOARGS, os_sync__doc__},
 
 static PyObject *
-os_sync_impl(PyModuleDef *module);
+os_sync_impl(PyObject *module);
 
 static PyObject *
-os_sync(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_sync(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_sync_impl(module);
 }
@@ -597,10 +596,10 @@ PyDoc_STRVAR(os_fdatasync__doc__,
     {"fdatasync", (PyCFunction)os_fdatasync, METH_VARARGS|METH_KEYWORDS, os_fdatasync__doc__},
 
 static PyObject *
-os_fdatasync_impl(PyModuleDef *module, int fd);
+os_fdatasync_impl(PyObject *module, int fd);
 
 static PyObject *
-os_fdatasync(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_fdatasync(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"fd", NULL};
@@ -653,11 +652,11 @@ PyDoc_STRVAR(os_chown__doc__,
     {"chown", (PyCFunction)os_chown, METH_VARARGS|METH_KEYWORDS, os_chown__doc__},
 
 static PyObject *
-os_chown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid,
+os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
               int dir_fd, int follow_symlinks);
 
 static PyObject *
-os_chown(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_chown(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "uid", "gid", "dir_fd", "follow_symlinks", NULL};
@@ -695,10 +694,10 @@ PyDoc_STRVAR(os_fchown__doc__,
     {"fchown", (PyCFunction)os_fchown, METH_VARARGS|METH_KEYWORDS, os_fchown__doc__},
 
 static PyObject *
-os_fchown_impl(PyModuleDef *module, int fd, uid_t uid, gid_t gid);
+os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid);
 
 static PyObject *
-os_fchown(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_fchown(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"fd", "uid", "gid", NULL};
@@ -732,10 +731,10 @@ PyDoc_STRVAR(os_lchown__doc__,
     {"lchown", (PyCFunction)os_lchown, METH_VARARGS|METH_KEYWORDS, os_lchown__doc__},
 
 static PyObject *
-os_lchown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid);
+os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid);
 
 static PyObject *
-os_lchown(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_lchown(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "uid", "gid", NULL};
@@ -767,10 +766,10 @@ PyDoc_STRVAR(os_getcwd__doc__,
     {"getcwd", (PyCFunction)os_getcwd, METH_NOARGS, os_getcwd__doc__},
 
 static PyObject *
-os_getcwd_impl(PyModuleDef *module);
+os_getcwd_impl(PyObject *module);
 
 static PyObject *
-os_getcwd(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getcwd(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getcwd_impl(module);
 }
@@ -785,10 +784,10 @@ PyDoc_STRVAR(os_getcwdb__doc__,
     {"getcwdb", (PyCFunction)os_getcwdb, METH_NOARGS, os_getcwdb__doc__},
 
 static PyObject *
-os_getcwdb_impl(PyModuleDef *module);
+os_getcwdb_impl(PyObject *module);
 
 static PyObject *
-os_getcwdb(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getcwdb(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getcwdb_impl(module);
 }
@@ -816,11 +815,11 @@ PyDoc_STRVAR(os_link__doc__,
     {"link", (PyCFunction)os_link, METH_VARARGS|METH_KEYWORDS, os_link__doc__},
 
 static PyObject *
-os_link_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd,
+os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
              int dst_dir_fd, int follow_symlinks);
 
 static PyObject *
-os_link(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_link(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"src", "dst", "src_dir_fd", "dst_dir_fd", "follow_symlinks", NULL};
@@ -867,10 +866,10 @@ PyDoc_STRVAR(os_listdir__doc__,
     {"listdir", (PyCFunction)os_listdir, METH_VARARGS|METH_KEYWORDS, os_listdir__doc__},
 
 static PyObject *
-os_listdir_impl(PyModuleDef *module, path_t *path);
+os_listdir_impl(PyObject *module, path_t *path);
 
 static PyObject *
-os_listdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_listdir(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", NULL};
@@ -899,10 +898,10 @@ PyDoc_STRVAR(os__getfullpathname__doc__,
     {"_getfullpathname", (PyCFunction)os__getfullpathname, METH_O, os__getfullpathname__doc__},
 
 static PyObject *
-os__getfullpathname_impl(PyModuleDef *module, path_t *path);
+os__getfullpathname_impl(PyObject *module, path_t *path);
 
 static PyObject *
-os__getfullpathname(PyModuleDef *module, PyObject *arg)
+os__getfullpathname(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     path_t path = PATH_T_INITIALIZE("_getfullpathname", "path", 0, 0);
@@ -932,10 +931,10 @@ PyDoc_STRVAR(os__getfinalpathname__doc__,
     {"_getfinalpathname", (PyCFunction)os__getfinalpathname, METH_O, os__getfinalpathname__doc__},
 
 static PyObject *
-os__getfinalpathname_impl(PyModuleDef *module, PyObject *path);
+os__getfinalpathname_impl(PyObject *module, PyObject *path);
 
 static PyObject *
-os__getfinalpathname(PyModuleDef *module, PyObject *arg)
+os__getfinalpathname(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *path;
@@ -955,16 +954,17 @@ exit:
 PyDoc_STRVAR(os__isdir__doc__,
 "_isdir($module, path, /)\n"
 "--\n"
-"\n");
+"\n"
+"Return true if the pathname refers to an existing directory.");
 
 #define OS__ISDIR_METHODDEF    \
     {"_isdir", (PyCFunction)os__isdir, METH_O, os__isdir__doc__},
 
 static PyObject *
-os__isdir_impl(PyModuleDef *module, path_t *path);
+os__isdir_impl(PyObject *module, path_t *path);
 
 static PyObject *
-os__isdir(PyModuleDef *module, PyObject *arg)
+os__isdir(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     path_t path = PATH_T_INITIALIZE("_isdir", "path", 0, 0);
@@ -994,10 +994,10 @@ PyDoc_STRVAR(os__getvolumepathname__doc__,
     {"_getvolumepathname", (PyCFunction)os__getvolumepathname, METH_VARARGS|METH_KEYWORDS, os__getvolumepathname__doc__},
 
 static PyObject *
-os__getvolumepathname_impl(PyModuleDef *module, PyObject *path);
+os__getvolumepathname_impl(PyObject *module, PyObject *path);
 
 static PyObject *
-os__getvolumepathname(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os__getvolumepathname(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", NULL};
@@ -1031,10 +1031,10 @@ PyDoc_STRVAR(os_mkdir__doc__,
     {"mkdir", (PyCFunction)os_mkdir, METH_VARARGS|METH_KEYWORDS, os_mkdir__doc__},
 
 static PyObject *
-os_mkdir_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd);
+os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd);
 
 static PyObject *
-os_mkdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_mkdir(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "mode", "dir_fd", NULL};
@@ -1066,10 +1066,10 @@ PyDoc_STRVAR(os_nice__doc__,
     {"nice", (PyCFunction)os_nice, METH_O, os_nice__doc__},
 
 static PyObject *
-os_nice_impl(PyModuleDef *module, int increment);
+os_nice_impl(PyObject *module, int increment);
 
 static PyObject *
-os_nice(PyModuleDef *module, PyObject *arg)
+os_nice(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int increment;
@@ -1096,10 +1096,10 @@ PyDoc_STRVAR(os_getpriority__doc__,
     {"getpriority", (PyCFunction)os_getpriority, METH_VARARGS|METH_KEYWORDS, os_getpriority__doc__},
 
 static PyObject *
-os_getpriority_impl(PyModuleDef *module, int which, int who);
+os_getpriority_impl(PyObject *module, int which, int who);
 
 static PyObject *
-os_getpriority(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_getpriority(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"which", "who", NULL};
@@ -1129,10 +1129,10 @@ PyDoc_STRVAR(os_setpriority__doc__,
     {"setpriority", (PyCFunction)os_setpriority, METH_VARARGS|METH_KEYWORDS, os_setpriority__doc__},
 
 static PyObject *
-os_setpriority_impl(PyModuleDef *module, int which, int who, int priority);
+os_setpriority_impl(PyObject *module, int which, int who, int priority);
 
 static PyObject *
-os_setpriority(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_setpriority(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"which", "who", "priority", NULL};
@@ -1167,11 +1167,11 @@ PyDoc_STRVAR(os_rename__doc__,
     {"rename", (PyCFunction)os_rename, METH_VARARGS|METH_KEYWORDS, os_rename__doc__},
 
 static PyObject *
-os_rename_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd,
+os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
                int dst_dir_fd);
 
 static PyObject *
-os_rename(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_rename(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"src", "dst", "src_dir_fd", "dst_dir_fd", NULL};
@@ -1210,11 +1210,11 @@ PyDoc_STRVAR(os_replace__doc__,
     {"replace", (PyCFunction)os_replace, METH_VARARGS|METH_KEYWORDS, os_replace__doc__},
 
 static PyObject *
-os_replace_impl(PyModuleDef *module, path_t *src, path_t *dst,
-                int src_dir_fd, int dst_dir_fd);
+os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
+                int dst_dir_fd);
 
 static PyObject *
-os_replace(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_replace(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"src", "dst", "src_dir_fd", "dst_dir_fd", NULL};
@@ -1252,10 +1252,10 @@ PyDoc_STRVAR(os_rmdir__doc__,
     {"rmdir", (PyCFunction)os_rmdir, METH_VARARGS|METH_KEYWORDS, os_rmdir__doc__},
 
 static PyObject *
-os_rmdir_impl(PyModuleDef *module, path_t *path, int dir_fd);
+os_rmdir_impl(PyObject *module, path_t *path, int dir_fd);
 
 static PyObject *
-os_rmdir(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_rmdir(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "dir_fd", NULL};
@@ -1286,10 +1286,10 @@ PyDoc_STRVAR(os_system__doc__,
     {"system", (PyCFunction)os_system, METH_VARARGS|METH_KEYWORDS, os_system__doc__},
 
 static long
-os_system_impl(PyModuleDef *module, Py_UNICODE *command);
+os_system_impl(PyObject *module, Py_UNICODE *command);
 
 static PyObject *
-os_system(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_system(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"command", NULL};
@@ -1322,10 +1322,10 @@ PyDoc_STRVAR(os_system__doc__,
     {"system", (PyCFunction)os_system, METH_VARARGS|METH_KEYWORDS, os_system__doc__},
 
 static long
-os_system_impl(PyModuleDef *module, PyObject *command);
+os_system_impl(PyObject *module, PyObject *command);
 
 static PyObject *
-os_system(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_system(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"command", NULL};
@@ -1359,10 +1359,10 @@ PyDoc_STRVAR(os_umask__doc__,
     {"umask", (PyCFunction)os_umask, METH_O, os_umask__doc__},
 
 static PyObject *
-os_umask_impl(PyModuleDef *module, int mask);
+os_umask_impl(PyObject *module, int mask);
 
 static PyObject *
-os_umask(PyModuleDef *module, PyObject *arg)
+os_umask(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int mask;
@@ -1390,10 +1390,10 @@ PyDoc_STRVAR(os_unlink__doc__,
     {"unlink", (PyCFunction)os_unlink, METH_VARARGS|METH_KEYWORDS, os_unlink__doc__},
 
 static PyObject *
-os_unlink_impl(PyModuleDef *module, path_t *path, int dir_fd);
+os_unlink_impl(PyObject *module, path_t *path, int dir_fd);
 
 static PyObject *
-os_unlink(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_unlink(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "dir_fd", NULL};
@@ -1427,10 +1427,10 @@ PyDoc_STRVAR(os_remove__doc__,
     {"remove", (PyCFunction)os_remove, METH_VARARGS|METH_KEYWORDS, os_remove__doc__},
 
 static PyObject *
-os_remove_impl(PyModuleDef *module, path_t *path, int dir_fd);
+os_remove_impl(PyObject *module, path_t *path, int dir_fd);
 
 static PyObject *
-os_remove(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_remove(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "dir_fd", NULL};
@@ -1464,10 +1464,10 @@ PyDoc_STRVAR(os_uname__doc__,
     {"uname", (PyCFunction)os_uname, METH_NOARGS, os_uname__doc__},
 
 static PyObject *
-os_uname_impl(PyModuleDef *module);
+os_uname_impl(PyObject *module);
 
 static PyObject *
-os_uname(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_uname(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_uname_impl(module);
 }
@@ -1507,11 +1507,11 @@ PyDoc_STRVAR(os_utime__doc__,
     {"utime", (PyCFunction)os_utime, METH_VARARGS|METH_KEYWORDS, os_utime__doc__},
 
 static PyObject *
-os_utime_impl(PyModuleDef *module, path_t *path, PyObject *times,
-              PyObject *ns, int dir_fd, int follow_symlinks);
+os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
+              int dir_fd, int follow_symlinks);
 
 static PyObject *
-os_utime(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_utime(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "times", "ns", "dir_fd", "follow_symlinks", NULL};
@@ -1543,10 +1543,10 @@ PyDoc_STRVAR(os__exit__doc__,
     {"_exit", (PyCFunction)os__exit, METH_VARARGS|METH_KEYWORDS, os__exit__doc__},
 
 static PyObject *
-os__exit_impl(PyModuleDef *module, int status);
+os__exit_impl(PyObject *module, int status);
 
 static PyObject *
-os__exit(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os__exit(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"status", NULL};
@@ -1578,10 +1578,10 @@ PyDoc_STRVAR(os_execv__doc__,
     {"execv", (PyCFunction)os_execv, METH_VARARGS, os_execv__doc__},
 
 static PyObject *
-os_execv_impl(PyModuleDef *module, PyObject *path, PyObject *argv);
+os_execv_impl(PyObject *module, PyObject *path, PyObject *argv);
 
 static PyObject *
-os_execv(PyModuleDef *module, PyObject *args)
+os_execv(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *path = NULL;
@@ -1620,11 +1620,10 @@ PyDoc_STRVAR(os_execve__doc__,
     {"execve", (PyCFunction)os_execve, METH_VARARGS|METH_KEYWORDS, os_execve__doc__},
 
 static PyObject *
-os_execve_impl(PyModuleDef *module, path_t *path, PyObject *argv,
-               PyObject *env);
+os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env);
 
 static PyObject *
-os_execve(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_execve(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "argv", "env", NULL};
@@ -1665,10 +1664,10 @@ PyDoc_STRVAR(os_spawnv__doc__,
     {"spawnv", (PyCFunction)os_spawnv, METH_VARARGS, os_spawnv__doc__},
 
 static PyObject *
-os_spawnv_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv);
+os_spawnv_impl(PyObject *module, int mode, PyObject *path, PyObject *argv);
 
 static PyObject *
-os_spawnv(PyModuleDef *module, PyObject *args)
+os_spawnv(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int mode;
@@ -1710,11 +1709,11 @@ PyDoc_STRVAR(os_spawnve__doc__,
     {"spawnve", (PyCFunction)os_spawnve, METH_VARARGS, os_spawnve__doc__},
 
 static PyObject *
-os_spawnve_impl(PyModuleDef *module, int mode, PyObject *path,
-                PyObject *argv, PyObject *env);
+os_spawnve_impl(PyObject *module, int mode, PyObject *path, PyObject *argv,
+                PyObject *env);
 
 static PyObject *
-os_spawnve(PyModuleDef *module, PyObject *args)
+os_spawnve(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int mode;
@@ -1750,10 +1749,10 @@ PyDoc_STRVAR(os_fork1__doc__,
     {"fork1", (PyCFunction)os_fork1, METH_NOARGS, os_fork1__doc__},
 
 static PyObject *
-os_fork1_impl(PyModuleDef *module);
+os_fork1_impl(PyObject *module);
 
 static PyObject *
-os_fork1(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_fork1(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_fork1_impl(module);
 }
@@ -1774,10 +1773,10 @@ PyDoc_STRVAR(os_fork__doc__,
     {"fork", (PyCFunction)os_fork, METH_NOARGS, os_fork__doc__},
 
 static PyObject *
-os_fork_impl(PyModuleDef *module);
+os_fork_impl(PyObject *module);
 
 static PyObject *
-os_fork(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_fork(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_fork_impl(module);
 }
@@ -1796,10 +1795,10 @@ PyDoc_STRVAR(os_sched_get_priority_max__doc__,
     {"sched_get_priority_max", (PyCFunction)os_sched_get_priority_max, METH_VARARGS|METH_KEYWORDS, os_sched_get_priority_max__doc__},
 
 static PyObject *
-os_sched_get_priority_max_impl(PyModuleDef *module, int policy);
+os_sched_get_priority_max_impl(PyObject *module, int policy);
 
 static PyObject *
-os_sched_get_priority_max(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_sched_get_priority_max(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"policy", NULL};
@@ -1828,10 +1827,10 @@ PyDoc_STRVAR(os_sched_get_priority_min__doc__,
     {"sched_get_priority_min", (PyCFunction)os_sched_get_priority_min, METH_VARARGS|METH_KEYWORDS, os_sched_get_priority_min__doc__},
 
 static PyObject *
-os_sched_get_priority_min_impl(PyModuleDef *module, int policy);
+os_sched_get_priority_min_impl(PyObject *module, int policy);
 
 static PyObject *
-os_sched_get_priority_min(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_sched_get_priority_min(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"policy", NULL};
@@ -1862,10 +1861,10 @@ PyDoc_STRVAR(os_sched_getscheduler__doc__,
     {"sched_getscheduler", (PyCFunction)os_sched_getscheduler, METH_O, os_sched_getscheduler__doc__},
 
 static PyObject *
-os_sched_getscheduler_impl(PyModuleDef *module, pid_t pid);
+os_sched_getscheduler_impl(PyObject *module, pid_t pid);
 
 static PyObject *
-os_sched_getscheduler(PyModuleDef *module, PyObject *arg)
+os_sched_getscheduler(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -1927,11 +1926,11 @@ PyDoc_STRVAR(os_sched_setscheduler__doc__,
     {"sched_setscheduler", (PyCFunction)os_sched_setscheduler, METH_VARARGS, os_sched_setscheduler__doc__},
 
 static PyObject *
-os_sched_setscheduler_impl(PyModuleDef *module, pid_t pid, int policy,
+os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
                            struct sched_param *param);
 
 static PyObject *
-os_sched_setscheduler(PyModuleDef *module, PyObject *args)
+os_sched_setscheduler(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -1964,10 +1963,10 @@ PyDoc_STRVAR(os_sched_getparam__doc__,
     {"sched_getparam", (PyCFunction)os_sched_getparam, METH_O, os_sched_getparam__doc__},
 
 static PyObject *
-os_sched_getparam_impl(PyModuleDef *module, pid_t pid);
+os_sched_getparam_impl(PyObject *module, pid_t pid);
 
 static PyObject *
-os_sched_getparam(PyModuleDef *module, PyObject *arg)
+os_sched_getparam(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -1997,11 +1996,11 @@ PyDoc_STRVAR(os_sched_setparam__doc__,
     {"sched_setparam", (PyCFunction)os_sched_setparam, METH_VARARGS, os_sched_setparam__doc__},
 
 static PyObject *
-os_sched_setparam_impl(PyModuleDef *module, pid_t pid,
+os_sched_setparam_impl(PyObject *module, pid_t pid,
                        struct sched_param *param);
 
 static PyObject *
-os_sched_setparam(PyModuleDef *module, PyObject *args)
+os_sched_setparam(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -2032,10 +2031,10 @@ PyDoc_STRVAR(os_sched_rr_get_interval__doc__,
     {"sched_rr_get_interval", (PyCFunction)os_sched_rr_get_interval, METH_O, os_sched_rr_get_interval__doc__},
 
 static double
-os_sched_rr_get_interval_impl(PyModuleDef *module, pid_t pid);
+os_sched_rr_get_interval_impl(PyObject *module, pid_t pid);
 
 static PyObject *
-os_sched_rr_get_interval(PyModuleDef *module, PyObject *arg)
+os_sched_rr_get_interval(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -2066,10 +2065,10 @@ PyDoc_STRVAR(os_sched_yield__doc__,
     {"sched_yield", (PyCFunction)os_sched_yield, METH_NOARGS, os_sched_yield__doc__},
 
 static PyObject *
-os_sched_yield_impl(PyModuleDef *module);
+os_sched_yield_impl(PyObject *module);
 
 static PyObject *
-os_sched_yield(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_sched_yield(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_sched_yield_impl(module);
 }
@@ -2090,10 +2089,10 @@ PyDoc_STRVAR(os_sched_setaffinity__doc__,
     {"sched_setaffinity", (PyCFunction)os_sched_setaffinity, METH_VARARGS, os_sched_setaffinity__doc__},
 
 static PyObject *
-os_sched_setaffinity_impl(PyModuleDef *module, pid_t pid, PyObject *mask);
+os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask);
 
 static PyObject *
-os_sched_setaffinity(PyModuleDef *module, PyObject *args)
+os_sched_setaffinity(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -2124,10 +2123,10 @@ PyDoc_STRVAR(os_sched_getaffinity__doc__,
     {"sched_getaffinity", (PyCFunction)os_sched_getaffinity, METH_O, os_sched_getaffinity__doc__},
 
 static PyObject *
-os_sched_getaffinity_impl(PyModuleDef *module, pid_t pid);
+os_sched_getaffinity_impl(PyObject *module, pid_t pid);
 
 static PyObject *
-os_sched_getaffinity(PyModuleDef *module, PyObject *arg)
+os_sched_getaffinity(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -2157,10 +2156,10 @@ PyDoc_STRVAR(os_openpty__doc__,
     {"openpty", (PyCFunction)os_openpty, METH_NOARGS, os_openpty__doc__},
 
 static PyObject *
-os_openpty_impl(PyModuleDef *module);
+os_openpty_impl(PyObject *module);
 
 static PyObject *
-os_openpty(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_openpty(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_openpty_impl(module);
 }
@@ -2184,10 +2183,10 @@ PyDoc_STRVAR(os_forkpty__doc__,
     {"forkpty", (PyCFunction)os_forkpty, METH_NOARGS, os_forkpty__doc__},
 
 static PyObject *
-os_forkpty_impl(PyModuleDef *module);
+os_forkpty_impl(PyObject *module);
 
 static PyObject *
-os_forkpty(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_forkpty(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_forkpty_impl(module);
 }
@@ -2206,10 +2205,10 @@ PyDoc_STRVAR(os_getegid__doc__,
     {"getegid", (PyCFunction)os_getegid, METH_NOARGS, os_getegid__doc__},
 
 static PyObject *
-os_getegid_impl(PyModuleDef *module);
+os_getegid_impl(PyObject *module);
 
 static PyObject *
-os_getegid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getegid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getegid_impl(module);
 }
@@ -2228,10 +2227,10 @@ PyDoc_STRVAR(os_geteuid__doc__,
     {"geteuid", (PyCFunction)os_geteuid, METH_NOARGS, os_geteuid__doc__},
 
 static PyObject *
-os_geteuid_impl(PyModuleDef *module);
+os_geteuid_impl(PyObject *module);
 
 static PyObject *
-os_geteuid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_geteuid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_geteuid_impl(module);
 }
@@ -2250,10 +2249,10 @@ PyDoc_STRVAR(os_getgid__doc__,
     {"getgid", (PyCFunction)os_getgid, METH_NOARGS, os_getgid__doc__},
 
 static PyObject *
-os_getgid_impl(PyModuleDef *module);
+os_getgid_impl(PyObject *module);
 
 static PyObject *
-os_getgid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getgid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getgid_impl(module);
 }
@@ -2270,10 +2269,10 @@ PyDoc_STRVAR(os_getpid__doc__,
     {"getpid", (PyCFunction)os_getpid, METH_NOARGS, os_getpid__doc__},
 
 static PyObject *
-os_getpid_impl(PyModuleDef *module);
+os_getpid_impl(PyObject *module);
 
 static PyObject *
-os_getpid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getpid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getpid_impl(module);
 }
@@ -2290,10 +2289,10 @@ PyDoc_STRVAR(os_getgroups__doc__,
     {"getgroups", (PyCFunction)os_getgroups, METH_NOARGS, os_getgroups__doc__},
 
 static PyObject *
-os_getgroups_impl(PyModuleDef *module);
+os_getgroups_impl(PyObject *module);
 
 static PyObject *
-os_getgroups(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getgroups(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getgroups_impl(module);
 }
@@ -2312,10 +2311,10 @@ PyDoc_STRVAR(os_getpgid__doc__,
     {"getpgid", (PyCFunction)os_getpgid, METH_VARARGS|METH_KEYWORDS, os_getpgid__doc__},
 
 static PyObject *
-os_getpgid_impl(PyModuleDef *module, pid_t pid);
+os_getpgid_impl(PyObject *module, pid_t pid);
 
 static PyObject *
-os_getpgid(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_getpgid(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"pid", NULL};
@@ -2344,10 +2343,10 @@ PyDoc_STRVAR(os_getpgrp__doc__,
     {"getpgrp", (PyCFunction)os_getpgrp, METH_NOARGS, os_getpgrp__doc__},
 
 static PyObject *
-os_getpgrp_impl(PyModuleDef *module);
+os_getpgrp_impl(PyObject *module);
 
 static PyObject *
-os_getpgrp(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getpgrp(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getpgrp_impl(module);
 }
@@ -2366,10 +2365,10 @@ PyDoc_STRVAR(os_setpgrp__doc__,
     {"setpgrp", (PyCFunction)os_setpgrp, METH_NOARGS, os_setpgrp__doc__},
 
 static PyObject *
-os_setpgrp_impl(PyModuleDef *module);
+os_setpgrp_impl(PyObject *module);
 
 static PyObject *
-os_setpgrp(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_setpgrp(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_setpgrp_impl(module);
 }
@@ -2391,10 +2390,10 @@ PyDoc_STRVAR(os_getppid__doc__,
     {"getppid", (PyCFunction)os_getppid, METH_NOARGS, os_getppid__doc__},
 
 static PyObject *
-os_getppid_impl(PyModuleDef *module);
+os_getppid_impl(PyObject *module);
 
 static PyObject *
-os_getppid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getppid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getppid_impl(module);
 }
@@ -2413,10 +2412,10 @@ PyDoc_STRVAR(os_getlogin__doc__,
     {"getlogin", (PyCFunction)os_getlogin, METH_NOARGS, os_getlogin__doc__},
 
 static PyObject *
-os_getlogin_impl(PyModuleDef *module);
+os_getlogin_impl(PyObject *module);
 
 static PyObject *
-os_getlogin(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getlogin(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getlogin_impl(module);
 }
@@ -2435,10 +2434,10 @@ PyDoc_STRVAR(os_getuid__doc__,
     {"getuid", (PyCFunction)os_getuid, METH_NOARGS, os_getuid__doc__},
 
 static PyObject *
-os_getuid_impl(PyModuleDef *module);
+os_getuid_impl(PyObject *module);
 
 static PyObject *
-os_getuid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getuid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getuid_impl(module);
 }
@@ -2457,10 +2456,10 @@ PyDoc_STRVAR(os_kill__doc__,
     {"kill", (PyCFunction)os_kill, METH_VARARGS, os_kill__doc__},
 
 static PyObject *
-os_kill_impl(PyModuleDef *module, pid_t pid, Py_ssize_t signal);
+os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal);
 
 static PyObject *
-os_kill(PyModuleDef *module, PyObject *args)
+os_kill(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -2489,10 +2488,10 @@ PyDoc_STRVAR(os_killpg__doc__,
     {"killpg", (PyCFunction)os_killpg, METH_VARARGS, os_killpg__doc__},
 
 static PyObject *
-os_killpg_impl(PyModuleDef *module, pid_t pgid, int signal);
+os_killpg_impl(PyObject *module, pid_t pgid, int signal);
 
 static PyObject *
-os_killpg(PyModuleDef *module, PyObject *args)
+os_killpg(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     pid_t pgid;
@@ -2521,10 +2520,10 @@ PyDoc_STRVAR(os_plock__doc__,
     {"plock", (PyCFunction)os_plock, METH_O, os_plock__doc__},
 
 static PyObject *
-os_plock_impl(PyModuleDef *module, int op);
+os_plock_impl(PyObject *module, int op);
 
 static PyObject *
-os_plock(PyModuleDef *module, PyObject *arg)
+os_plock(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int op;
@@ -2551,10 +2550,10 @@ PyDoc_STRVAR(os_setuid__doc__,
     {"setuid", (PyCFunction)os_setuid, METH_O, os_setuid__doc__},
 
 static PyObject *
-os_setuid_impl(PyModuleDef *module, uid_t uid);
+os_setuid_impl(PyObject *module, uid_t uid);
 
 static PyObject *
-os_setuid(PyModuleDef *module, PyObject *arg)
+os_setuid(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     uid_t uid;
@@ -2581,10 +2580,10 @@ PyDoc_STRVAR(os_seteuid__doc__,
     {"seteuid", (PyCFunction)os_seteuid, METH_O, os_seteuid__doc__},
 
 static PyObject *
-os_seteuid_impl(PyModuleDef *module, uid_t euid);
+os_seteuid_impl(PyObject *module, uid_t euid);
 
 static PyObject *
-os_seteuid(PyModuleDef *module, PyObject *arg)
+os_seteuid(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     uid_t euid;
@@ -2611,10 +2610,10 @@ PyDoc_STRVAR(os_setegid__doc__,
     {"setegid", (PyCFunction)os_setegid, METH_O, os_setegid__doc__},
 
 static PyObject *
-os_setegid_impl(PyModuleDef *module, gid_t egid);
+os_setegid_impl(PyObject *module, gid_t egid);
 
 static PyObject *
-os_setegid(PyModuleDef *module, PyObject *arg)
+os_setegid(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     gid_t egid;
@@ -2641,10 +2640,10 @@ PyDoc_STRVAR(os_setreuid__doc__,
     {"setreuid", (PyCFunction)os_setreuid, METH_VARARGS, os_setreuid__doc__},
 
 static PyObject *
-os_setreuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid);
+os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid);
 
 static PyObject *
-os_setreuid(PyModuleDef *module, PyObject *args)
+os_setreuid(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     uid_t ruid;
@@ -2673,10 +2672,10 @@ PyDoc_STRVAR(os_setregid__doc__,
     {"setregid", (PyCFunction)os_setregid, METH_VARARGS, os_setregid__doc__},
 
 static PyObject *
-os_setregid_impl(PyModuleDef *module, gid_t rgid, gid_t egid);
+os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid);
 
 static PyObject *
-os_setregid(PyModuleDef *module, PyObject *args)
+os_setregid(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     gid_t rgid;
@@ -2705,10 +2704,10 @@ PyDoc_STRVAR(os_setgid__doc__,
     {"setgid", (PyCFunction)os_setgid, METH_O, os_setgid__doc__},
 
 static PyObject *
-os_setgid_impl(PyModuleDef *module, gid_t gid);
+os_setgid_impl(PyObject *module, gid_t gid);
 
 static PyObject *
-os_setgid(PyModuleDef *module, PyObject *arg)
+os_setgid(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     gid_t gid;
@@ -2751,10 +2750,10 @@ PyDoc_STRVAR(os_wait3__doc__,
     {"wait3", (PyCFunction)os_wait3, METH_VARARGS|METH_KEYWORDS, os_wait3__doc__},
 
 static PyObject *
-os_wait3_impl(PyModuleDef *module, int options);
+os_wait3_impl(PyObject *module, int options);
 
 static PyObject *
-os_wait3(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_wait3(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"options", NULL};
@@ -2786,10 +2785,10 @@ PyDoc_STRVAR(os_wait4__doc__,
     {"wait4", (PyCFunction)os_wait4, METH_VARARGS|METH_KEYWORDS, os_wait4__doc__},
 
 static PyObject *
-os_wait4_impl(PyModuleDef *module, pid_t pid, int options);
+os_wait4_impl(PyObject *module, pid_t pid, int options);
 
 static PyObject *
-os_wait4(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_wait4(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"pid", "options", NULL};
@@ -2830,10 +2829,10 @@ PyDoc_STRVAR(os_waitid__doc__,
     {"waitid", (PyCFunction)os_waitid, METH_VARARGS, os_waitid__doc__},
 
 static PyObject *
-os_waitid_impl(PyModuleDef *module, idtype_t idtype, id_t id, int options);
+os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options);
 
 static PyObject *
-os_waitid(PyModuleDef *module, PyObject *args)
+os_waitid(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     idtype_t idtype;
@@ -2868,10 +2867,10 @@ PyDoc_STRVAR(os_waitpid__doc__,
     {"waitpid", (PyCFunction)os_waitpid, METH_VARARGS, os_waitpid__doc__},
 
 static PyObject *
-os_waitpid_impl(PyModuleDef *module, pid_t pid, int options);
+os_waitpid_impl(PyObject *module, pid_t pid, int options);
 
 static PyObject *
-os_waitpid(PyModuleDef *module, PyObject *args)
+os_waitpid(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -2905,10 +2904,10 @@ PyDoc_STRVAR(os_waitpid__doc__,
     {"waitpid", (PyCFunction)os_waitpid, METH_VARARGS, os_waitpid__doc__},
 
 static PyObject *
-os_waitpid_impl(PyModuleDef *module, Py_intptr_t pid, int options);
+os_waitpid_impl(PyObject *module, Py_intptr_t pid, int options);
 
 static PyObject *
-os_waitpid(PyModuleDef *module, PyObject *args)
+os_waitpid(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_intptr_t pid;
@@ -2940,10 +2939,10 @@ PyDoc_STRVAR(os_wait__doc__,
     {"wait", (PyCFunction)os_wait, METH_NOARGS, os_wait__doc__},
 
 static PyObject *
-os_wait_impl(PyModuleDef *module);
+os_wait_impl(PyObject *module);
 
 static PyObject *
-os_wait(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_wait(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_wait_impl(module);
 }
@@ -2972,11 +2971,11 @@ PyDoc_STRVAR(os_symlink__doc__,
     {"symlink", (PyCFunction)os_symlink, METH_VARARGS|METH_KEYWORDS, os_symlink__doc__},
 
 static PyObject *
-os_symlink_impl(PyModuleDef *module, path_t *src, path_t *dst,
+os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
                 int target_is_directory, int dir_fd);
 
 static PyObject *
-os_symlink(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_symlink(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"src", "dst", "target_is_directory", "dir_fd", NULL};
@@ -3017,10 +3016,10 @@ PyDoc_STRVAR(os_times__doc__,
     {"times", (PyCFunction)os_times, METH_NOARGS, os_times__doc__},
 
 static PyObject *
-os_times_impl(PyModuleDef *module);
+os_times_impl(PyObject *module);
 
 static PyObject *
-os_times(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_times(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_times_impl(module);
 }
@@ -3039,10 +3038,10 @@ PyDoc_STRVAR(os_getsid__doc__,
     {"getsid", (PyCFunction)os_getsid, METH_O, os_getsid__doc__},
 
 static PyObject *
-os_getsid_impl(PyModuleDef *module, pid_t pid);
+os_getsid_impl(PyObject *module, pid_t pid);
 
 static PyObject *
-os_getsid(PyModuleDef *module, PyObject *arg)
+os_getsid(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -3069,10 +3068,10 @@ PyDoc_STRVAR(os_setsid__doc__,
     {"setsid", (PyCFunction)os_setsid, METH_NOARGS, os_setsid__doc__},
 
 static PyObject *
-os_setsid_impl(PyModuleDef *module);
+os_setsid_impl(PyObject *module);
 
 static PyObject *
-os_setsid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_setsid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_setsid_impl(module);
 }
@@ -3091,10 +3090,10 @@ PyDoc_STRVAR(os_setpgid__doc__,
     {"setpgid", (PyCFunction)os_setpgid, METH_VARARGS, os_setpgid__doc__},
 
 static PyObject *
-os_setpgid_impl(PyModuleDef *module, pid_t pid, pid_t pgrp);
+os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp);
 
 static PyObject *
-os_setpgid(PyModuleDef *module, PyObject *args)
+os_setpgid(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     pid_t pid;
@@ -3123,10 +3122,10 @@ PyDoc_STRVAR(os_tcgetpgrp__doc__,
     {"tcgetpgrp", (PyCFunction)os_tcgetpgrp, METH_O, os_tcgetpgrp__doc__},
 
 static PyObject *
-os_tcgetpgrp_impl(PyModuleDef *module, int fd);
+os_tcgetpgrp_impl(PyObject *module, int fd);
 
 static PyObject *
-os_tcgetpgrp(PyModuleDef *module, PyObject *arg)
+os_tcgetpgrp(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3153,10 +3152,10 @@ PyDoc_STRVAR(os_tcsetpgrp__doc__,
     {"tcsetpgrp", (PyCFunction)os_tcsetpgrp, METH_VARARGS, os_tcsetpgrp__doc__},
 
 static PyObject *
-os_tcsetpgrp_impl(PyModuleDef *module, int fd, pid_t pgid);
+os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid);
 
 static PyObject *
-os_tcsetpgrp(PyModuleDef *module, PyObject *args)
+os_tcsetpgrp(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3188,11 +3187,10 @@ PyDoc_STRVAR(os_open__doc__,
     {"open", (PyCFunction)os_open, METH_VARARGS|METH_KEYWORDS, os_open__doc__},
 
 static int
-os_open_impl(PyModuleDef *module, path_t *path, int flags, int mode,
-             int dir_fd);
+os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd);
 
 static PyObject *
-os_open(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_open(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "flags", "mode", "dir_fd", NULL};
@@ -3227,10 +3225,10 @@ PyDoc_STRVAR(os_close__doc__,
     {"close", (PyCFunction)os_close, METH_VARARGS|METH_KEYWORDS, os_close__doc__},
 
 static PyObject *
-os_close_impl(PyModuleDef *module, int fd);
+os_close_impl(PyObject *module, int fd);
 
 static PyObject *
-os_close(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_close(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"fd", NULL};
@@ -3255,10 +3253,10 @@ PyDoc_STRVAR(os_closerange__doc__,
     {"closerange", (PyCFunction)os_closerange, METH_VARARGS, os_closerange__doc__},
 
 static PyObject *
-os_closerange_impl(PyModuleDef *module, int fd_low, int fd_high);
+os_closerange_impl(PyObject *module, int fd_low, int fd_high);
 
 static PyObject *
-os_closerange(PyModuleDef *module, PyObject *args)
+os_closerange(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd_low;
@@ -3283,10 +3281,10 @@ PyDoc_STRVAR(os_dup__doc__,
     {"dup", (PyCFunction)os_dup, METH_O, os_dup__doc__},
 
 static int
-os_dup_impl(PyModuleDef *module, int fd);
+os_dup_impl(PyObject *module, int fd);
 
 static PyObject *
-os_dup(PyModuleDef *module, PyObject *arg)
+os_dup(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3313,10 +3311,10 @@ PyDoc_STRVAR(os_dup2__doc__,
     {"dup2", (PyCFunction)os_dup2, METH_VARARGS|METH_KEYWORDS, os_dup2__doc__},
 
 static PyObject *
-os_dup2_impl(PyModuleDef *module, int fd, int fd2, int inheritable);
+os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable);
 
 static PyObject *
-os_dup2(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_dup2(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"fd", "fd2", "inheritable", NULL};
@@ -3352,10 +3350,10 @@ PyDoc_STRVAR(os_lockf__doc__,
     {"lockf", (PyCFunction)os_lockf, METH_VARARGS, os_lockf__doc__},
 
 static PyObject *
-os_lockf_impl(PyModuleDef *module, int fd, int command, Py_off_t length);
+os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length);
 
 static PyObject *
-os_lockf(PyModuleDef *module, PyObject *args)
+os_lockf(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3386,10 +3384,10 @@ PyDoc_STRVAR(os_lseek__doc__,
     {"lseek", (PyCFunction)os_lseek, METH_VARARGS, os_lseek__doc__},
 
 static Py_off_t
-os_lseek_impl(PyModuleDef *module, int fd, Py_off_t position, int how);
+os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how);
 
 static PyObject *
-os_lseek(PyModuleDef *module, PyObject *args)
+os_lseek(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3419,10 +3417,10 @@ PyDoc_STRVAR(os_read__doc__,
     {"read", (PyCFunction)os_read, METH_VARARGS, os_read__doc__},
 
 static PyObject *
-os_read_impl(PyModuleDef *module, int fd, Py_ssize_t length);
+os_read_impl(PyObject *module, int fd, Py_ssize_t length);
 
 static PyObject *
-os_read(PyModuleDef *module, PyObject *args)
+os_read(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3457,10 +3455,10 @@ PyDoc_STRVAR(os_readv__doc__,
     {"readv", (PyCFunction)os_readv, METH_VARARGS, os_readv__doc__},
 
 static Py_ssize_t
-os_readv_impl(PyModuleDef *module, int fd, PyObject *buffers);
+os_readv_impl(PyObject *module, int fd, PyObject *buffers);
 
 static PyObject *
-os_readv(PyModuleDef *module, PyObject *args)
+os_readv(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3496,10 +3494,10 @@ PyDoc_STRVAR(os_pread__doc__,
     {"pread", (PyCFunction)os_pread, METH_VARARGS, os_pread__doc__},
 
 static PyObject *
-os_pread_impl(PyModuleDef *module, int fd, int length, Py_off_t offset);
+os_pread_impl(PyObject *module, int fd, int length, Py_off_t offset);
 
 static PyObject *
-os_pread(PyModuleDef *module, PyObject *args)
+os_pread(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3527,10 +3525,10 @@ PyDoc_STRVAR(os_write__doc__,
     {"write", (PyCFunction)os_write, METH_VARARGS, os_write__doc__},
 
 static Py_ssize_t
-os_write_impl(PyModuleDef *module, int fd, Py_buffer *data);
+os_write_impl(PyObject *module, int fd, Py_buffer *data);
 
 static PyObject *
-os_write(PyModuleDef *module, PyObject *args)
+os_write(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3566,10 +3564,10 @@ PyDoc_STRVAR(os_fstat__doc__,
     {"fstat", (PyCFunction)os_fstat, METH_VARARGS|METH_KEYWORDS, os_fstat__doc__},
 
 static PyObject *
-os_fstat_impl(PyModuleDef *module, int fd);
+os_fstat_impl(PyObject *module, int fd);
 
 static PyObject *
-os_fstat(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_fstat(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"fd", NULL};
@@ -3597,10 +3595,10 @@ PyDoc_STRVAR(os_isatty__doc__,
     {"isatty", (PyCFunction)os_isatty, METH_O, os_isatty__doc__},
 
 static int
-os_isatty_impl(PyModuleDef *module, int fd);
+os_isatty_impl(PyObject *module, int fd);
 
 static PyObject *
-os_isatty(PyModuleDef *module, PyObject *arg)
+os_isatty(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3632,10 +3630,10 @@ PyDoc_STRVAR(os_pipe__doc__,
     {"pipe", (PyCFunction)os_pipe, METH_NOARGS, os_pipe__doc__},
 
 static PyObject *
-os_pipe_impl(PyModuleDef *module);
+os_pipe_impl(PyObject *module);
 
 static PyObject *
-os_pipe(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_pipe(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_pipe_impl(module);
 }
@@ -3660,10 +3658,10 @@ PyDoc_STRVAR(os_pipe2__doc__,
     {"pipe2", (PyCFunction)os_pipe2, METH_O, os_pipe2__doc__},
 
 static PyObject *
-os_pipe2_impl(PyModuleDef *module, int flags);
+os_pipe2_impl(PyObject *module, int flags);
 
 static PyObject *
-os_pipe2(PyModuleDef *module, PyObject *arg)
+os_pipe2(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int flags;
@@ -3693,10 +3691,10 @@ PyDoc_STRVAR(os_writev__doc__,
     {"writev", (PyCFunction)os_writev, METH_VARARGS, os_writev__doc__},
 
 static Py_ssize_t
-os_writev_impl(PyModuleDef *module, int fd, PyObject *buffers);
+os_writev_impl(PyObject *module, int fd, PyObject *buffers);
 
 static PyObject *
-os_writev(PyModuleDef *module, PyObject *args)
+os_writev(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3733,11 +3731,10 @@ PyDoc_STRVAR(os_pwrite__doc__,
     {"pwrite", (PyCFunction)os_pwrite, METH_VARARGS, os_pwrite__doc__},
 
 static Py_ssize_t
-os_pwrite_impl(PyModuleDef *module, int fd, Py_buffer *buffer,
-               Py_off_t offset);
+os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset);
 
 static PyObject *
-os_pwrite(PyModuleDef *module, PyObject *args)
+os_pwrite(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -3780,10 +3777,10 @@ PyDoc_STRVAR(os_mkfifo__doc__,
     {"mkfifo", (PyCFunction)os_mkfifo, METH_VARARGS|METH_KEYWORDS, os_mkfifo__doc__},
 
 static PyObject *
-os_mkfifo_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd);
+os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd);
 
 static PyObject *
-os_mkfifo(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_mkfifo(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "mode", "dir_fd", NULL};
@@ -3829,11 +3826,11 @@ PyDoc_STRVAR(os_mknod__doc__,
     {"mknod", (PyCFunction)os_mknod, METH_VARARGS|METH_KEYWORDS, os_mknod__doc__},
 
 static PyObject *
-os_mknod_impl(PyModuleDef *module, path_t *path, int mode, dev_t device,
+os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
               int dir_fd);
 
 static PyObject *
-os_mknod(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_mknod(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "mode", "device", "dir_fd", NULL};
@@ -3868,10 +3865,10 @@ PyDoc_STRVAR(os_major__doc__,
     {"major", (PyCFunction)os_major, METH_O, os_major__doc__},
 
 static unsigned int
-os_major_impl(PyModuleDef *module, dev_t device);
+os_major_impl(PyObject *module, dev_t device);
 
 static PyObject *
-os_major(PyModuleDef *module, PyObject *arg)
+os_major(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     dev_t device;
@@ -3902,10 +3899,10 @@ PyDoc_STRVAR(os_minor__doc__,
     {"minor", (PyCFunction)os_minor, METH_O, os_minor__doc__},
 
 static unsigned int
-os_minor_impl(PyModuleDef *module, dev_t device);
+os_minor_impl(PyObject *module, dev_t device);
 
 static PyObject *
-os_minor(PyModuleDef *module, PyObject *arg)
+os_minor(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     dev_t device;
@@ -3936,10 +3933,10 @@ PyDoc_STRVAR(os_makedev__doc__,
     {"makedev", (PyCFunction)os_makedev, METH_VARARGS, os_makedev__doc__},
 
 static dev_t
-os_makedev_impl(PyModuleDef *module, int major, int minor);
+os_makedev_impl(PyObject *module, int major, int minor);
 
 static PyObject *
-os_makedev(PyModuleDef *module, PyObject *args)
+os_makedev(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int major;
@@ -3972,10 +3969,10 @@ PyDoc_STRVAR(os_ftruncate__doc__,
     {"ftruncate", (PyCFunction)os_ftruncate, METH_VARARGS, os_ftruncate__doc__},
 
 static PyObject *
-os_ftruncate_impl(PyModuleDef *module, int fd, Py_off_t length);
+os_ftruncate_impl(PyObject *module, int fd, Py_off_t length);
 
 static PyObject *
-os_ftruncate(PyModuleDef *module, PyObject *args)
+os_ftruncate(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -4007,10 +4004,10 @@ PyDoc_STRVAR(os_truncate__doc__,
     {"truncate", (PyCFunction)os_truncate, METH_VARARGS|METH_KEYWORDS, os_truncate__doc__},
 
 static PyObject *
-os_truncate_impl(PyModuleDef *module, path_t *path, Py_off_t length);
+os_truncate_impl(PyObject *module, path_t *path, Py_off_t length);
 
 static PyObject *
-os_truncate(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_truncate(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "length", NULL};
@@ -4046,11 +4043,11 @@ PyDoc_STRVAR(os_posix_fallocate__doc__,
     {"posix_fallocate", (PyCFunction)os_posix_fallocate, METH_VARARGS, os_posix_fallocate__doc__},
 
 static PyObject *
-os_posix_fallocate_impl(PyModuleDef *module, int fd, Py_off_t offset,
+os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
                         Py_off_t length);
 
 static PyObject *
-os_posix_fallocate(PyModuleDef *module, PyObject *args)
+os_posix_fallocate(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -4088,11 +4085,11 @@ PyDoc_STRVAR(os_posix_fadvise__doc__,
     {"posix_fadvise", (PyCFunction)os_posix_fadvise, METH_VARARGS, os_posix_fadvise__doc__},
 
 static PyObject *
-os_posix_fadvise_impl(PyModuleDef *module, int fd, Py_off_t offset,
+os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
                       Py_off_t length, int advice);
 
 static PyObject *
-os_posix_fadvise(PyModuleDef *module, PyObject *args)
+os_posix_fadvise(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -4123,10 +4120,10 @@ PyDoc_STRVAR(os_putenv__doc__,
     {"putenv", (PyCFunction)os_putenv, METH_VARARGS, os_putenv__doc__},
 
 static PyObject *
-os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value);
+os_putenv_impl(PyObject *module, PyObject *name, PyObject *value);
 
 static PyObject *
-os_putenv(PyModuleDef *module, PyObject *args)
+os_putenv(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *name;
@@ -4155,10 +4152,10 @@ PyDoc_STRVAR(os_putenv__doc__,
     {"putenv", (PyCFunction)os_putenv, METH_VARARGS, os_putenv__doc__},
 
 static PyObject *
-os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value);
+os_putenv_impl(PyObject *module, PyObject *name, PyObject *value);
 
 static PyObject *
-os_putenv(PyModuleDef *module, PyObject *args)
+os_putenv(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *name = NULL;
@@ -4192,10 +4189,10 @@ PyDoc_STRVAR(os_unsetenv__doc__,
     {"unsetenv", (PyCFunction)os_unsetenv, METH_O, os_unsetenv__doc__},
 
 static PyObject *
-os_unsetenv_impl(PyModuleDef *module, PyObject *name);
+os_unsetenv_impl(PyObject *module, PyObject *name);
 
 static PyObject *
-os_unsetenv(PyModuleDef *module, PyObject *arg)
+os_unsetenv(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *name = NULL;
@@ -4223,10 +4220,10 @@ PyDoc_STRVAR(os_strerror__doc__,
     {"strerror", (PyCFunction)os_strerror, METH_O, os_strerror__doc__},
 
 static PyObject *
-os_strerror_impl(PyModuleDef *module, int code);
+os_strerror_impl(PyObject *module, int code);
 
 static PyObject *
-os_strerror(PyModuleDef *module, PyObject *arg)
+os_strerror(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int code;
@@ -4251,10 +4248,10 @@ PyDoc_STRVAR(os_WCOREDUMP__doc__,
     {"WCOREDUMP", (PyCFunction)os_WCOREDUMP, METH_O, os_WCOREDUMP__doc__},
 
 static int
-os_WCOREDUMP_impl(PyModuleDef *module, int status);
+os_WCOREDUMP_impl(PyObject *module, int status);
 
 static PyObject *
-os_WCOREDUMP(PyModuleDef *module, PyObject *arg)
+os_WCOREDUMP(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int status;
@@ -4288,10 +4285,10 @@ PyDoc_STRVAR(os_WIFCONTINUED__doc__,
     {"WIFCONTINUED", (PyCFunction)os_WIFCONTINUED, METH_VARARGS|METH_KEYWORDS, os_WIFCONTINUED__doc__},
 
 static int
-os_WIFCONTINUED_impl(PyModuleDef *module, int status);
+os_WIFCONTINUED_impl(PyObject *module, int status);
 
 static PyObject *
-os_WIFCONTINUED(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_WIFCONTINUED(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"status", NULL};
@@ -4324,10 +4321,10 @@ PyDoc_STRVAR(os_WIFSTOPPED__doc__,
     {"WIFSTOPPED", (PyCFunction)os_WIFSTOPPED, METH_VARARGS|METH_KEYWORDS, os_WIFSTOPPED__doc__},
 
 static int
-os_WIFSTOPPED_impl(PyModuleDef *module, int status);
+os_WIFSTOPPED_impl(PyObject *module, int status);
 
 static PyObject *
-os_WIFSTOPPED(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_WIFSTOPPED(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"status", NULL};
@@ -4360,10 +4357,10 @@ PyDoc_STRVAR(os_WIFSIGNALED__doc__,
     {"WIFSIGNALED", (PyCFunction)os_WIFSIGNALED, METH_VARARGS|METH_KEYWORDS, os_WIFSIGNALED__doc__},
 
 static int
-os_WIFSIGNALED_impl(PyModuleDef *module, int status);
+os_WIFSIGNALED_impl(PyObject *module, int status);
 
 static PyObject *
-os_WIFSIGNALED(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_WIFSIGNALED(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"status", NULL};
@@ -4396,10 +4393,10 @@ PyDoc_STRVAR(os_WIFEXITED__doc__,
     {"WIFEXITED", (PyCFunction)os_WIFEXITED, METH_VARARGS|METH_KEYWORDS, os_WIFEXITED__doc__},
 
 static int
-os_WIFEXITED_impl(PyModuleDef *module, int status);
+os_WIFEXITED_impl(PyObject *module, int status);
 
 static PyObject *
-os_WIFEXITED(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_WIFEXITED(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"status", NULL};
@@ -4432,10 +4429,10 @@ PyDoc_STRVAR(os_WEXITSTATUS__doc__,
     {"WEXITSTATUS", (PyCFunction)os_WEXITSTATUS, METH_VARARGS|METH_KEYWORDS, os_WEXITSTATUS__doc__},
 
 static int
-os_WEXITSTATUS_impl(PyModuleDef *module, int status);
+os_WEXITSTATUS_impl(PyObject *module, int status);
 
 static PyObject *
-os_WEXITSTATUS(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_WEXITSTATUS(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"status", NULL};
@@ -4468,10 +4465,10 @@ PyDoc_STRVAR(os_WTERMSIG__doc__,
     {"WTERMSIG", (PyCFunction)os_WTERMSIG, METH_VARARGS|METH_KEYWORDS, os_WTERMSIG__doc__},
 
 static int
-os_WTERMSIG_impl(PyModuleDef *module, int status);
+os_WTERMSIG_impl(PyObject *module, int status);
 
 static PyObject *
-os_WTERMSIG(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_WTERMSIG(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"status", NULL};
@@ -4504,10 +4501,10 @@ PyDoc_STRVAR(os_WSTOPSIG__doc__,
     {"WSTOPSIG", (PyCFunction)os_WSTOPSIG, METH_VARARGS|METH_KEYWORDS, os_WSTOPSIG__doc__},
 
 static int
-os_WSTOPSIG_impl(PyModuleDef *module, int status);
+os_WSTOPSIG_impl(PyObject *module, int status);
 
 static PyObject *
-os_WSTOPSIG(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_WSTOPSIG(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"status", NULL};
@@ -4542,10 +4539,10 @@ PyDoc_STRVAR(os_fstatvfs__doc__,
     {"fstatvfs", (PyCFunction)os_fstatvfs, METH_O, os_fstatvfs__doc__},
 
 static PyObject *
-os_fstatvfs_impl(PyModuleDef *module, int fd);
+os_fstatvfs_impl(PyObject *module, int fd);
 
 static PyObject *
-os_fstatvfs(PyModuleDef *module, PyObject *arg)
+os_fstatvfs(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -4576,10 +4573,10 @@ PyDoc_STRVAR(os_statvfs__doc__,
     {"statvfs", (PyCFunction)os_statvfs, METH_VARARGS|METH_KEYWORDS, os_statvfs__doc__},
 
 static PyObject *
-os_statvfs_impl(PyModuleDef *module, path_t *path);
+os_statvfs_impl(PyObject *module, path_t *path);
 
 static PyObject *
-os_statvfs(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_statvfs(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", NULL};
@@ -4611,10 +4608,10 @@ PyDoc_STRVAR(os__getdiskusage__doc__,
     {"_getdiskusage", (PyCFunction)os__getdiskusage, METH_VARARGS|METH_KEYWORDS, os__getdiskusage__doc__},
 
 static PyObject *
-os__getdiskusage_impl(PyModuleDef *module, Py_UNICODE *path);
+os__getdiskusage_impl(PyObject *module, Py_UNICODE *path);
 
 static PyObject *
-os__getdiskusage(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os__getdiskusage(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", NULL};
@@ -4645,10 +4642,10 @@ PyDoc_STRVAR(os_fpathconf__doc__,
     {"fpathconf", (PyCFunction)os_fpathconf, METH_VARARGS, os_fpathconf__doc__},
 
 static long
-os_fpathconf_impl(PyModuleDef *module, int fd, int name);
+os_fpathconf_impl(PyObject *module, int fd, int name);
 
 static PyObject *
-os_fpathconf(PyModuleDef *module, PyObject *args)
+os_fpathconf(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -4685,10 +4682,10 @@ PyDoc_STRVAR(os_pathconf__doc__,
     {"pathconf", (PyCFunction)os_pathconf, METH_VARARGS|METH_KEYWORDS, os_pathconf__doc__},
 
 static long
-os_pathconf_impl(PyModuleDef *module, path_t *path, int name);
+os_pathconf_impl(PyObject *module, path_t *path, int name);
 
 static PyObject *
-os_pathconf(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_pathconf(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "name", NULL};
@@ -4725,10 +4722,10 @@ PyDoc_STRVAR(os_confstr__doc__,
     {"confstr", (PyCFunction)os_confstr, METH_O, os_confstr__doc__},
 
 static PyObject *
-os_confstr_impl(PyModuleDef *module, int name);
+os_confstr_impl(PyObject *module, int name);
 
 static PyObject *
-os_confstr(PyModuleDef *module, PyObject *arg)
+os_confstr(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int name;
@@ -4755,10 +4752,10 @@ PyDoc_STRVAR(os_sysconf__doc__,
     {"sysconf", (PyCFunction)os_sysconf, METH_O, os_sysconf__doc__},
 
 static long
-os_sysconf_impl(PyModuleDef *module, int name);
+os_sysconf_impl(PyObject *module, int name);
 
 static PyObject *
-os_sysconf(PyModuleDef *module, PyObject *arg)
+os_sysconf(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int name;
@@ -4790,10 +4787,10 @@ PyDoc_STRVAR(os_abort__doc__,
     {"abort", (PyCFunction)os_abort, METH_NOARGS, os_abort__doc__},
 
 static PyObject *
-os_abort_impl(PyModuleDef *module);
+os_abort_impl(PyObject *module);
 
 static PyObject *
-os_abort(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_abort(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_abort_impl(module);
 }
@@ -4814,10 +4811,10 @@ PyDoc_STRVAR(os_getloadavg__doc__,
     {"getloadavg", (PyCFunction)os_getloadavg, METH_NOARGS, os_getloadavg__doc__},
 
 static PyObject *
-os_getloadavg_impl(PyModuleDef *module);
+os_getloadavg_impl(PyObject *module);
 
 static PyObject *
-os_getloadavg(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getloadavg(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getloadavg_impl(module);
 }
@@ -4837,10 +4834,10 @@ PyDoc_STRVAR(os_device_encoding__doc__,
     {"device_encoding", (PyCFunction)os_device_encoding, METH_VARARGS|METH_KEYWORDS, os_device_encoding__doc__},
 
 static PyObject *
-os_device_encoding_impl(PyModuleDef *module, int fd);
+os_device_encoding_impl(PyObject *module, int fd);
 
 static PyObject *
-os_device_encoding(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_device_encoding(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"fd", NULL};
@@ -4867,10 +4864,10 @@ PyDoc_STRVAR(os_setresuid__doc__,
     {"setresuid", (PyCFunction)os_setresuid, METH_VARARGS, os_setresuid__doc__},
 
 static PyObject *
-os_setresuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid, uid_t suid);
+os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid);
 
 static PyObject *
-os_setresuid(PyModuleDef *module, PyObject *args)
+os_setresuid(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     uid_t ruid;
@@ -4900,10 +4897,10 @@ PyDoc_STRVAR(os_setresgid__doc__,
     {"setresgid", (PyCFunction)os_setresgid, METH_VARARGS, os_setresgid__doc__},
 
 static PyObject *
-os_setresgid_impl(PyModuleDef *module, gid_t rgid, gid_t egid, gid_t sgid);
+os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid);
 
 static PyObject *
-os_setresgid(PyModuleDef *module, PyObject *args)
+os_setresgid(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     gid_t rgid;
@@ -4933,10 +4930,10 @@ PyDoc_STRVAR(os_getresuid__doc__,
     {"getresuid", (PyCFunction)os_getresuid, METH_NOARGS, os_getresuid__doc__},
 
 static PyObject *
-os_getresuid_impl(PyModuleDef *module);
+os_getresuid_impl(PyObject *module);
 
 static PyObject *
-os_getresuid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getresuid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getresuid_impl(module);
 }
@@ -4955,10 +4952,10 @@ PyDoc_STRVAR(os_getresgid__doc__,
     {"getresgid", (PyCFunction)os_getresgid, METH_NOARGS, os_getresgid__doc__},
 
 static PyObject *
-os_getresgid_impl(PyModuleDef *module);
+os_getresgid_impl(PyObject *module);
 
 static PyObject *
-os_getresgid(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_getresgid(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_getresgid_impl(module);
 }
@@ -4982,11 +4979,11 @@ PyDoc_STRVAR(os_getxattr__doc__,
     {"getxattr", (PyCFunction)os_getxattr, METH_VARARGS|METH_KEYWORDS, os_getxattr__doc__},
 
 static PyObject *
-os_getxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute,
+os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
                  int follow_symlinks);
 
 static PyObject *
-os_getxattr(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_getxattr(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "attribute", "follow_symlinks", NULL};
@@ -5028,11 +5025,11 @@ PyDoc_STRVAR(os_setxattr__doc__,
     {"setxattr", (PyCFunction)os_setxattr, METH_VARARGS|METH_KEYWORDS, os_setxattr__doc__},
 
 static PyObject *
-os_setxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute,
+os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
                  Py_buffer *value, int flags, int follow_symlinks);
 
 static PyObject *
-os_setxattr(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_setxattr(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "attribute", "value", "flags", "follow_symlinks", NULL};
@@ -5078,11 +5075,11 @@ PyDoc_STRVAR(os_removexattr__doc__,
     {"removexattr", (PyCFunction)os_removexattr, METH_VARARGS|METH_KEYWORDS, os_removexattr__doc__},
 
 static PyObject *
-os_removexattr_impl(PyModuleDef *module, path_t *path, path_t *attribute,
+os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
                     int follow_symlinks);
 
 static PyObject *
-os_removexattr(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_removexattr(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "attribute", "follow_symlinks", NULL};
@@ -5124,10 +5121,10 @@ PyDoc_STRVAR(os_listxattr__doc__,
     {"listxattr", (PyCFunction)os_listxattr, METH_VARARGS|METH_KEYWORDS, os_listxattr__doc__},
 
 static PyObject *
-os_listxattr_impl(PyModuleDef *module, path_t *path, int follow_symlinks);
+os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks);
 
 static PyObject *
-os_listxattr(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+os_listxattr(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"path", "follow_symlinks", NULL};
@@ -5158,10 +5155,10 @@ PyDoc_STRVAR(os_urandom__doc__,
     {"urandom", (PyCFunction)os_urandom, METH_O, os_urandom__doc__},
 
 static PyObject *
-os_urandom_impl(PyModuleDef *module, Py_ssize_t size);
+os_urandom_impl(PyObject *module, Py_ssize_t size);
 
 static PyObject *
-os_urandom(PyModuleDef *module, PyObject *arg)
+os_urandom(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_ssize_t size;
@@ -5184,10 +5181,10 @@ PyDoc_STRVAR(os_cpu_count__doc__,
     {"cpu_count", (PyCFunction)os_cpu_count, METH_NOARGS, os_cpu_count__doc__},
 
 static PyObject *
-os_cpu_count_impl(PyModuleDef *module);
+os_cpu_count_impl(PyObject *module);
 
 static PyObject *
-os_cpu_count(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+os_cpu_count(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return os_cpu_count_impl(module);
 }
@@ -5202,10 +5199,10 @@ PyDoc_STRVAR(os_get_inheritable__doc__,
     {"get_inheritable", (PyCFunction)os_get_inheritable, METH_O, os_get_inheritable__doc__},
 
 static int
-os_get_inheritable_impl(PyModuleDef *module, int fd);
+os_get_inheritable_impl(PyObject *module, int fd);
 
 static PyObject *
-os_get_inheritable(PyModuleDef *module, PyObject *arg)
+os_get_inheritable(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -5232,10 +5229,10 @@ PyDoc_STRVAR(os_set_inheritable__doc__,
     {"set_inheritable", (PyCFunction)os_set_inheritable, METH_VARARGS, os_set_inheritable__doc__},
 
 static PyObject *
-os_set_inheritable_impl(PyModuleDef *module, int fd, int inheritable);
+os_set_inheritable_impl(PyObject *module, int fd, int inheritable);
 
 static PyObject *
-os_set_inheritable(PyModuleDef *module, PyObject *args)
+os_set_inheritable(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -5262,10 +5259,10 @@ PyDoc_STRVAR(os_get_handle_inheritable__doc__,
     {"get_handle_inheritable", (PyCFunction)os_get_handle_inheritable, METH_O, os_get_handle_inheritable__doc__},
 
 static int
-os_get_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle);
+os_get_handle_inheritable_impl(PyObject *module, Py_intptr_t handle);
 
 static PyObject *
-os_get_handle_inheritable(PyModuleDef *module, PyObject *arg)
+os_get_handle_inheritable(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_intptr_t handle;
@@ -5296,11 +5293,11 @@ PyDoc_STRVAR(os_set_handle_inheritable__doc__,
     {"set_handle_inheritable", (PyCFunction)os_set_handle_inheritable, METH_VARARGS, os_set_handle_inheritable__doc__},
 
 static PyObject *
-os_set_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle,
+os_set_handle_inheritable_impl(PyObject *module, Py_intptr_t handle,
                                int inheritable);
 
 static PyObject *
-os_set_handle_inheritable(PyModuleDef *module, PyObject *args)
+os_set_handle_inheritable(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_intptr_t handle;
@@ -5788,4 +5785,4 @@ exit:
 #ifndef OS_SET_HANDLE_INHERITABLE_METHODDEF
     #define OS_SET_HANDLE_INHERITABLE_METHODDEF
 #endif /* !defined(OS_SET_HANDLE_INHERITABLE_METHODDEF) */
-/*[clinic end generated code: output=95824c52fd034654 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=7690b72549d2524e input=a9049054013a1b77]*/
index 9de2e4f..cb191a0 100644 (file)
@@ -25,10 +25,10 @@ PyDoc_STRVAR(pwd_getpwnam__doc__,
     {"getpwnam", (PyCFunction)pwd_getpwnam, METH_O, pwd_getpwnam__doc__},
 
 static PyObject *
-pwd_getpwnam_impl(PyModuleDef *module, PyObject *arg);
+pwd_getpwnam_impl(PyObject *module, PyObject *arg);
 
 static PyObject *
-pwd_getpwnam(PyModuleDef *module, PyObject *arg_)
+pwd_getpwnam(PyObject *module, PyObject *arg_)
 {
     PyObject *return_value = NULL;
     PyObject *arg;
@@ -55,10 +55,10 @@ PyDoc_STRVAR(pwd_getpwall__doc__,
     {"getpwall", (PyCFunction)pwd_getpwall, METH_NOARGS, pwd_getpwall__doc__},
 
 static PyObject *
-pwd_getpwall_impl(PyModuleDef *module);
+pwd_getpwall_impl(PyObject *module);
 
 static PyObject *
-pwd_getpwall(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+pwd_getpwall(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return pwd_getpwall_impl(module);
 }
@@ -68,4 +68,4 @@ pwd_getpwall(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
 #ifndef PWD_GETPWALL_METHODDEF
     #define PWD_GETPWALL_METHODDEF
 #endif /* !defined(PWD_GETPWALL_METHODDEF) */
-/*[clinic end generated code: output=2ed0ecf34fd3f98f input=a9049054013a1b77]*/
+/*[clinic end generated code: output=d0ea1c5c832f0c1a input=a9049054013a1b77]*/
index 379c5db..c5b5c71 100644 (file)
@@ -231,11 +231,11 @@ PyDoc_STRVAR(pyexpat_ParserCreate__doc__,
     {"ParserCreate", (PyCFunction)pyexpat_ParserCreate, METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__},
 
 static PyObject *
-pyexpat_ParserCreate_impl(PyModuleDef *module, const char *encoding,
+pyexpat_ParserCreate_impl(PyObject *module, const char *encoding,
                           const char *namespace_separator, PyObject *intern);
 
 static PyObject *
-pyexpat_ParserCreate(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+pyexpat_ParserCreate(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"encoding", "namespace_separator", "intern", NULL};
@@ -262,10 +262,10 @@ PyDoc_STRVAR(pyexpat_ErrorString__doc__,
     {"ErrorString", (PyCFunction)pyexpat_ErrorString, METH_O, pyexpat_ErrorString__doc__},
 
 static PyObject *
-pyexpat_ErrorString_impl(PyModuleDef *module, long code);
+pyexpat_ErrorString_impl(PyObject *module, long code);
 
 static PyObject *
-pyexpat_ErrorString(PyModuleDef *module, PyObject *arg)
+pyexpat_ErrorString(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     long code;
@@ -281,4 +281,4 @@ exit:
 #ifndef PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
     #define PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
 #endif /* !defined(PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF) */
-/*[clinic end generated code: output=bf4d99c9702d8a6c input=a9049054013a1b77]*/
+/*[clinic end generated code: output=d479cfab607e9dc8 input=a9049054013a1b77]*/
index fa865ba..5b8db80 100644 (file)
@@ -75,10 +75,10 @@ PyDoc_STRVAR(_sha1_sha1__doc__,
     {"sha1", (PyCFunction)_sha1_sha1, METH_VARARGS|METH_KEYWORDS, _sha1_sha1__doc__},
 
 static PyObject *
-_sha1_sha1_impl(PyModuleDef *module, PyObject *string);
+_sha1_sha1_impl(PyObject *module, PyObject *string);
 
 static PyObject *
-_sha1_sha1(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_sha1_sha1(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"string", NULL};
@@ -92,4 +92,4 @@ _sha1_sha1(PyModuleDef *module, PyObject *args, PyObject *kwargs)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=be19102f3120490a input=a9049054013a1b77]*/
+/*[clinic end generated code: output=0b6a194fbb0b94f2 input=a9049054013a1b77]*/
index c5fe188..661569c 100644 (file)
@@ -75,10 +75,10 @@ PyDoc_STRVAR(_sha256_sha256__doc__,
     {"sha256", (PyCFunction)_sha256_sha256, METH_VARARGS|METH_KEYWORDS, _sha256_sha256__doc__},
 
 static PyObject *
-_sha256_sha256_impl(PyModuleDef *module, PyObject *string);
+_sha256_sha256_impl(PyObject *module, PyObject *string);
 
 static PyObject *
-_sha256_sha256(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_sha256_sha256(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"string", NULL};
@@ -103,10 +103,10 @@ PyDoc_STRVAR(_sha256_sha224__doc__,
     {"sha224", (PyCFunction)_sha256_sha224, METH_VARARGS|METH_KEYWORDS, _sha256_sha224__doc__},
 
 static PyObject *
-_sha256_sha224_impl(PyModuleDef *module, PyObject *string);
+_sha256_sha224_impl(PyObject *module, PyObject *string);
 
 static PyObject *
-_sha256_sha224(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_sha256_sha224(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"string", NULL};
@@ -120,4 +120,4 @@ _sha256_sha224(PyModuleDef *module, PyObject *args, PyObject *kwargs)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=354cedf3b632c7b2 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=5a1fc5480e399f95 input=a9049054013a1b77]*/
index c308739..d64c2a4 100644 (file)
@@ -93,10 +93,10 @@ PyDoc_STRVAR(_sha512_sha512__doc__,
     {"sha512", (PyCFunction)_sha512_sha512, METH_VARARGS|METH_KEYWORDS, _sha512_sha512__doc__},
 
 static PyObject *
-_sha512_sha512_impl(PyModuleDef *module, PyObject *string);
+_sha512_sha512_impl(PyObject *module, PyObject *string);
 
 static PyObject *
-_sha512_sha512(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_sha512_sha512(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"string", NULL};
@@ -125,10 +125,10 @@ PyDoc_STRVAR(_sha512_sha384__doc__,
     {"sha384", (PyCFunction)_sha512_sha384, METH_VARARGS|METH_KEYWORDS, _sha512_sha384__doc__},
 
 static PyObject *
-_sha512_sha384_impl(PyModuleDef *module, PyObject *string);
+_sha512_sha384_impl(PyObject *module, PyObject *string);
 
 static PyObject *
-_sha512_sha384(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+_sha512_sha384(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"string", NULL};
@@ -168,4 +168,4 @@ exit:
 #ifndef _SHA512_SHA384_METHODDEF
     #define _SHA512_SHA384_METHODDEF
 #endif /* !defined(_SHA512_SHA384_METHODDEF) */
-/*[clinic end generated code: output=1c7d385731fee7c0 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=bb87f494df50ffc0 input=a9049054013a1b77]*/
index ec07ef1..c8f4cd5 100644 (file)
@@ -14,10 +14,10 @@ PyDoc_STRVAR(signal_alarm__doc__,
     {"alarm", (PyCFunction)signal_alarm, METH_O, signal_alarm__doc__},
 
 static long
-signal_alarm_impl(PyModuleDef *module, int seconds);
+signal_alarm_impl(PyObject *module, int seconds);
 
 static PyObject *
-signal_alarm(PyModuleDef *module, PyObject *arg)
+signal_alarm(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int seconds;
@@ -48,10 +48,10 @@ PyDoc_STRVAR(signal_pause__doc__,
     {"pause", (PyCFunction)signal_pause, METH_NOARGS, signal_pause__doc__},
 
 static PyObject *
-signal_pause_impl(PyModuleDef *module);
+signal_pause_impl(PyObject *module);
 
 static PyObject *
-signal_pause(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+signal_pause(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return signal_pause_impl(module);
 }
@@ -75,10 +75,10 @@ PyDoc_STRVAR(signal_signal__doc__,
     {"signal", (PyCFunction)signal_signal, METH_VARARGS, signal_signal__doc__},
 
 static PyObject *
-signal_signal_impl(PyModuleDef *module, int signalnum, PyObject *handler);
+signal_signal_impl(PyObject *module, int signalnum, PyObject *handler);
 
 static PyObject *
-signal_signal(PyModuleDef *module, PyObject *args)
+signal_signal(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int signalnum;
@@ -109,10 +109,10 @@ PyDoc_STRVAR(signal_getsignal__doc__,
     {"getsignal", (PyCFunction)signal_getsignal, METH_O, signal_getsignal__doc__},
 
 static PyObject *
-signal_getsignal_impl(PyModuleDef *module, int signalnum);
+signal_getsignal_impl(PyObject *module, int signalnum);
 
 static PyObject *
-signal_getsignal(PyModuleDef *module, PyObject *arg)
+signal_getsignal(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int signalnum;
@@ -140,10 +140,10 @@ PyDoc_STRVAR(signal_siginterrupt__doc__,
     {"siginterrupt", (PyCFunction)signal_siginterrupt, METH_VARARGS, signal_siginterrupt__doc__},
 
 static PyObject *
-signal_siginterrupt_impl(PyModuleDef *module, int signalnum, int flag);
+signal_siginterrupt_impl(PyObject *module, int signalnum, int flag);
 
 static PyObject *
-signal_siginterrupt(PyModuleDef *module, PyObject *args)
+signal_siginterrupt(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int signalnum;
@@ -177,11 +177,11 @@ PyDoc_STRVAR(signal_setitimer__doc__,
     {"setitimer", (PyCFunction)signal_setitimer, METH_VARARGS, signal_setitimer__doc__},
 
 static PyObject *
-signal_setitimer_impl(PyModuleDef *module, int which, double seconds,
+signal_setitimer_impl(PyObject *module, int which, double seconds,
                       double interval);
 
 static PyObject *
-signal_setitimer(PyModuleDef *module, PyObject *args)
+signal_setitimer(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int which;
@@ -211,10 +211,10 @@ PyDoc_STRVAR(signal_getitimer__doc__,
     {"getitimer", (PyCFunction)signal_getitimer, METH_O, signal_getitimer__doc__},
 
 static PyObject *
-signal_getitimer_impl(PyModuleDef *module, int which);
+signal_getitimer_impl(PyObject *module, int which);
 
 static PyObject *
-signal_getitimer(PyModuleDef *module, PyObject *arg)
+signal_getitimer(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int which;
@@ -241,10 +241,10 @@ PyDoc_STRVAR(signal_pthread_sigmask__doc__,
     {"pthread_sigmask", (PyCFunction)signal_pthread_sigmask, METH_VARARGS, signal_pthread_sigmask__doc__},
 
 static PyObject *
-signal_pthread_sigmask_impl(PyModuleDef *module, int how, PyObject *mask);
+signal_pthread_sigmask_impl(PyObject *module, int how, PyObject *mask);
 
 static PyObject *
-signal_pthread_sigmask(PyModuleDef *module, PyObject *args)
+signal_pthread_sigmask(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int how;
@@ -276,10 +276,10 @@ PyDoc_STRVAR(signal_sigpending__doc__,
     {"sigpending", (PyCFunction)signal_sigpending, METH_NOARGS, signal_sigpending__doc__},
 
 static PyObject *
-signal_sigpending_impl(PyModuleDef *module);
+signal_sigpending_impl(PyObject *module);
 
 static PyObject *
-signal_sigpending(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+signal_sigpending(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return signal_sigpending_impl(module);
 }
@@ -332,11 +332,11 @@ PyDoc_STRVAR(signal_sigtimedwait__doc__,
     {"sigtimedwait", (PyCFunction)signal_sigtimedwait, METH_VARARGS, signal_sigtimedwait__doc__},
 
 static PyObject *
-signal_sigtimedwait_impl(PyModuleDef *module, PyObject *sigset,
+signal_sigtimedwait_impl(PyObject *module, PyObject *sigset,
                          PyObject *timeout_obj);
 
 static PyObject *
-signal_sigtimedwait(PyModuleDef *module, PyObject *args)
+signal_sigtimedwait(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *sigset;
@@ -366,10 +366,10 @@ PyDoc_STRVAR(signal_pthread_kill__doc__,
     {"pthread_kill", (PyCFunction)signal_pthread_kill, METH_VARARGS, signal_pthread_kill__doc__},
 
 static PyObject *
-signal_pthread_kill_impl(PyModuleDef *module, long thread_id, int signalnum);
+signal_pthread_kill_impl(PyObject *module, long thread_id, int signalnum);
 
 static PyObject *
-signal_pthread_kill(PyModuleDef *module, PyObject *args)
+signal_pthread_kill(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     long thread_id;
@@ -429,4 +429,4 @@ exit:
 #ifndef SIGNAL_PTHREAD_KILL_METHODDEF
     #define SIGNAL_PTHREAD_KILL_METHODDEF
 #endif /* !defined(SIGNAL_PTHREAD_KILL_METHODDEF) */
-/*[clinic end generated code: output=b99278c16c40ea43 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=dafa598412bfb8d2 input=a9049054013a1b77]*/
index c0d18db..e26acf1 100644 (file)
@@ -16,10 +16,10 @@ PyDoc_STRVAR(spwd_getspnam__doc__,
     {"getspnam", (PyCFunction)spwd_getspnam, METH_O, spwd_getspnam__doc__},
 
 static PyObject *
-spwd_getspnam_impl(PyModuleDef *module, PyObject *arg);
+spwd_getspnam_impl(PyObject *module, PyObject *arg);
 
 static PyObject *
-spwd_getspnam(PyModuleDef *module, PyObject *arg_)
+spwd_getspnam(PyObject *module, PyObject *arg_)
 {
     PyObject *return_value = NULL;
     PyObject *arg;
@@ -48,10 +48,10 @@ PyDoc_STRVAR(spwd_getspall__doc__,
     {"getspall", (PyCFunction)spwd_getspall, METH_NOARGS, spwd_getspall__doc__},
 
 static PyObject *
-spwd_getspall_impl(PyModuleDef *module);
+spwd_getspall_impl(PyObject *module);
 
 static PyObject *
-spwd_getspall(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+spwd_getspall(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return spwd_getspall_impl(module);
 }
@@ -65,4 +65,4 @@ spwd_getspall(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
 #ifndef SPWD_GETSPALL_METHODDEF
     #define SPWD_GETSPALL_METHODDEF
 #endif /* !defined(SPWD_GETSPALL_METHODDEF) */
-/*[clinic end generated code: output=6c178830413f7763 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=510f681b36f54c30 input=a9049054013a1b77]*/
index 602ae1d..b1af7ce 100644 (file)
@@ -17,10 +17,10 @@ PyDoc_STRVAR(zlib_compress__doc__,
     {"compress", (PyCFunction)zlib_compress, METH_VARARGS, zlib_compress__doc__},
 
 static PyObject *
-zlib_compress_impl(PyModuleDef *module, Py_buffer *bytes, int level);
+zlib_compress_impl(PyObject *module, Py_buffer *bytes, int level);
 
 static PyObject *
-zlib_compress(PyModuleDef *module, PyObject *args)
+zlib_compress(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer bytes = {NULL, NULL};
@@ -56,19 +56,19 @@ PyDoc_STRVAR(zlib_decompress__doc__,
     {"decompress", (PyCFunction)zlib_decompress, METH_VARARGS, zlib_decompress__doc__},
 
 static PyObject *
-zlib_decompress_impl(PyModuleDef *module, Py_buffer *data, int wbits,
-                     unsigned int bufsize);
+zlib_decompress_impl(PyObject *module, Py_buffer *data, int wbits,
+                     Py_ssize_t bufsize);
 
 static PyObject *
-zlib_decompress(PyModuleDef *module, PyObject *args)
+zlib_decompress(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
     int wbits = MAX_WBITS;
-    unsigned int bufsize = DEF_BUF_SIZE;
+    Py_ssize_t bufsize = DEF_BUF_SIZE;
 
     if (!PyArg_ParseTuple(args, "y*|iO&:decompress",
-        &data, &wbits, capped_uint_converter, &bufsize))
+        &data, &wbits, ssize_t_converter, &bufsize))
         goto exit;
     return_value = zlib_decompress_impl(module, &data, wbits, bufsize);
 
@@ -114,11 +114,11 @@ PyDoc_STRVAR(zlib_compressobj__doc__,
     {"compressobj", (PyCFunction)zlib_compressobj, METH_VARARGS|METH_KEYWORDS, zlib_compressobj__doc__},
 
 static PyObject *
-zlib_compressobj_impl(PyModuleDef *module, int level, int method, int wbits,
+zlib_compressobj_impl(PyObject *module, int level, int method, int wbits,
                       int memLevel, int strategy, Py_buffer *zdict);
 
 static PyObject *
-zlib_compressobj(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+zlib_compressobj(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"level", "method", "wbits", "memLevel", "strategy", "zdict", NULL};
@@ -158,10 +158,10 @@ PyDoc_STRVAR(zlib_decompressobj__doc__,
     {"decompressobj", (PyCFunction)zlib_decompressobj, METH_VARARGS|METH_KEYWORDS, zlib_decompressobj__doc__},
 
 static PyObject *
-zlib_decompressobj_impl(PyModuleDef *module, int wbits, PyObject *zdict);
+zlib_decompressobj_impl(PyObject *module, int wbits, PyObject *zdict);
 
 static PyObject *
-zlib_decompressobj(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+zlib_decompressobj(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"wbits", "zdict", NULL};
@@ -236,17 +236,17 @@ PyDoc_STRVAR(zlib_Decompress_decompress__doc__,
 
 static PyObject *
 zlib_Decompress_decompress_impl(compobject *self, Py_buffer *data,
-                                unsigned int max_length);
+                                Py_ssize_t max_length);
 
 static PyObject *
 zlib_Decompress_decompress(compobject *self, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
-    unsigned int max_length = 0;
+    Py_ssize_t max_length = 0;
 
     if (!PyArg_ParseTuple(args, "y*|O&:decompress",
-        &data, capped_uint_converter, &max_length))
+        &data, ssize_t_converter, &max_length))
         goto exit;
     return_value = zlib_Decompress_decompress_impl(self, &data, max_length);
 
@@ -348,16 +348,16 @@ PyDoc_STRVAR(zlib_Decompress_flush__doc__,
     {"flush", (PyCFunction)zlib_Decompress_flush, METH_VARARGS, zlib_Decompress_flush__doc__},
 
 static PyObject *
-zlib_Decompress_flush_impl(compobject *self, unsigned int length);
+zlib_Decompress_flush_impl(compobject *self, Py_ssize_t length);
 
 static PyObject *
 zlib_Decompress_flush(compobject *self, PyObject *args)
 {
     PyObject *return_value = NULL;
-    unsigned int length = DEF_BUF_SIZE;
+    Py_ssize_t length = DEF_BUF_SIZE;
 
     if (!PyArg_ParseTuple(args, "|O&:flush",
-        capped_uint_converter, &length))
+        ssize_t_converter, &length))
         goto exit;
     return_value = zlib_Decompress_flush_impl(self, length);
 
@@ -380,10 +380,10 @@ PyDoc_STRVAR(zlib_adler32__doc__,
     {"adler32", (PyCFunction)zlib_adler32, METH_VARARGS, zlib_adler32__doc__},
 
 static PyObject *
-zlib_adler32_impl(PyModuleDef *module, Py_buffer *data, unsigned int value);
+zlib_adler32_impl(PyObject *module, Py_buffer *data, unsigned int value);
 
 static PyObject *
-zlib_adler32(PyModuleDef *module, PyObject *args)
+zlib_adler32(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -417,10 +417,10 @@ PyDoc_STRVAR(zlib_crc32__doc__,
     {"crc32", (PyCFunction)zlib_crc32, METH_VARARGS, zlib_crc32__doc__},
 
 static PyObject *
-zlib_crc32_impl(PyModuleDef *module, Py_buffer *data, unsigned int value);
+zlib_crc32_impl(PyObject *module, Py_buffer *data, unsigned int value);
 
 static PyObject *
-zlib_crc32(PyModuleDef *module, PyObject *args)
+zlib_crc32(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_buffer data = {NULL, NULL};
@@ -442,4 +442,4 @@ exit:
 #ifndef ZLIB_COMPRESS_COPY_METHODDEF
     #define ZLIB_COMPRESS_COPY_METHODDEF
 #endif /* !defined(ZLIB_COMPRESS_COPY_METHODDEF) */
-/*[clinic end generated code: output=f31627b314a7bd2f input=a9049054013a1b77]*/
+/*[clinic end generated code: output=7711ef02d1d5776c input=a9049054013a1b77]*/
index 82ea589..cba42a7 100644 (file)
@@ -82,12 +82,12 @@ else {
 #define CM_SCALE_DOWN (-(CM_SCALE_UP+1)/2)
 
 /* forward declarations */
-static Py_complex cmath_asinh_impl(PyModuleDef *, Py_complex);
-static Py_complex cmath_atanh_impl(PyModuleDef *, Py_complex);
-static Py_complex cmath_cosh_impl(PyModuleDef *, Py_complex);
-static Py_complex cmath_sinh_impl(PyModuleDef *, Py_complex);
-static Py_complex cmath_sqrt_impl(PyModuleDef *, Py_complex);
-static Py_complex cmath_tanh_impl(PyModuleDef *, Py_complex);
+static Py_complex cmath_asinh_impl(PyObject *, Py_complex);
+static Py_complex cmath_atanh_impl(PyObject *, Py_complex);
+static Py_complex cmath_cosh_impl(PyObject *, Py_complex);
+static Py_complex cmath_sinh_impl(PyObject *, Py_complex);
+static Py_complex cmath_sqrt_impl(PyObject *, Py_complex);
+static Py_complex cmath_tanh_impl(PyObject *, Py_complex);
 static PyObject * math_error(void);
 
 /* Code to deal with special values (infinities, NaNs, etc.). */
@@ -167,8 +167,8 @@ Return the arc cosine of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_acos_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=7c1dd21ff818db6b input=bd6cbd78ae851927]*/
+cmath_acos_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=40bd42853fd460ae input=bd6cbd78ae851927]*/
 {
     Py_complex s1, s2, r;
 
@@ -210,8 +210,8 @@ Return the inverse hyperbolic cosine of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_acosh_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=c23c776429def981 input=3f61bee7d703e53c]*/
+cmath_acosh_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=3e2454d4fcf404ca input=3f61bee7d703e53c]*/
 {
     Py_complex s1, s2, r;
 
@@ -242,8 +242,8 @@ Return the arc sine of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_asin_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=42d2346d46690826 input=be0bf0cfdd5239c5]*/
+cmath_asin_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=3b264cd1b16bf4e1 input=be0bf0cfdd5239c5]*/
 {
     /* asin(z) = -i asinh(iz) */
     Py_complex s, r;
@@ -265,8 +265,8 @@ Return the inverse hyperbolic sine of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_asinh_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=0c6664823c7b1b35 input=5c09448fcfc89a79]*/
+cmath_asinh_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=733d8107841a7599 input=5c09448fcfc89a79]*/
 {
     Py_complex s1, s2, r;
 
@@ -303,8 +303,8 @@ Return the arc tangent of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_atan_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=b7d44f02c6a5c3b5 input=3b21ff7d5eac632a]*/
+cmath_atan_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=b6bfc497058acba4 input=3b21ff7d5eac632a]*/
 {
     /* atan(z) = -i atanh(iz) */
     Py_complex s, r;
@@ -356,8 +356,8 @@ Return the inverse hyperbolic tangent of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_atanh_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=279e0b9fefc8da7c input=2b3fdb82fb34487b]*/
+cmath_atanh_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=e83355f93a989c9e input=2b3fdb82fb34487b]*/
 {
     Py_complex r;
     double ay, h;
@@ -411,8 +411,8 @@ Return the cosine of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_cos_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=9d1cdc1b5e761667 input=6022e39b77127ac7]*/
+cmath_cos_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=fd64918d5b3186db input=6022e39b77127ac7]*/
 {
     /* cos(z) = cosh(iz) */
     Py_complex r;
@@ -433,8 +433,8 @@ Return the hyperbolic cosine of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_cosh_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=f3b5d3282b3024d3 input=d6b66339e9cc332b]*/
+cmath_cosh_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=2e969047da601bdb input=d6b66339e9cc332b]*/
 {
     Py_complex r;
     double x_minus_one;
@@ -495,8 +495,8 @@ Return the exponential value e**z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_exp_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=6f8825eb2bcad9ba input=8b9e6cf8a92174c3]*/
+cmath_exp_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=edcec61fb9dfda6c input=8b9e6cf8a92174c3]*/
 {
     Py_complex r;
     double l;
@@ -624,8 +624,8 @@ Return the base-10 logarithm of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_log10_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=c7c426ca0e782341 input=cff5644f73c1519c]*/
+cmath_log10_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=2922779a7c38cbe1 input=cff5644f73c1519c]*/
 {
     Py_complex r;
     int errno_save;
@@ -646,8 +646,8 @@ Return the sine of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_sin_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=e7f5e2b253825ac7 input=2d3519842a8b4b85]*/
+cmath_sin_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=980370d2ff0bb5aa input=2d3519842a8b4b85]*/
 {
     /* sin(z) = -i sin(iz) */
     Py_complex s, r;
@@ -670,8 +670,8 @@ Return the hyperbolic sine of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_sinh_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=d71fff8298043a95 input=d2d3fc8c1ddfd2dd]*/
+cmath_sinh_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=38b0a6cce26f3536 input=d2d3fc8c1ddfd2dd]*/
 {
     Py_complex r;
     double x_minus_one;
@@ -729,8 +729,8 @@ Return the square root of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_sqrt_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=b6bda283d0c5a7b4 input=7088b166fc9a58c7]*/
+cmath_sqrt_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=b6507b3029c339fc input=7088b166fc9a58c7]*/
 {
     /*
        Method: use symmetries to reduce to the case when x = z.real and y
@@ -804,8 +804,8 @@ Return the tangent of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_tan_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=df374bacf36d99b4 input=fc167e528767888e]*/
+cmath_tan_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=7c5f13158a72eb13 input=fc167e528767888e]*/
 {
     /* tan(z) = -i tanh(iz) */
     Py_complex s, r;
@@ -828,8 +828,8 @@ Return the hyperbolic tangent of z.
 [clinic start generated code]*/
 
 static Py_complex
-cmath_tanh_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=f578773d27a18e96 input=22f67f9dc6d29685]*/
+cmath_tanh_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=36d547ef7aca116c input=22f67f9dc6d29685]*/
 {
     /* Formula:
 
@@ -906,8 +906,8 @@ If the base not specified, returns the natural logarithm (base e) of z.
 [clinic start generated code]*/
 
 static PyObject *
-cmath_log_impl(PyModuleDef *module, Py_complex x, PyObject *y_obj)
-/*[clinic end generated code: output=35e2a1e5229b5a46 input=ee0e823a7c6e68ea]*/
+cmath_log_impl(PyObject *module, Py_complex x, PyObject *y_obj)
+/*[clinic end generated code: output=4effdb7d258e0d94 input=ee0e823a7c6e68ea]*/
 {
     Py_complex y;
 
@@ -954,8 +954,8 @@ Return argument, also known as the phase angle, of a complex.
 [clinic start generated code]*/
 
 static PyObject *
-cmath_phase_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=e09eaf373cb624c3 input=5cf75228ba94b69d]*/
+cmath_phase_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=50725086a7bfd253 input=5cf75228ba94b69d]*/
 {
     double phi;
 
@@ -981,8 +981,8 @@ r is the distance from 0 and phi the phase angle.
 [clinic start generated code]*/
 
 static PyObject *
-cmath_polar_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=07d41b16c877875a input=26c353574fd1a861]*/
+cmath_polar_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=d0a8147c41dbb654 input=26c353574fd1a861]*/
 {
     double r, phi;
 
@@ -1021,8 +1021,8 @@ Convert from polar coordinates to rectangular coordinates.
 [clinic start generated code]*/
 
 static PyObject *
-cmath_rect_impl(PyModuleDef *module, double r, double phi)
-/*[clinic end generated code: output=d97a8749bd63e9d5 input=24c5646d147efd69]*/
+cmath_rect_impl(PyObject *module, double r, double phi)
+/*[clinic end generated code: output=385a0690925df2d5 input=24c5646d147efd69]*/
 {
     Py_complex z;
     errno = 0;
@@ -1082,8 +1082,8 @@ Return True if both the real and imaginary parts of z are finite, else False.
 [clinic start generated code]*/
 
 static PyObject *
-cmath_isfinite_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=8f6682fa93de45d6 input=848e7ee701895815]*/
+cmath_isfinite_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=ac76611e2c774a36 input=848e7ee701895815]*/
 {
     return PyBool_FromLong(Py_IS_FINITE(z.real) && Py_IS_FINITE(z.imag));
 }
@@ -1095,8 +1095,8 @@ Checks if the real or imaginary part of z not a number (NaN).
 [clinic start generated code]*/
 
 static PyObject *
-cmath_isnan_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=b85fe8c2047718ee input=71799f5d284c9baf]*/
+cmath_isnan_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=e7abf6e0b28beab7 input=71799f5d284c9baf]*/
 {
     return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag));
 }
@@ -1108,8 +1108,8 @@ Checks if the real or imaginary part of z is infinite.
 [clinic start generated code]*/
 
 static PyObject *
-cmath_isinf_impl(PyModuleDef *module, Py_complex z)
-/*[clinic end generated code: output=8ca9c6109e468bf4 input=363df155c7181329]*/
+cmath_isinf_impl(PyObject *module, Py_complex z)
+/*[clinic end generated code: output=502a75a79c773469 input=363df155c7181329]*/
 {
     return PyBool_FromLong(Py_IS_INFINITY(z.real) ||
                            Py_IS_INFINITY(z.imag));
@@ -1140,9 +1140,9 @@ not close to anything, even itself. inf and -inf are only close to themselves.
 [clinic start generated code]*/
 
 static int
-cmath_isclose_impl(PyModuleDef *module, Py_complex a, Py_complex b,
+cmath_isclose_impl(PyObject *module, Py_complex a, Py_complex b,
                    double rel_tol, double abs_tol)
-/*[clinic end generated code: output=da0c535fb54e2310 input=df9636d7de1d4ac3]*/
+/*[clinic end generated code: output=8a2486cc6e0014d1 input=df9636d7de1d4ac3]*/
 {
     double diff;
 
index 9a8f85d..44772e2 100644 (file)
@@ -2,6 +2,8 @@
    See the file COPYING for copying permission.
 */
 
+#include <stddef.h>
+
 #ifdef COMPILED_FROM_DSP
 #include "winconfig.h"
 #elif defined(MACOS_CLASSIC)
@@ -16,8 +18,6 @@
 #endif
 #endif /* ndef COMPILED_FROM_DSP */
 
-#include <stddef.h>
-
 #include "expat_external.h"
 #include "internal.h"
 #include "xmlrole.h"
index 205c07e..bf09dfc 100644 (file)
@@ -2,6 +2,8 @@
    See the file COPYING for copying permission.
 */
 
+#include <stddef.h>
+
 #ifdef COMPILED_FROM_DSP
 #include "winconfig.h"
 #elif defined(MACOS_CLASSIC)
@@ -16,8 +18,6 @@
 #endif
 #endif /* ndef COMPILED_FROM_DSP */
 
-#include <stddef.h>
-
 #include "expat_external.h"
 #include "internal.h"
 #include "xmltok.h"
index 4e6eb72..8875b26 100644 (file)
@@ -26,7 +26,7 @@ conv_descriptor(PyObject *object, int *target)
     int fd = PyObject_AsFileDescriptor(object);
 
     if (fd < 0)
-    return 0;
+        return 0;
     *target = fd;
     return 1;
 }
@@ -56,8 +56,8 @@ corresponding to the return value of the fcntl call in the C code.
 [clinic start generated code]*/
 
 static PyObject *
-fcntl_fcntl_impl(PyModuleDef *module, int fd, int code, PyObject *arg)
-/*[clinic end generated code: output=afc5bfa74a03ef0d input=8cefbe59b29efbe2]*/
+fcntl_fcntl_impl(PyObject *module, int fd, int code, PyObject *arg)
+/*[clinic end generated code: output=888fc93b51c295bd input=8cefbe59b29efbe2]*/
 {
     unsigned int int_arg = 0;
     int ret;
@@ -146,9 +146,9 @@ code.
 [clinic start generated code]*/
 
 static PyObject *
-fcntl_ioctl_impl(PyModuleDef *module, int fd, unsigned int code,
+fcntl_ioctl_impl(PyObject *module, int fd, unsigned int code,
                  PyObject *ob_arg, int mutate_arg)
-/*[clinic end generated code: output=102faa0f7ebe2210 input=ede70c433cccbbb2]*/
+/*[clinic end generated code: output=7f7f5840c65991be input=ede70c433cccbbb2]*/
 {
 #define IOCTL_BUFSZ 1024
     /* We use the unsigned non-checked 'I' format for the 'code' parameter
@@ -279,8 +279,8 @@ function is emulated using fcntl()).
 [clinic start generated code]*/
 
 static PyObject *
-fcntl_flock_impl(PyModuleDef *module, int fd, int code)
-/*[clinic end generated code: output=c9035133a7dbfc96 input=b70a0a41ca22a8a0]*/
+fcntl_flock_impl(PyObject *module, int fd, int code)
+/*[clinic end generated code: output=84059e2b37d2fc64 input=b70a0a41ca22a8a0]*/
 {
     int ret;
 
@@ -358,9 +358,9 @@ starts.  `whence` is as with fileobj.seek(), specifically:
 [clinic start generated code]*/
 
 static PyObject *
-fcntl_lockf_impl(PyModuleDef *module, int fd, int code, PyObject *lenobj,
+fcntl_lockf_impl(PyObject *module, int fd, int code, PyObject *lenobj,
                  PyObject *startobj, int whence)
-/*[clinic end generated code: output=31af35eba08b9af7 input=3a5dc01b04371f1a]*/
+/*[clinic end generated code: output=4985e7a172e7461a input=3a5dc01b04371f1a]*/
 {
     int ret;
 
index 18deb60..c438b8e 100644 (file)
@@ -762,7 +762,10 @@ calculate_path(void)
 
         if (defpath[0] != SEP) {
             wcscat(buf, prefix);
-            wcscat(buf, separator);
+            if (prefixsz >= 2 && prefix[prefixsz - 2] != SEP &&
+                defpath[0] != (delim ? DELIM : L'\0')) {  /* not empty */
+                wcscat(buf, separator);
+            }
         }
 
         if (delim) {
index 403e434..3a134a0 100644 (file)
@@ -93,8 +93,8 @@ If id is not valid, raise KeyError.
 [clinic start generated code]*/
 
 static PyObject *
-grp_getgrgid_impl(PyModuleDef *module, PyObject *id)
-/*[clinic end generated code: output=8a11f5fdeb8c78a0 input=15fa0e2ccf5cda25]*/
+grp_getgrgid_impl(PyObject *module, PyObject *id)
+/*[clinic end generated code: output=30797c289504a1ba input=15fa0e2ccf5cda25]*/
 {
     PyObject *py_int_id;
     gid_t gid;
@@ -131,8 +131,8 @@ If name is not valid, raise KeyError.
 [clinic start generated code]*/
 
 static PyObject *
-grp_getgrnam_impl(PyModuleDef *module, PyObject *name)
-/*[clinic end generated code: output=cd47511f4854da8e input=08ded29affa3c863]*/
+grp_getgrnam_impl(PyObject *module, PyObject *name)
+/*[clinic end generated code: output=67905086f403c21c input=08ded29affa3c863]*/
 {
     char *name_chars;
     struct group *p;
@@ -163,8 +163,8 @@ to use YP/NIS and may not be accessible via getgrnam or getgrgid.
 [clinic start generated code]*/
 
 static PyObject *
-grp_getgrall_impl(PyModuleDef *module)
-/*[clinic end generated code: output=add9037a20c202de input=d7df76c825c367df]*/
+grp_getgrall_impl(PyObject *module)
+/*[clinic end generated code: output=585dad35e2e763d7 input=d7df76c825c367df]*/
 {
     PyObject *d;
     struct group *p;
index 133f313..fdddc19 100644 (file)
@@ -327,7 +327,8 @@ _Py_hashtable_set(_Py_hashtable_t *ht, const void *key,
     entry->key_hash = key_hash;
 
     assert(data_size == ht->data_size);
-    memcpy(_Py_HASHTABLE_ENTRY_DATA(entry), data, data_size);
+    if (data)
+        memcpy(_Py_HASHTABLE_ENTRY_DATA(entry), data, data_size);
 
     _Py_slist_prepend(&ht->buckets[index], (_Py_slist_item_t*)entry);
     ht->entries++;
index 409922a..be0f498 100644 (file)
@@ -155,8 +155,13 @@ static PyObject *
 groupby_setstate(groupbyobject *lz, PyObject *state)
 {
     PyObject *currkey, *currvalue, *tgtkey;
-    if (!PyArg_ParseTuple(state, "OOO", &currkey, &currvalue, &tgtkey))
+    if (!PyTuple_Check(state)) {
+        PyErr_SetString(PyExc_TypeError, "state is not a tuple");
         return NULL;
+    }
+    if (!PyArg_ParseTuple(state, "OOO", &currkey, &currvalue, &tgtkey)) {
+        return NULL;
+    }
     Py_INCREF(currkey);
     Py_XSETREF(lz->currkey, currkey);
     Py_INCREF(currvalue);
@@ -736,8 +741,13 @@ tee_setstate(teeobject *to, PyObject *state)
 {
     teedataobject *tdo;
     int index;
-    if (!PyArg_ParseTuple(state, "O!i", &teedataobject_type, &tdo, &index))
+    if (!PyTuple_Check(state)) {
+        PyErr_SetString(PyExc_TypeError, "state is not a tuple");
+        return NULL;
+    }
+    if (!PyArg_ParseTuple(state, "O!i", &teedataobject_type, &tdo, &index)) {
         return NULL;
+    }
     if (index < 0 || index > LINKCELLS) {
         PyErr_SetString(PyExc_ValueError, "Index out of range");
         return NULL;
@@ -966,8 +976,13 @@ cycle_setstate(cycleobject *lz, PyObject *state)
 {
     PyObject *saved=NULL;
     int firstpass;
-    if (!PyArg_ParseTuple(state, "Oi", &saved, &firstpass))
+    if (!PyTuple_Check(state)) {
+        PyErr_SetString(PyExc_TypeError, "state is not a tuple");
+        return NULL;
+    }
+    if (!PyArg_ParseTuple(state, "O!i", &PyList_Type, &saved, &firstpass)) {
         return NULL;
+    }
     Py_XINCREF(saved);
     Py_XSETREF(lz->saved, saved);
     lz->firstpass = firstpass != 0;
@@ -1891,8 +1906,18 @@ static PyObject *
 chain_setstate(chainobject *lz, PyObject *state)
 {
     PyObject *source, *active=NULL;
-    if (! PyArg_ParseTuple(state, "O|O", &source, &active))
+
+    if (!PyTuple_Check(state)) {
+        PyErr_SetString(PyExc_TypeError, "state is not a tuple");
+        return NULL;
+    }
+    if (!PyArg_ParseTuple(state, "O|O", &source, &active)) {
         return NULL;
+    }
+    if (!PyIter_Check(source) || (active != NULL && !PyIter_Check(active))) {
+        PyErr_SetString(PyExc_TypeError, "Arguments must be iterators.");
+        return NULL;
+    }
 
     Py_INCREF(source);
     Py_XSETREF(lz->source, source);
@@ -1911,7 +1936,7 @@ iterable, until all of the iterables are exhausted.");
 PyDoc_STRVAR(chain_from_iterable_doc,
 "chain.from_iterable(iterable) --> chain object\n\
 \n\
-Alternate chain() contructor taking a single iterable argument\n\
+Alternate chain() constructor taking a single iterable argument\n\
 that evaluates lazily.");
 
 static PyMethodDef chain_methods[] = {
@@ -3251,10 +3276,15 @@ permutations_setstate(permutationsobject *po, PyObject *state)
     PyObject *indices, *cycles, *result;
     Py_ssize_t n, i;
 
+    if (!PyTuple_Check(state)) {
+        PyErr_SetString(PyExc_TypeError, "state is not a tuple");
+        return NULL;
+    }
     if (!PyArg_ParseTuple(state, "O!O!",
                           &PyTuple_Type, &indices,
-                          &PyTuple_Type, &cycles))
+                          &PyTuple_Type, &cycles)) {
         return NULL;
+    }
 
     n = PyTuple_GET_SIZE(po->pool);
     if (PyTuple_GET_SIZE(indices) != n ||
@@ -3905,7 +3935,7 @@ static PyObject *
 count_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
     countobject *lz;
-    int slow_mode = 0;
+    int fast_mode;
     Py_ssize_t cnt = 0;
     PyObject *long_cnt = NULL;
     PyObject *long_step = NULL;
@@ -3922,16 +3952,26 @@ count_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
                     return NULL;
     }
 
+    fast_mode = (long_cnt == NULL || PyLong_Check(long_cnt)) &&
+                (long_step == NULL || PyLong_Check(long_step));
+
+    /* If not specified, start defaults to 0 */
     if (long_cnt != NULL) {
-        cnt = PyLong_AsSsize_t(long_cnt);
-        if ((cnt == -1 && PyErr_Occurred()) || !PyLong_Check(long_cnt)) {
-            PyErr_Clear();
-            slow_mode = 1;
+        if (fast_mode) {
+            assert(PyLong_Check(long_cnt));
+            cnt = PyLong_AsSsize_t(long_cnt);
+            if (cnt == -1 && PyErr_Occurred()) {
+                PyErr_Clear();
+                fast_mode = 0;
+            }
         }
         Py_INCREF(long_cnt);
     } else {
         cnt = 0;
         long_cnt = PyLong_FromLong(0);
+        if (long_cnt == NULL) {
+            return NULL;
+        }
     }
 
     /* If not specified, step defaults to 1 */
@@ -3947,21 +3987,24 @@ count_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     assert(long_cnt != NULL && long_step != NULL);
 
     /* Fast mode only works when the step is 1 */
-    step = PyLong_AsLong(long_step);
-    if (step != 1) {
-        slow_mode = 1;
-        if (step == -1 && PyErr_Occurred())
-            PyErr_Clear();
+    if (fast_mode) {
+        assert(PyLong_Check(long_step));
+        step = PyLong_AsLong(long_step);
+        if (step != 1) {
+            fast_mode = 0;
+            if (step == -1 && PyErr_Occurred())
+                PyErr_Clear();
+        }
     }
 
-    if (slow_mode)
-        cnt = PY_SSIZE_T_MAX;
-    else
+    if (fast_mode)
         Py_CLEAR(long_cnt);
+    else
+        cnt = PY_SSIZE_T_MAX;
 
-    assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) ||
-           (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode));
-    assert(slow_mode ||
+    assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && fast_mode) ||
+           (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && !fast_mode));
+    assert(!fast_mode ||
            (PyLong_Check(long_step) && PyLong_AS_LONG(long_step) == 1));
 
     /* create countobject structure */
index add6b3e..f4eab40 100644 (file)
@@ -70,6 +70,7 @@ if test ! -n "$*"; then
 fi
 
 makexp=`dirname $0`/makexp_aix
+test -x "${makexp}" || makexp="@abs_srcdir@/makexp_aix"
 
 # Check for existence of compiler.
 CC=$1; shift
index 90db42e..e204a05 100755 (executable)
@@ -29,6 +29,7 @@
 #
 # Copying Makefile.pre to Makefile:
 # - insert an identifying comment at the start
+# - replace _MODNAMES_ by the list of modules from Setup
 # - replace _MODOBJS_ by the list of objects from Setup (except for
 #   Setup files after a -n option)
 # - replace _MODLIBS_ by the list of libraries from Setup
@@ -82,7 +83,7 @@ esac
 NL='\
 '
 
-# Setup to link with extra libraries when makeing shared extensions.
+# Setup to link with extra libraries when making shared extensions.
 # Currently, only Cygwin needs this baggage.
 case `uname -s` in
 CYGWIN*) if test $libdir = .
@@ -110,6 +111,7 @@ sed -e 's/[         ]*#.*//' -e '/^[        ]*$/d' |
 # Rules appended by makedepend
 " >$rulesf
        DEFS=
+       NAMES=
        MODS=
        SHAREDMODS=
        OBJS=
@@ -181,7 +183,7 @@ sed -e 's/[         ]*#.*//' -e '/^[        ]*$/d' |
                        *.*)            echo 1>&2 "bad word $arg in $line"
                                        exit 1;;
                        -u)             skip=libs; libs="$libs -u";;
-                       [a-zA-Z_]*)     mods="$mods $arg";;
+                       [a-zA-Z_]*)     NAMES="$NAMES $arg"; mods="$mods $arg";;
                        *)              echo 1>&2 "bad word $arg in $line"
                                        exit 1;;
                        esac
@@ -280,6 +282,7 @@ sed -e 's/[         ]*#.*//' -e '/^[        ]*$/d' |
                echo "1i\\" >$sedf
                str="# Generated automatically from $makepre by makesetup."
                echo "$str" >>$sedf
+               echo "s%_MODNAMES_%$NAMES%" >>$sedf
                echo "s%_MODOBJS_%$OBJS%" >>$sedf
                echo "s%_MODLIBS_%$LIBS%" >>$sedf
                echo "/Definitions added by makesetup/a$NL$NL$DEFS" >>$sedf
index 7ebf8e8..b945bd6 100644 (file)
@@ -1274,7 +1274,7 @@ count_set_bits(unsigned long n)
 
 /* Divide-and-conquer factorial algorithm
  *
- * Based on the formula and psuedo-code provided at:
+ * Based on the formula and pseudo-code provided at:
  * http://www.luschny.de/math/factorial/binarysplitfact.html
  *
  * Faster algorithms exist, but they're more complicated and depend on
index a9ebc8c..f94acc7 100644 (file)
@@ -509,8 +509,8 @@ Return a new MD5 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
 static PyObject *
-_md5_md5_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=3527436a2090b956 input=d12ef8f72d684f7b]*/
+_md5_md5_impl(PyObject *module, PyObject *string)
+/*[clinic end generated code: output=2cfd0f8c091b97e6 input=d12ef8f72d684f7b]*/
 {
     MD5object *new;
     Py_buffer buf;
index bb98a99..4eb9274 100644 (file)
@@ -90,8 +90,8 @@ typedef enum
 typedef struct {
     PyObject_HEAD
     char *      data;
-    size_t      size;
-    size_t      pos;    /* relative to offset */
+    Py_ssize_t  size;
+    Py_ssize_t  pos;    /* relative to offset */
 #ifdef MS_WINDOWS
     PY_LONG_LONG offset;
 #else
@@ -210,33 +210,32 @@ mmap_read_byte_method(mmap_object *self,
                       PyObject *unused)
 {
     CHECK_VALID(NULL);
-    if (self->pos < self->size) {
-        char value = self->data[self->pos];
-        self->pos += 1;
-        return Py_BuildValue("B", (unsigned char)value);
-    } else {
+    if (self->pos >= self->size) {
         PyErr_SetString(PyExc_ValueError, "read byte out of range");
         return NULL;
     }
+    return PyLong_FromLong((unsigned char)self->data[self->pos++]);
 }
 
 static PyObject *
 mmap_read_line_method(mmap_object *self,
                       PyObject *unused)
 {
-    char *start = self->data+self->pos;
-    char *eof = self->data+self->size;
-    char *eol;
+    Py_ssize_t remaining;
+    char *start, *eol;
     PyObject *result;
 
     CHECK_VALID(NULL);
 
-    eol = memchr(start, '\n', self->size - self->pos);
+    remaining = (self->pos < self->size) ? self->size - self->pos : 0;
+    if (!remaining)
+        return PyBytes_FromString("");
+    start = self->data + self->pos;
+    eol = memchr(start, '\n', remaining);
     if (!eol)
-        eol = eof;
+        eol = self->data + self->size;
     else
-        ++eol;                  /* we're interested in the position after the
-                           newline. */
+        ++eol; /* advance past newline */
     result = PyBytes_FromStringAndSize(start, (eol - start));
     self->pos += (eol - start);
     return result;
@@ -268,7 +267,7 @@ static PyObject *
 mmap_read_method(mmap_object *self,
                  PyObject *args)
 {
-    Py_ssize_t num_bytes = -1, n;
+    Py_ssize_t num_bytes = PY_SSIZE_T_MAX, remaining;
     PyObject *result;
 
     CHECK_VALID(NULL);
@@ -276,20 +275,10 @@ mmap_read_method(mmap_object *self,
         return(NULL);
 
     /* silently 'adjust' out-of-range requests */
-    assert(self->size >= self->pos);
-    n = self->size - self->pos;
-    /* The difference can overflow, only if self->size is greater than
-     * PY_SSIZE_T_MAX.  But then the operation cannot possibly succeed,
-     * because the mapped area and the returned string each need more
-     * than half of the addressable memory.  So we clip the size, and let
-     * the code below raise MemoryError.
-     */
-    if (n < 0)
-        n = PY_SSIZE_T_MAX;
-    if (num_bytes < 0 || num_bytes > n) {
-        num_bytes = n;
-    }
-    result = PyBytes_FromStringAndSize(self->data+self->pos, num_bytes);
+    remaining = (self->pos < self->size) ? self->size - self->pos : 0;
+    if (num_bytes < 0 || num_bytes > remaining)
+        num_bytes = remaining;
+    result = PyBytes_FromStringAndSize(&self->data[self->pos], num_bytes);
     self->pos += num_bytes;
     return result;
 }
@@ -317,14 +306,14 @@ mmap_gfind(mmap_object *self,
             start += self->size;
         if (start < 0)
             start = 0;
-        else if ((size_t)start > self->size)
+        else if (start > self->size)
             start = self->size;
 
         if (end < 0)
             end += self->size;
         if (end < 0)
             end = 0;
-        else if ((size_t)end > self->size)
+        else if (end > self->size)
             end = self->size;
 
         start_p = self->data + start;
@@ -399,13 +388,14 @@ mmap_write_method(mmap_object *self,
         return NULL;
     }
 
-    if ((self->pos + data.len) > self->size) {
-        PyErr_SetString(PyExc_ValueError, "data out of range");
+    if (self->pos > self->size || self->size - self->pos < data.len) {
         PyBuffer_Release(&data);
+        PyErr_SetString(PyExc_ValueError, "data out of range");
         return NULL;
     }
-    memcpy(self->data + self->pos, data.buf, data.len);
-    self->pos = self->pos + data.len;
+
+    memcpy(&self->data[self->pos], data.buf, data.len);
+    self->pos += data.len;
     PyBuffer_Release(&data);
     Py_INCREF(Py_None);
     return Py_None;
@@ -425,8 +415,7 @@ mmap_write_byte_method(mmap_object *self,
         return NULL;
 
     if (self->pos < self->size) {
-        *(self->data+self->pos) = value;
-        self->pos += 1;
+        self->data[self->pos++] = value;
         Py_INCREF(Py_None);
         return Py_None;
     }
@@ -495,8 +484,14 @@ mmap_resize_method(mmap_object *self,
     if (!PyArg_ParseTuple(args, "n:resize", &new_size) ||
         !is_resizeable(self)) {
         return NULL;
+    }
+    if (new_size < 0 || PY_SSIZE_T_MAX - new_size < self->offset) {
+        PyErr_SetString(PyExc_ValueError, "new size out of range");
+        return NULL;
+    }
+
+    {
 #ifdef MS_WINDOWS
-    } else {
         DWORD dwErrCode = 0;
         DWORD off_hi, off_lo, newSizeLow, newSizeHigh;
         /* First, unmap the file view */
@@ -546,15 +541,13 @@ mmap_resize_method(mmap_object *self,
 
 #ifdef UNIX
 #ifndef HAVE_MREMAP
-    } else {
         PyErr_SetString(PyExc_SystemError,
                         "mmap: resizing not available--no mremap()");
         return NULL;
 #else
-    } else {
         void *newmap;
 
-        if (ftruncate(self->fd, self->offset + new_size) == -1) {
+        if (self->fd != -1 && ftruncate(self->fd, self->offset + new_size) == -1) {
             PyErr_SetFromErrno(PyExc_OSError);
             return NULL;
         }
@@ -562,11 +555,11 @@ mmap_resize_method(mmap_object *self,
 #ifdef MREMAP_MAYMOVE
         newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE);
 #else
-        #if defined(__NetBSD__)
-            newmap = mremap(self->data, self->size, self->data, new_size, 0);
-        #else
-            newmap = mremap(self->data, self->size, new_size, 0);
-        #endif /* __NetBSD__ */
+#if defined(__NetBSD__)
+        newmap = mremap(self->data, self->size, self->data, new_size, 0);
+#else
+        newmap = mremap(self->data, self->size, new_size, 0);
+#endif /* __NetBSD__ */
 #endif
         if (newmap == (void *)-1)
         {
@@ -597,7 +590,7 @@ mmap_flush_method(mmap_object *self, PyObject *args)
     CHECK_VALID(NULL);
     if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size))
         return NULL;
-    if ((size_t)(offset + size) > self->size) {
+    if (size < 0 || offset < 0 || self->size - offset < size) {
         PyErr_SetString(PyExc_ValueError, "flush values out of range");
         return NULL;
     }
@@ -630,20 +623,18 @@ mmap_seek_method(mmap_object *self, PyObject *args)
     if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how))
         return NULL;
     else {
-        size_t where;
+        Py_ssize_t where;
         switch (how) {
         case 0: /* relative to start */
-            if (dist < 0)
-                goto onoutofrange;
             where = dist;
             break;
         case 1: /* relative to current position */
-            if ((Py_ssize_t)self->pos + dist < 0)
+            if (PY_SSIZE_T_MAX - self->pos < dist)
                 goto onoutofrange;
             where = self->pos + dist;
             break;
         case 2: /* relative to end */
-            if ((Py_ssize_t)self->size + dist < 0)
+            if (PY_SSIZE_T_MAX - self->size < dist)
                 goto onoutofrange;
             where = self->size + dist;
             break;
@@ -651,7 +642,7 @@ mmap_seek_method(mmap_object *self, PyObject *args)
             PyErr_SetString(PyExc_ValueError, "unknown seek type");
             return NULL;
         }
-        if (where > self->size)
+        if (where > self->size || where < 0)
             goto onoutofrange;
         self->pos = where;
         Py_INCREF(Py_None);
@@ -666,23 +657,27 @@ mmap_seek_method(mmap_object *self, PyObject *args)
 static PyObject *
 mmap_move_method(mmap_object *self, PyObject *args)
 {
-    unsigned long dest, src, cnt;
+    Py_ssize_t dest, src, cnt;
     CHECK_VALID(NULL);
-    if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) ||
+    if (!PyArg_ParseTuple(args, "nnn:move", &dest, &src, &cnt) ||
         !is_writable(self)) {
         return NULL;
     } else {
         /* bounds check the values */
-        if ((cnt + dest) < cnt || (cnt + src) < cnt ||
-           src > self->size || (src + cnt) > self->size ||
-           dest > self->size || (dest + cnt) > self->size) {
-            PyErr_SetString(PyExc_ValueError,
-                "source, destination, or count out of range");
-            return NULL;
-        }
-        memmove(self->data+dest, self->data+src, cnt);
+        if (dest < 0 || src < 0 || cnt < 0)
+            goto bounds;
+        if (self->size - dest < cnt || self->size - src < cnt)
+            goto bounds;
+
+        memmove(&self->data[dest], &self->data[src], cnt);
+
         Py_INCREF(Py_None);
         return Py_None;
+
+      bounds:
+        PyErr_SetString(PyExc_ValueError,
+                        "source, destination, or count out of range");
+        return NULL;
     }
 }
 
@@ -785,7 +780,7 @@ static PyObject *
 mmap_item(mmap_object *self, Py_ssize_t i)
 {
     CHECK_VALID(NULL);
-    if (i < 0 || (size_t)i >= self->size) {
+    if (i < 0 || i >= self->size) {
         PyErr_SetString(PyExc_IndexError, "mmap index out of range");
         return NULL;
     }
@@ -802,7 +797,7 @@ mmap_subscript(mmap_object *self, PyObject *item)
             return NULL;
         if (i < 0)
             i += self->size;
-        if (i < 0 || (size_t)i >= self->size) {
+        if (i < 0 || i >= self->size) {
             PyErr_SetString(PyExc_IndexError,
                 "mmap index out of range");
             return NULL;
@@ -870,7 +865,7 @@ mmap_ass_item(mmap_object *self, Py_ssize_t i, PyObject *v)
     const char *buf;
 
     CHECK_VALID(-1);
-    if (i < 0 || (size_t)i >= self->size) {
+    if (i < 0 || i >= self->size) {
         PyErr_SetString(PyExc_IndexError, "mmap index out of range");
         return -1;
     }
@@ -907,7 +902,7 @@ mmap_ass_subscript(mmap_object *self, PyObject *item, PyObject *value)
             return -1;
         if (i < 0)
             i += self->size;
-        if (i < 0 || (size_t)i >= self->size) {
+        if (i < 0 || i >= self->size) {
             PyErr_SetString(PyExc_IndexError,
                             "mmap index out of range");
             return -1;
@@ -1074,32 +1069,6 @@ static PyTypeObject mmap_object_type = {
 };
 
 
-/* extract the map size from the given PyObject
-
-   Returns -1 on error, with an appropriate Python exception raised. On
-   success, the map size is returned. */
-static Py_ssize_t
-_GetMapSize(PyObject *o, const char* param)
-{
-    if (o == NULL)
-        return 0;
-    if (PyIndex_Check(o)) {
-        Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
-        if (i==-1 && PyErr_Occurred())
-            return -1;
-        if (i < 0) {
-            PyErr_Format(PyExc_OverflowError,
-                            "memory mapped %s must be positive",
-                            param);
-            return -1;
-        }
-        return i;
-    }
-
-    PyErr_SetString(PyExc_TypeError, "map size must be an integral value");
-    return -1;
-}
-
 #ifdef UNIX
 #ifdef HAVE_LARGEFILE_SUPPORT
 #define _Py_PARSE_OFF_T "L"
@@ -1112,7 +1081,6 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
 {
     struct _Py_stat_struct status;
     mmap_object *m_obj;
-    PyObject *map_size_obj = NULL;
     Py_ssize_t map_size;
     off_t offset = 0;
     int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
@@ -1122,13 +1090,15 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
                                "flags", "prot",
                                "access", "offset", NULL};
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iii" _Py_PARSE_OFF_T, keywords,
-                                     &fd, &map_size_obj, &flags, &prot,
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|iii" _Py_PARSE_OFF_T, keywords,
+                                     &fd, &map_size, &flags, &prot,
                                      &access, &offset))
         return NULL;
-    map_size = _GetMapSize(map_size_obj, "size");
-    if (map_size < 0)
+    if (map_size < 0) {
+        PyErr_SetString(PyExc_OverflowError,
+                        "memory mapped length must be postiive");
         return NULL;
+    }
     if (offset < 0) {
         PyErr_SetString(PyExc_OverflowError,
             "memory mapped offset must be positive");
@@ -1194,7 +1164,7 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
                 return NULL;
             }
             map_size = (Py_ssize_t) (status.st_size - offset);
-        } else if (offset + map_size > status.st_size) {
+        } else if (offset > status.st_size || status.st_size - offset < map_size) {
             PyErr_SetString(PyExc_ValueError,
                             "mmap length is greater than file size");
             return NULL;
@@ -1203,8 +1173,8 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
     m_obj = (mmap_object *)type->tp_alloc(type, 0);
     if (m_obj == NULL) {return NULL;}
     m_obj->data = NULL;
-    m_obj->size = (size_t) map_size;
-    m_obj->pos = (size_t) 0;
+    m_obj->size = map_size;
+    m_obj->pos = 0;
     m_obj->weakreflist = NULL;
     m_obj->exports = 0;
     m_obj->offset = offset;
@@ -1264,7 +1234,6 @@ static PyObject *
 new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
 {
     mmap_object *m_obj;
-    PyObject *map_size_obj = NULL;
     Py_ssize_t map_size;
     PY_LONG_LONG offset = 0, size;
     DWORD off_hi;       /* upper 32 bits of offset */
@@ -1281,8 +1250,8 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
                                 "tagname",
                                 "access", "offset", NULL };
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziL", keywords,
-                                     &fileno, &map_size_obj,
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "in|ziL", keywords,
+                                     &fileno, &map_size,
                                      &tagname, &access, &offset)) {
         return NULL;
     }
@@ -1305,9 +1274,11 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
                             "mmap invalid access parameter.");
     }
 
-    map_size = _GetMapSize(map_size_obj, "size");
-    if (map_size < 0)
+    if (map_size < 0) {
+        PyErr_SetString(PyExc_OverflowError,
+                        "memory mapped length must be postiive");
         return NULL;
+    }
     if (offset < 0) {
         PyErr_SetString(PyExc_OverflowError,
             "memory mapped offset must be positive");
index d2fd5c8..5423308 100644 (file)
@@ -925,11 +925,14 @@ static PyMethodDef oss_mixer_methods[] = {
 static PyObject *
 oss_getattro(oss_audio_t *self, PyObject *nameobj)
 {
-    char *name = "";
+    const char *name = "";
     PyObject * rval = NULL;
 
-    if (PyUnicode_Check(nameobj))
-        name = _PyUnicode_AsString(nameobj);
+    if (PyUnicode_Check(nameobj)) {
+        name = PyUnicode_AsUTF8(nameobj);
+        if (name == NULL)
+            return NULL;
+    }
 
     if (strcmp(name, "closed") == 0) {
         rval = (self->fd == -1) ? Py_True : Py_False;
index e5f58ab..3e446a5 100644 (file)
@@ -1515,7 +1515,9 @@ win32_xstat_impl(const char *path, struct _Py_stat_struct *result,
         /* Either the target doesn't exist, or we don't have access to
            get a handle to it. If the former, we need to return an error.
            If the latter, we can use attributes_from_dir. */
-        if (GetLastError() != ERROR_SHARING_VIOLATION)
+        DWORD lastError = GetLastError();
+        if (lastError != ERROR_ACCESS_DENIED &&
+            lastError != ERROR_SHARING_VIOLATION)
             return -1;
         /* Could not get attributes on open file. Fall back to
            reading the directory. */
@@ -1525,7 +1527,7 @@ win32_xstat_impl(const char *path, struct _Py_stat_struct *result,
         if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
             if (traverse) {
                 /* Should traverse, but could not open reparse point handle */
-                SetLastError(ERROR_SHARING_VIOLATION);
+                SetLastError(lastError);
                 return -1;
             }
         }
@@ -1605,7 +1607,9 @@ win32_xstat_impl_w(const wchar_t *path, struct _Py_stat_struct *result,
         /* Either the target doesn't exist, or we don't have access to
            get a handle to it. If the former, we need to return an error.
            If the latter, we can use attributes_from_dir. */
-        if (GetLastError() != ERROR_SHARING_VIOLATION)
+        DWORD lastError = GetLastError();
+        if (lastError != ERROR_ACCESS_DENIED &&
+            lastError != ERROR_SHARING_VIOLATION)
             return -1;
         /* Could not get attributes on open file. Fall back to
            reading the directory. */
@@ -1615,7 +1619,7 @@ win32_xstat_impl_w(const wchar_t *path, struct _Py_stat_struct *result,
         if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
             if (traverse) {
                 /* Should traverse, but could not open reparse point handle */
-                SetLastError(ERROR_SHARING_VIOLATION);
+                SetLastError(lastError);
                 return -1;
             }
         }
@@ -2483,9 +2487,8 @@ It's an error to use dir_fd or follow_symlinks when specifying path as
 [clinic start generated code]*/
 
 static PyObject *
-os_stat_impl(PyModuleDef *module, path_t *path, int dir_fd,
-             int follow_symlinks)
-/*[clinic end generated code: output=e4f7569f95d523ca input=099d356c306fa24a]*/
+os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
+/*[clinic end generated code: output=7d4976e6f18a59c5 input=099d356c306fa24a]*/
 {
     return posix_do_stat("stat", path, dir_fd, follow_symlinks);
 }
@@ -2507,8 +2510,8 @@ Equivalent to stat(path, follow_symlinks=False).
 [clinic start generated code]*/
 
 static PyObject *
-os_lstat_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=7a748e333fcb39bd input=0b7474765927b925]*/
+os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
+/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
 {
     int follow_symlinks = 0;
     return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
@@ -2518,8 +2521,8 @@ os_lstat_impl(PyModuleDef *module, path_t *path, int dir_fd)
 /*[clinic input]
 os.access -> bool
 
-    path: path_t(allow_fd=True)
-        Path to be tested; can be string, bytes, or open-file-descriptor int.
+    path: path_t
+        Path to be tested; can be string or bytes
 
     mode: int
         Operating-system mode bitfield.  Can be F_OK to test existence,
@@ -2555,9 +2558,9 @@ Note that most operations will use the effective uid/gid, therefore this
 [clinic start generated code]*/
 
 static int
-os_access_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd,
+os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
                int effective_ids, int follow_symlinks)
-/*[clinic end generated code: output=abaa53340210088d input=b75a756797af45ec]*/
+/*[clinic end generated code: output=cf84158bc90b1a77 input=8e8c3a6ba791fee3]*/
 {
     int return_value;
 
@@ -2648,8 +2651,8 @@ Return the name of the terminal device connected to 'fd'.
 [clinic start generated code]*/
 
 static char *
-os_ttyname_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=03ad3d5ccaef75c3 input=5f72ca83e76b3b45]*/
+os_ttyname_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=ed16ad216d813591 input=5f72ca83e76b3b45]*/
 {
     char *ret;
 
@@ -2668,8 +2671,8 @@ Return the name of the controlling terminal for this process.
 [clinic start generated code]*/
 
 static PyObject *
-os_ctermid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=1b73788201e0aebd input=3b87fdd52556382d]*/
+os_ctermid_impl(PyObject *module)
+/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
 {
     char *ret;
     char buffer[L_ctermid];
@@ -2699,8 +2702,8 @@ On some platforms, path may also be specified as an open file descriptor.
 [clinic start generated code]*/
 
 static PyObject *
-os_chdir_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=7358e3a20fb5aa93 input=1a4a15b4d12cb15d]*/
+os_chdir_impl(PyObject *module, path_t *path)
+/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
 {
     int result;
 
@@ -2743,8 +2746,8 @@ Equivalent to os.chdir(fd).
 [clinic start generated code]*/
 
 static PyObject *
-os_fchdir_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=361d30df6b2d3418 input=18e816479a2fa985]*/
+os_fchdir_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
 {
     return posix_fildes_fd(fd, fchdir);
 }
@@ -2784,9 +2787,9 @@ dir_fd and follow_symlinks may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_chmod_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd,
+os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
               int follow_symlinks)
-/*[clinic end generated code: output=05e7f73b1a843ba2 input=7f1618e5e15cc196]*/
+/*[clinic end generated code: output=5cf6a94915cc7bff input=7f1618e5e15cc196]*/
 {
     int result;
 
@@ -2898,8 +2901,8 @@ Equivalent to os.chmod(fd, mode).
 [clinic start generated code]*/
 
 static PyObject *
-os_fchmod_impl(PyModuleDef *module, int fd, int mode)
-/*[clinic end generated code: output=2ee31ca226d1ed33 input=8ab11975ca01ee5b]*/
+os_fchmod_impl(PyObject *module, int fd, int mode)
+/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
 {
     int res;
     int async_err = 0;
@@ -2931,8 +2934,8 @@ Equivalent to chmod(path, mode, follow_symlinks=False)."
 [clinic start generated code]*/
 
 static PyObject *
-os_lchmod_impl(PyModuleDef *module, path_t *path, int mode)
-/*[clinic end generated code: output=7c0cc46588d89e46 input=90c5663c7465d24f]*/
+os_lchmod_impl(PyObject *module, path_t *path, int mode)
+/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
 {
     int res;
     Py_BEGIN_ALLOW_THREADS
@@ -2966,9 +2969,9 @@ unavailable, using it will raise a NotImplementedError.
 [clinic start generated code]*/
 
 static PyObject *
-os_chflags_impl(PyModuleDef *module, path_t *path, unsigned long flags,
+os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
                 int follow_symlinks)
-/*[clinic end generated code: output=ff2d6e73534a95b9 input=0327e29feb876236]*/
+/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
 {
     int result;
 
@@ -3008,8 +3011,8 @@ Equivalent to chflags(path, flags, follow_symlinks=False).
 [clinic start generated code]*/
 
 static PyObject *
-os_lchflags_impl(PyModuleDef *module, path_t *path, unsigned long flags)
-/*[clinic end generated code: output=6741322fb949661b input=f9f82ea8b585ca9d]*/
+os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
+/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
 {
     int res;
     Py_BEGIN_ALLOW_THREADS
@@ -3033,8 +3036,8 @@ Change root directory to path.
 [clinic start generated code]*/
 
 static PyObject *
-os_chroot_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=b6dbfabe74ecaa9d input=14822965652c3dc3]*/
+os_chroot_impl(PyObject *module, path_t *path)
+/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
 {
     int res;
     Py_BEGIN_ALLOW_THREADS
@@ -3057,8 +3060,8 @@ Force write of fd to disk.
 [clinic start generated code]*/
 
 static PyObject *
-os_fsync_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=83a350851064aea7 input=21c3645c056967f2]*/
+os_fsync_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
 {
     return posix_fildes_fd(fd, fsync);
 }
@@ -3073,8 +3076,8 @@ Force write of everything to disk.
 [clinic start generated code]*/
 
 static PyObject *
-os_sync_impl(PyModuleDef *module)
-/*[clinic end generated code: output=ba524f656c201c40 input=84749fe5e9b404ff]*/
+os_sync_impl(PyObject *module)
+/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
 {
     Py_BEGIN_ALLOW_THREADS
     sync();
@@ -3098,8 +3101,8 @@ Force write of fd to disk without forcing update of metadata.
 [clinic start generated code]*/
 
 static PyObject *
-os_fdatasync_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=e0f04a3aff515b75 input=bc74791ee54dd291]*/
+os_fdatasync_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
 {
     return posix_fildes_fd(fd, fdatasync);
 }
@@ -3147,9 +3150,9 @@ dir_fd and follow_symlinks may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_chown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid,
+os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
               int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=e0a4559f394dbd91 input=a61cc35574814d5d]*/
+/*[clinic end generated code: output=4beadab0db5f70cd input=a61cc35574814d5d]*/
 {
     int result;
 
@@ -3217,8 +3220,8 @@ Equivalent to os.chown(fd, uid, gid).
 [clinic start generated code]*/
 
 static PyObject *
-os_fchown_impl(PyModuleDef *module, int fd, uid_t uid, gid_t gid)
-/*[clinic end generated code: output=7545abf8f6086d76 input=3af544ba1b13a0d7]*/
+os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
+/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
 {
     int res;
     int async_err = 0;
@@ -3251,8 +3254,8 @@ Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
 [clinic start generated code]*/
 
 static PyObject *
-os_lchown_impl(PyModuleDef *module, path_t *path, uid_t uid, gid_t gid)
-/*[clinic end generated code: output=bb0d2da1579ac275 input=b1c6014d563a7161]*/
+os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
+/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
 {
     int res;
     Py_BEGIN_ALLOW_THREADS
@@ -3346,8 +3349,8 @@ Return a unicode string representing the current working directory.
 [clinic start generated code]*/
 
 static PyObject *
-os_getcwd_impl(PyModuleDef *module)
-/*[clinic end generated code: output=efe3a8c0121525ea input=f069211bb70e3d39]*/
+os_getcwd_impl(PyObject *module)
+/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
 {
     return posix_getcwd(0);
 }
@@ -3360,8 +3363,8 @@ Return a bytes string representing the current working directory.
 [clinic start generated code]*/
 
 static PyObject *
-os_getcwdb_impl(PyModuleDef *module)
-/*[clinic end generated code: output=7fce42ee4b2a296a input=f6f6a378dad3d9cb]*/
+os_getcwdb_impl(PyObject *module)
+/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
 {
     return posix_getcwd(1);
 }
@@ -3397,9 +3400,9 @@ src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
 [clinic start generated code]*/
 
 static PyObject *
-os_link_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd,
+os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
              int dst_dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=f47a7e88f7b391b6 input=b0095ebbcbaa7e04]*/
+/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
 {
 #ifdef MS_WINDOWS
     BOOL result;
@@ -3738,8 +3741,8 @@ entries '.' and '..' even if they are present in the directory.
 [clinic start generated code]*/
 
 static PyObject *
-os_listdir_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=1fbe67c1f780c8b7 input=09e300416e3cd729]*/
+os_listdir_impl(PyObject *module, path_t *path)
+/*[clinic end generated code: output=293045673fcd1a75 input=09e300416e3cd729]*/
 {
 #if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
     return _listdir_windows_no_opendir(path, NULL);
@@ -3759,8 +3762,8 @@ os._getfullpathname
 [clinic start generated code]*/
 
 static PyObject *
-os__getfullpathname_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=b90b1f103b08773f input=332ed537c29d0a3e]*/
+os__getfullpathname_impl(PyObject *module, path_t *path)
+/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
 {
     if (!path->narrow)
     {
@@ -3810,8 +3813,8 @@ A helper function for samepath on windows.
 [clinic start generated code]*/
 
 static PyObject *
-os__getfinalpathname_impl(PyModuleDef *module, PyObject *path)
-/*[clinic end generated code: output=8be81a5f51a34bcf input=71d5e89334891bf4]*/
+os__getfinalpathname_impl(PyObject *module, PyObject *path)
+/*[clinic end generated code: output=9bd78d0e52782e75 input=71d5e89334891bf4]*/
 {
     HANDLE hFile;
     int buf_size;
@@ -3862,27 +3865,27 @@ os__getfinalpathname_impl(PyModuleDef *module, PyObject *path)
     return result;
 }
 
-PyDoc_STRVAR(posix__isdir__doc__,
-"Return true if the pathname refers to an existing directory.");
-
 /*[clinic input]
 os._isdir
 
     path: path_t
     /
 
+Return true if the pathname refers to an existing directory.
 [clinic start generated code]*/
 
 static PyObject *
-os__isdir_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=f17b2d4e1994b0ff input=e794f12faab62a2a]*/
+os__isdir_impl(PyObject *module, path_t *path)
+/*[clinic end generated code: output=75f56f32720836cb input=5e0800149c0ad95f]*/
 {
     DWORD attributes;
 
+    Py_BEGIN_ALLOW_THREADS
     if (!path->narrow)
         attributes = GetFileAttributesW(path->wide);
     else
         attributes = GetFileAttributesA(path->narrow);
+    Py_END_ALLOW_THREADS
 
     if (attributes == INVALID_FILE_ATTRIBUTES)
         Py_RETURN_FALSE;
@@ -3903,8 +3906,8 @@ A helper function for ismount on Win32.
 [clinic start generated code]*/
 
 static PyObject *
-os__getvolumepathname_impl(PyModuleDef *module, PyObject *path)
-/*[clinic end generated code: output=79a0ba729f956dbe input=7eacadc40acbda6b]*/
+os__getvolumepathname_impl(PyObject *module, PyObject *path)
+/*[clinic end generated code: output=cbdcbd1059ceef4c input=7eacadc40acbda6b]*/
 {
     PyObject *result;
     wchar_t *path_wchar, *mountpath=NULL;
@@ -3971,8 +3974,8 @@ The mode argument is ignored on Windows.
 [clinic start generated code]*/
 
 static PyObject *
-os_mkdir_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd)
-/*[clinic end generated code: output=8bf1f738873ef2c5 input=e965f68377e9b1ce]*/
+os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
+/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
 {
     int result;
 
@@ -4023,8 +4026,8 @@ Add increment to the priority of process and return the new priority.
 [clinic start generated code]*/
 
 static PyObject *
-os_nice_impl(PyModuleDef *module, int increment)
-/*[clinic end generated code: output=8870418a3fc07b51 input=864be2d402a21da2]*/
+os_nice_impl(PyObject *module, int increment)
+/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
 {
     int value;
 
@@ -4063,8 +4066,8 @@ Return program scheduling priority.
 [clinic start generated code]*/
 
 static PyObject *
-os_getpriority_impl(PyModuleDef *module, int which, int who)
-/*[clinic end generated code: output=4759937aa5b67ed6 input=9be615d40e2544ef]*/
+os_getpriority_impl(PyObject *module, int which, int who)
+/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
 {
     int retval;
 
@@ -4089,8 +4092,8 @@ Set program scheduling priority.
 [clinic start generated code]*/
 
 static PyObject *
-os_setpriority_impl(PyModuleDef *module, int which, int who, int priority)
-/*[clinic end generated code: output=6497d3301547e7d5 input=710ccbf65b9dc513]*/
+os_setpriority_impl(PyObject *module, int which, int who, int priority)
+/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
 {
     int retval;
 
@@ -4177,9 +4180,9 @@ src_dir_fd and dst_dir_fd, may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_rename_impl(PyModuleDef *module, path_t *src, path_t *dst, int src_dir_fd,
+os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
                int dst_dir_fd)
-/*[clinic end generated code: output=08033bb2ec27fb5f input=faa61c847912c850]*/
+/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
 {
     return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
 }
@@ -4198,9 +4201,9 @@ src_dir_fd and dst_dir_fd, may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_replace_impl(PyModuleDef *module, path_t *src, path_t *dst,
-                int src_dir_fd, int dst_dir_fd)
-/*[clinic end generated code: output=131d012eed8d3b8b input=25515dfb107c8421]*/
+os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
+                int dst_dir_fd)
+/*[clinic end generated code: output=1968c02e7857422b input=25515dfb107c8421]*/
 {
     return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
 }
@@ -4222,8 +4225,8 @@ dir_fd may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_rmdir_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=cabadec80d5a77c7 input=38c8b375ca34a7e2]*/
+os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
+/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
 {
     int result;
 
@@ -4262,8 +4265,8 @@ Execute the command in a subshell.
 [clinic start generated code]*/
 
 static long
-os_system_impl(PyModuleDef *module, Py_UNICODE *command)
-/*[clinic end generated code: output=4c3bd5abcd9c29e7 input=303f5ce97df606b0]*/
+os_system_impl(PyObject *module, Py_UNICODE *command)
+/*[clinic end generated code: output=96c4dffee36dfb48 input=303f5ce97df606b0]*/
 {
     long result;
     Py_BEGIN_ALLOW_THREADS
@@ -4281,8 +4284,8 @@ Execute the command in a subshell.
 [clinic start generated code]*/
 
 static long
-os_system_impl(PyModuleDef *module, PyObject *command)
-/*[clinic end generated code: output=800f775e10b7be55 input=86a58554ba6094af]*/
+os_system_impl(PyObject *module, PyObject *command)
+/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
 {
     long result;
     char *bytes = PyBytes_AsString(command);
@@ -4305,8 +4308,8 @@ Set the current numeric umask and return the previous umask.
 [clinic start generated code]*/
 
 static PyObject *
-os_umask_impl(PyModuleDef *module, int mask)
-/*[clinic end generated code: output=9e1fe3c9f14d6a05 input=ab6bfd9b24d8a7e8]*/
+os_umask_impl(PyObject *module, int mask)
+/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
 {
     int i = (int)umask(mask);
     if (i < 0)
@@ -4371,8 +4374,8 @@ dir_fd may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_unlink_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=474afd5cd09b237e input=d7bcde2b1b2a2552]*/
+os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
+/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
 {
     int result;
 
@@ -4414,8 +4417,8 @@ dir_fd may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_remove_impl(PyModuleDef *module, path_t *path, int dir_fd)
-/*[clinic end generated code: output=d0d5149e64832b9e input=e05c5ab55cd30983]*/
+os_remove_impl(PyObject *module, path_t *path, int dir_fd)
+/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
 {
     return os_unlink_impl(module, path, dir_fd);
 }
@@ -4460,8 +4463,8 @@ The object behaves like a named tuple with the following fields:
 [clinic start generated code]*/
 
 static PyObject *
-os_uname_impl(PyModuleDef *module)
-/*[clinic end generated code: output=01e1421b757e753f input=e68bd246db3043ed]*/
+os_uname_impl(PyObject *module)
+/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
 {
     struct utsname u;
     int res;
@@ -4710,9 +4713,9 @@ dir_fd and follow_symlinks may not be available on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_utime_impl(PyModuleDef *module, path_t *path, PyObject *times,
-              PyObject *ns, int dir_fd, int follow_symlinks)
-/*[clinic end generated code: output=31f3434e560ba2f0 input=081cdc54ca685385]*/
+os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
+              int dir_fd, int follow_symlinks)
+/*[clinic end generated code: output=cfcac69d027b82cf input=081cdc54ca685385]*/
 {
 #ifdef MS_WINDOWS
     HANDLE hFile;
@@ -4880,8 +4883,8 @@ Exit to the system with specified status, without normal exit processing.
 [clinic start generated code]*/
 
 static PyObject *
-os__exit_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=472a3cbaf68f3621 input=5e6d57556b0c4a62]*/
+os__exit_impl(PyObject *module, int status)
+/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
 {
     _exit(status);
     return NULL; /* Make gcc -Wall happy */
@@ -5036,8 +5039,8 @@ Execute an executable path with arguments, replacing current process.
 [clinic start generated code]*/
 
 static PyObject *
-os_execv_impl(PyModuleDef *module, PyObject *path, PyObject *argv)
-/*[clinic end generated code: output=9221f08143146fff input=96041559925e5229]*/
+os_execv_impl(PyObject *module, PyObject *path, PyObject *argv)
+/*[clinic end generated code: output=b21dc34deeb5b004 input=96041559925e5229]*/
 {
     char *path_char;
     char **argvlist;
@@ -5086,9 +5089,8 @@ Execute an executable path with arguments, replacing current process.
 [clinic start generated code]*/
 
 static PyObject *
-os_execve_impl(PyModuleDef *module, path_t *path, PyObject *argv,
-               PyObject *env)
-/*[clinic end generated code: output=181884fcdb21508e input=626804fa092606d9]*/
+os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
+/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
 {
     char **argvlist = NULL;
     char **envlist;
@@ -5157,8 +5159,8 @@ Execute the program specified by path in a new process.
 [clinic start generated code]*/
 
 static PyObject *
-os_spawnv_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv)
-/*[clinic end generated code: output=140a7945484c8cc5 input=042c91dfc1e6debc]*/
+os_spawnv_impl(PyObject *module, int mode, PyObject *path, PyObject *argv)
+/*[clinic end generated code: output=c427c0ce40f10638 input=042c91dfc1e6debc]*/
 {
     char *path_char;
     char **argvlist;
@@ -5184,6 +5186,16 @@ os_spawnv_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv)
                         "spawnv() arg 2 must be a tuple or list");
         return NULL;
     }
+#ifdef MS_WINDOWS
+    /* Avoid changing behavior in maintenance release, but
+       the previous Windows behavior was to crash, so this
+       is a "compatible" improvement. */
+    if (argc == 0) {
+        PyErr_SetString(PyExc_ValueError,
+                        "spawnv() arg 2 cannot be empty");
+        return NULL;
+    }
+#endif
 
     argvlist = PyMem_NEW(char *, argc+1);
     if (argvlist == NULL) {
@@ -5198,6 +5210,15 @@ os_spawnv_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv)
                 "spawnv() arg 2 must contain only strings");
             return NULL;
         }
+#ifdef MS_WINDOWS
+        if (i == 0 && !argvlist[0][0]) {
+            free_string_array(argvlist, i);
+            PyErr_SetString(
+                PyExc_ValueError,
+                "spawnv() arg 2 first element cannot be empty");
+            return NULL;
+        }
+#endif
     }
     argvlist[argc] = NULL;
 
@@ -5205,7 +5226,9 @@ os_spawnv_impl(PyModuleDef *module, int mode, PyObject *path, PyObject *argv)
         mode = _P_OVERLAY;
 
     Py_BEGIN_ALLOW_THREADS
+    _Py_BEGIN_SUPPRESS_IPH
     spawnval = _spawnv(mode, path_char, argvlist);
+    _Py_END_SUPPRESS_IPH
     Py_END_ALLOW_THREADS
 
     free_string_array(argvlist, argc);
@@ -5234,9 +5257,9 @@ Execute the program specified by path in a new process.
 [clinic start generated code]*/
 
 static PyObject *
-os_spawnve_impl(PyModuleDef *module, int mode, PyObject *path,
-                PyObject *argv, PyObject *env)
-/*[clinic end generated code: output=e7f5f0703610531f input=02362fd937963f8f]*/
+os_spawnve_impl(PyObject *module, int mode, PyObject *path, PyObject *argv,
+                PyObject *env)
+/*[clinic end generated code: output=ebcfa5f7ba2f4219 input=02362fd937963f8f]*/
 {
     char *path_char;
     char **argvlist;
@@ -5295,7 +5318,9 @@ os_spawnve_impl(PyModuleDef *module, int mode, PyObject *path,
         mode = _P_OVERLAY;
 
     Py_BEGIN_ALLOW_THREADS
+    _Py_BEGIN_SUPPRESS_IPH
     spawnval = _spawnve(mode, path_char, argvlist, envlist);
+    _Py_END_SUPPRESS_IPH
     Py_END_ALLOW_THREADS
 
     if (spawnval == -1)
@@ -5325,8 +5350,8 @@ Return 0 to child process and PID of child to parent process.
 [clinic start generated code]*/
 
 static PyObject *
-os_fork1_impl(PyModuleDef *module)
-/*[clinic end generated code: output=e27b4f66419c9dcf input=12db02167893926e]*/
+os_fork1_impl(PyObject *module)
+/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
 {
     pid_t pid;
     int result = 0;
@@ -5362,8 +5387,8 @@ Return 0 to child process and PID of child to parent process.
 [clinic start generated code]*/
 
 static PyObject *
-os_fork_impl(PyModuleDef *module)
-/*[clinic end generated code: output=898b1ecd3498ba12 input=13c956413110eeaa]*/
+os_fork_impl(PyObject *module)
+/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
 {
     pid_t pid;
     int result = 0;
@@ -5400,8 +5425,8 @@ Get the maximum scheduling priority for policy.
 [clinic start generated code]*/
 
 static PyObject *
-os_sched_get_priority_max_impl(PyModuleDef *module, int policy)
-/*[clinic end generated code: output=a6a30fa5071f2d81 input=2097b7998eca6874]*/
+os_sched_get_priority_max_impl(PyObject *module, int policy)
+/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
 {
     int max;
 
@@ -5421,8 +5446,8 @@ Get the minimum scheduling priority for policy.
 [clinic start generated code]*/
 
 static PyObject *
-os_sched_get_priority_min_impl(PyModuleDef *module, int policy)
-/*[clinic end generated code: output=5ca3ed6bc43e9b20 input=21bc8fa0d70983bf]*/
+os_sched_get_priority_min_impl(PyObject *module, int policy)
+/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
 {
     int min = sched_get_priority_min(policy);
     if (min < 0)
@@ -5444,8 +5469,8 @@ Passing 0 for pid returns the scheduling policy for the calling process.
 [clinic start generated code]*/
 
 static PyObject *
-os_sched_getscheduler_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=8cd63c15caf54fa9 input=5f14cfd1f189e1a0]*/
+os_sched_getscheduler_impl(PyObject *module, pid_t pid)
+/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=5f14cfd1f189e1a0]*/
 {
     int policy;
 
@@ -5537,9 +5562,9 @@ param is an instance of sched_param.
 [clinic start generated code]*/
 
 static PyObject *
-os_sched_setscheduler_impl(PyModuleDef *module, pid_t pid, int policy,
+os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
                            struct sched_param *param)
-/*[clinic end generated code: output=37053e5c528c35c9 input=c581f9469a5327dd]*/
+/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
 {
     /*
     ** sched_setscheduler() returns 0 in Linux, but the previous
@@ -5566,8 +5591,8 @@ Return value is an instance of sched_param.
 [clinic start generated code]*/
 
 static PyObject *
-os_sched_getparam_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=f42c5bd2604ecd08 input=18a1ef9c2efae296]*/
+os_sched_getparam_impl(PyObject *module, pid_t pid)
+/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
 {
     struct sched_param param;
     PyObject *result;
@@ -5601,9 +5626,9 @@ param should be an instance of sched_param.
 [clinic start generated code]*/
 
 static PyObject *
-os_sched_setparam_impl(PyModuleDef *module, pid_t pid,
+os_sched_setparam_impl(PyObject *module, pid_t pid,
                        struct sched_param *param)
-/*[clinic end generated code: output=b7a3c589436cec9b input=6b8d6dfcecdc21bd]*/
+/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
 {
     if (sched_setparam(pid, param))
         return posix_error();
@@ -5624,8 +5649,8 @@ Value returned is a float.
 [clinic start generated code]*/
 
 static double
-os_sched_rr_get_interval_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=7adc137a86dea581 input=2a973da15cca6fae]*/
+os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
+/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
 {
     struct timespec interval;
     if (sched_rr_get_interval(pid, &interval)) {
@@ -5644,8 +5669,8 @@ Voluntarily relinquish the CPU.
 [clinic start generated code]*/
 
 static PyObject *
-os_sched_yield_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d7bd51869c4cb6a8 input=e54d6f98189391d4]*/
+os_sched_yield_impl(PyObject *module)
+/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
 {
     if (sched_yield())
         return posix_error();
@@ -5668,8 +5693,8 @@ mask should be an iterable of integers identifying CPUs.
 [clinic start generated code]*/
 
 static PyObject *
-os_sched_setaffinity_impl(PyModuleDef *module, pid_t pid, PyObject *mask)
-/*[clinic end generated code: output=582bcbf40d3253a9 input=a0791a597c7085ba]*/
+os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
+/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
 {
     int ncpus;
     size_t setsize;
@@ -5764,8 +5789,8 @@ The affinity is returned as a set of CPU identifiers.
 [clinic start generated code]*/
 
 static PyObject *
-os_sched_getaffinity_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=b431a8f310e369e7 input=eaf161936874b8a1]*/
+os_sched_getaffinity_impl(PyObject *module, pid_t pid)
+/*[clinic end generated code: output=f726f2c193c17a4f input=eaf161936874b8a1]*/
 {
     int cpu, ncpus, count;
     size_t setsize;
@@ -5860,8 +5885,8 @@ for both the master and slave ends.
 [clinic start generated code]*/
 
 static PyObject *
-os_openpty_impl(PyModuleDef *module)
-/*[clinic end generated code: output=358e571c1ba135ee input=f3d99fd99e762907]*/
+os_openpty_impl(PyObject *module)
+/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
 {
     int master_fd = -1, slave_fd = -1;
 #ifndef HAVE_OPENPTY
@@ -5962,8 +5987,8 @@ To both, return fd of newly opened pseudo-terminal.
 [clinic start generated code]*/
 
 static PyObject *
-os_forkpty_impl(PyModuleDef *module)
-/*[clinic end generated code: output=a11b8391dce3cb57 input=f1f7f4bae3966010]*/
+os_forkpty_impl(PyObject *module)
+/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
 {
     int master_fd = -1, result = 0;
     pid_t pid;
@@ -5998,8 +6023,8 @@ Return the current process's effective group id.
 [clinic start generated code]*/
 
 static PyObject *
-os_getegid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=90f433a8c0b1d919 input=1596f79ad1107d5d]*/
+os_getegid_impl(PyObject *module)
+/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
 {
     return _PyLong_FromGid(getegid());
 }
@@ -6014,8 +6039,8 @@ Return the current process's effective user id.
 [clinic start generated code]*/
 
 static PyObject *
-os_geteuid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=1a532c4a66874357 input=4644c662d3bd9f19]*/
+os_geteuid_impl(PyObject *module)
+/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
 {
     return _PyLong_FromUid(geteuid());
 }
@@ -6030,8 +6055,8 @@ Return the current process's group id.
 [clinic start generated code]*/
 
 static PyObject *
-os_getgid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=91a22021b74ea46b input=58796344cd87c0f6]*/
+os_getgid_impl(PyObject *module)
+/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
 {
     return _PyLong_FromGid(getgid());
 }
@@ -6045,8 +6070,8 @@ Return the current process id.
 [clinic start generated code]*/
 
 static PyObject *
-os_getpid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=8fbf3a934ee09e62 input=5a9a00f0ab68aa00]*/
+os_getpid_impl(PyObject *module)
+/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
 {
     return PyLong_FromPid(getpid());
 }
@@ -6137,8 +6162,8 @@ Return list of supplemental group IDs for the process.
 [clinic start generated code]*/
 
 static PyObject *
-os_getgroups_impl(PyModuleDef *module)
-/*[clinic end generated code: output=6e7c4fd2db6d5c60 input=d3f109412e6a155c]*/
+os_getgroups_impl(PyObject *module)
+/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
 {
     PyObject *result = NULL;
 
@@ -6292,8 +6317,8 @@ Call the system call getpgid(), and return the result.
 [clinic start generated code]*/
 
 static PyObject *
-os_getpgid_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=70e713b4d54b7c61 input=39d710ae3baaf1c7]*/
+os_getpgid_impl(PyObject *module, pid_t pid)
+/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
 {
     pid_t pgid = getpgid(pid);
     if (pgid < 0)
@@ -6311,8 +6336,8 @@ Return the current process group id.
 [clinic start generated code]*/
 
 static PyObject *
-os_getpgrp_impl(PyModuleDef *module)
-/*[clinic end generated code: output=cf3403585846811f input=6846fb2bb9a3705e]*/
+os_getpgrp_impl(PyObject *module)
+/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
 {
 #ifdef GETPGRP_HAVE_ARG
     return PyLong_FromPid(getpgrp(0));
@@ -6331,8 +6356,8 @@ Make the current process the leader of its process group.
 [clinic start generated code]*/
 
 static PyObject *
-os_setpgrp_impl(PyModuleDef *module)
-/*[clinic end generated code: output=59650f55a963d7ac input=1f0619fcb5731e7e]*/
+os_setpgrp_impl(PyObject *module)
+/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
 {
 #ifdef SETPGRP_HAVE_ARG
     if (setpgrp(0, 0) < 0)
@@ -6400,8 +6425,8 @@ return its id; others systems will return the id of the 'init' process (1).
 [clinic start generated code]*/
 
 static PyObject *
-os_getppid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=4e49c8e7a8738cd2 input=e637cb87539c030e]*/
+os_getppid_impl(PyObject *module)
+/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
 {
 #ifdef MS_WINDOWS
     return win32_getppid();
@@ -6420,8 +6445,8 @@ Return the actual login name.
 [clinic start generated code]*/
 
 static PyObject *
-os_getlogin_impl(PyModuleDef *module)
-/*[clinic end generated code: output=037ebdb3e4b5dac1 input=2a21ab1e917163df]*/
+os_getlogin_impl(PyObject *module)
+/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
 {
     PyObject *result = NULL;
 #ifdef MS_WINDOWS
@@ -6463,8 +6488,8 @@ Return the current process's user id.
 [clinic start generated code]*/
 
 static PyObject *
-os_getuid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=03a8b894cefb3fa5 input=b53c8b35f110a516]*/
+os_getuid_impl(PyObject *module)
+/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
 {
     return _PyLong_FromUid(getuid());
 }
@@ -6487,8 +6512,8 @@ Kill a process with a signal.
 [clinic start generated code]*/
 
 static PyObject *
-os_kill_impl(PyModuleDef *module, pid_t pid, Py_ssize_t signal)
-/*[clinic end generated code: output=74f907dd00a83c26 input=61a36b86ca275ab9]*/
+os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
+/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
 #ifndef MS_WINDOWS
 {
     if (kill(pid, (int)signal) == -1)
@@ -6548,8 +6573,8 @@ Kill a process group with a signal.
 [clinic start generated code]*/
 
 static PyObject *
-os_killpg_impl(PyModuleDef *module, pid_t pgid, int signal)
-/*[clinic end generated code: output=3434a766ef945f93 input=38b5449eb8faec19]*/
+os_killpg_impl(PyObject *module, pid_t pgid, int signal)
+/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
 {
     /* XXX some man pages make the `pgid` parameter an int, others
        a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
@@ -6576,8 +6601,8 @@ Lock program segments into memory.");
 [clinic start generated code]*/
 
 static PyObject *
-os_plock_impl(PyModuleDef *module, int op)
-/*[clinic end generated code: output=5cb851f81b914984 input=e6e5e348e1525f60]*/
+os_plock_impl(PyObject *module, int op)
+/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
 {
     if (plock(op) == -1)
         return posix_error();
@@ -6597,8 +6622,8 @@ Set the current process's user id.
 [clinic start generated code]*/
 
 static PyObject *
-os_setuid_impl(PyModuleDef *module, uid_t uid)
-/*[clinic end generated code: output=941ea9a8d1e5d565 input=c921a3285aa22256]*/
+os_setuid_impl(PyObject *module, uid_t uid)
+/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
 {
     if (setuid(uid) < 0)
         return posix_error();
@@ -6618,8 +6643,8 @@ Set the current process's effective user id.
 [clinic start generated code]*/
 
 static PyObject *
-os_seteuid_impl(PyModuleDef *module, uid_t euid)
-/*[clinic end generated code: output=66f4f6823a648d6d input=ba93d927e4781aa9]*/
+os_seteuid_impl(PyObject *module, uid_t euid)
+/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
 {
     if (seteuid(euid) < 0)
         return posix_error();
@@ -6639,8 +6664,8 @@ Set the current process's effective group id.
 [clinic start generated code]*/
 
 static PyObject *
-os_setegid_impl(PyModuleDef *module, gid_t egid)
-/*[clinic end generated code: output=ca094a69a081a60f input=4080526d0ccd6ce3]*/
+os_setegid_impl(PyObject *module, gid_t egid)
+/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
 {
     if (setegid(egid) < 0)
         return posix_error();
@@ -6661,8 +6686,8 @@ Set the current process's real and effective user ids.
 [clinic start generated code]*/
 
 static PyObject *
-os_setreuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid)
-/*[clinic end generated code: output=b2938c3e73d27ec7 input=0ca8978de663880c]*/
+os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
+/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
 {
     if (setreuid(ruid, euid) < 0) {
         return posix_error();
@@ -6686,8 +6711,8 @@ Set the current process's real and effective group ids.
 [clinic start generated code]*/
 
 static PyObject *
-os_setregid_impl(PyModuleDef *module, gid_t rgid, gid_t egid)
-/*[clinic end generated code: output=db18f1839ababe3d input=c59499f72846db78]*/
+os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
+/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
 {
     if (setregid(rgid, egid) < 0)
         return posix_error();
@@ -6706,8 +6731,8 @@ Set the current process's group id.
 [clinic start generated code]*/
 
 static PyObject *
-os_setgid_impl(PyModuleDef *module, gid_t gid)
-/*[clinic end generated code: output=756cb42c6abd9d87 input=27d30c4059045dc6]*/
+os_setgid_impl(PyObject *module, gid_t gid)
+/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
 {
     if (setgid(gid) < 0)
         return posix_error();
@@ -6727,8 +6752,8 @@ Set the groups of the current process to list.
 [clinic start generated code]*/
 
 static PyObject *
-os_setgroups(PyModuleDef *module, PyObject *groups)
-/*[clinic end generated code: output=7945c2e3cc817c58 input=fa742ca3daf85a7e]*/
+os_setgroups(PyObject *module, PyObject *groups)
+/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
 {
     int i, len;
     gid_t grouplist[MAX_GROUPS];
@@ -6842,8 +6867,8 @@ Returns a tuple of information about the child process:
 [clinic start generated code]*/
 
 static PyObject *
-os_wait3_impl(PyModuleDef *module, int options)
-/*[clinic end generated code: output=e18af4924dc54945 input=8ac4c56956b61710]*/
+os_wait3_impl(PyObject *module, int options)
+/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
 {
     pid_t pid;
     struct rusage ru;
@@ -6879,8 +6904,8 @@ Returns a tuple of information about the child process:
 [clinic start generated code]*/
 
 static PyObject *
-os_wait4_impl(PyModuleDef *module, pid_t pid, int options)
-/*[clinic end generated code: output=714f19e6ff01e099 input=d11deed0750600ba]*/
+os_wait4_impl(PyObject *module, pid_t pid, int options)
+/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
 {
     pid_t res;
     struct rusage ru;
@@ -6921,8 +6946,8 @@ no children in a waitable state.
 [clinic start generated code]*/
 
 static PyObject *
-os_waitid_impl(PyModuleDef *module, idtype_t idtype, id_t id, int options)
-/*[clinic end generated code: output=5c0192750e22fa2e input=d8e7f76e052b7920]*/
+os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
+/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
 {
     PyObject *result;
     int res;
@@ -6976,8 +7001,8 @@ The options argument is ignored on Windows.
 [clinic start generated code]*/
 
 static PyObject *
-os_waitpid_impl(PyModuleDef *module, pid_t pid, int options)
-/*[clinic end generated code: output=5e3593353d54b15b input=0bf1666b8758fda3]*/
+os_waitpid_impl(PyObject *module, pid_t pid, int options)
+/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
 {
     pid_t res;
     int async_err = 0;
@@ -7011,8 +7036,8 @@ The options argument is ignored on Windows.
 [clinic start generated code]*/
 
 static PyObject *
-os_waitpid_impl(PyModuleDef *module, Py_intptr_t pid, int options)
-/*[clinic end generated code: output=fc1d520db019625f input=444c8f51cca5b862]*/
+os_waitpid_impl(PyObject *module, Py_intptr_t pid, int options)
+/*[clinic end generated code: output=15f1ce005a346b09 input=444c8f51cca5b862]*/
 {
     int status;
     Py_intptr_t res;
@@ -7020,7 +7045,9 @@ os_waitpid_impl(PyModuleDef *module, Py_intptr_t pid, int options)
 
     do {
         Py_BEGIN_ALLOW_THREADS
+        _Py_BEGIN_SUPPRESS_IPH
         res = _cwait(&status, pid, options);
+        _Py_END_SUPPRESS_IPH
         Py_END_ALLOW_THREADS
     } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
     if (res < 0)
@@ -7043,8 +7070,8 @@ Returns a tuple of information about the child process:
 [clinic start generated code]*/
 
 static PyObject *
-os_wait_impl(PyModuleDef *module)
-/*[clinic end generated code: output=4a7f4978393e0654 input=03b0182d4a4700ce]*/
+os_wait_impl(PyObject *module)
+/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
 {
     pid_t pid;
     int async_err = 0;
@@ -7083,7 +7110,7 @@ posix_readlink(PyObject *self, PyObject *args, PyObject *kwargs)
 {
     path_t path;
     int dir_fd = DEFAULT_DIR_FD;
-    char buffer[MAXPATHLEN];
+    char buffer[MAXPATHLEN+1];
     ssize_t length;
     PyObject *return_value = NULL;
     static char *keywords[] = {"path", "dir_fd", NULL};
@@ -7098,16 +7125,17 @@ posix_readlink(PyObject *self, PyObject *args, PyObject *kwargs)
     Py_BEGIN_ALLOW_THREADS
 #ifdef HAVE_READLINKAT
     if (dir_fd != DEFAULT_DIR_FD)
-        length = readlinkat(dir_fd, path.narrow, buffer, sizeof(buffer));
+        length = readlinkat(dir_fd, path.narrow, buffer, MAXPATHLEN);
     else
 #endif
-        length = readlink(path.narrow, buffer, sizeof(buffer));
+        length = readlink(path.narrow, buffer, MAXPATHLEN);
     Py_END_ALLOW_THREADS
 
     if (length < 0) {
         return_value = path_error(&path);
         goto exit;
     }
+    buffer[length] = '\0';
 
     if (PyUnicode_Check(path.object))
         return_value = PyUnicode_DecodeFSDefaultAndSize(buffer, length);
@@ -7371,9 +7399,9 @@ dir_fd may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_symlink_impl(PyModuleDef *module, path_t *src, path_t *dst,
+os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
                 int target_is_directory, int dir_fd)
-/*[clinic end generated code: output=a01b4bcf32403ccd input=e820ec4472547bc3]*/
+/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
 {
 #ifdef MS_WINDOWS
     DWORD result;
@@ -7521,8 +7549,8 @@ All fields are floating point numbers.
 [clinic start generated code]*/
 
 static PyObject *
-os_times_impl(PyModuleDef *module)
-/*[clinic end generated code: output=df0a63ebe6e6f091 input=2bf9df3d6ab2e48b]*/
+os_times_impl(PyObject *module)
+/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
 #ifdef MS_WINDOWS
 {
     FILETIME create, exit, kernel, user;
@@ -7575,8 +7603,8 @@ Call the system call getsid(pid) and return the result.
 [clinic start generated code]*/
 
 static PyObject *
-os_getsid_impl(PyModuleDef *module, pid_t pid)
-/*[clinic end generated code: output=a074f80c0e6bfb38 input=eeb2b923a30ce04e]*/
+os_getsid_impl(PyObject *module, pid_t pid)
+/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
 {
     int sid;
     sid = getsid(pid);
@@ -7595,8 +7623,8 @@ Call the system call setsid().
 [clinic start generated code]*/
 
 static PyObject *
-os_setsid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=398fc152ae327330 input=5fff45858e2f0776]*/
+os_setsid_impl(PyObject *module)
+/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
 {
     if (setsid() < 0)
         return posix_error();
@@ -7617,8 +7645,8 @@ Call the system call setpgid(pid, pgrp).
 [clinic start generated code]*/
 
 static PyObject *
-os_setpgid_impl(PyModuleDef *module, pid_t pid, pid_t pgrp)
-/*[clinic end generated code: output=7079a8e932912841 input=fceb395eca572e1a]*/
+os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
+/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
 {
     if (setpgid(pid, pgrp) < 0)
         return posix_error();
@@ -7638,8 +7666,8 @@ Return the process group associated with the terminal specified by fd.
 [clinic start generated code]*/
 
 static PyObject *
-os_tcgetpgrp_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=ebb6dc5f111c7dc0 input=7f6c18eac10ada86]*/
+os_tcgetpgrp_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
 {
     pid_t pgid = tcgetpgrp(fd);
     if (pgid < 0)
@@ -7661,8 +7689,8 @@ Set the process group associated with the terminal specified by fd.
 [clinic start generated code]*/
 
 static PyObject *
-os_tcsetpgrp_impl(PyModuleDef *module, int fd, pid_t pgid)
-/*[clinic end generated code: output=3e4b05177462cd22 input=5bdc997c6a619020]*/
+os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
+/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
 {
     if (tcsetpgrp(fd, pgid) < 0)
         return posix_error();
@@ -7696,9 +7724,8 @@ dir_fd may not be implemented on your platform.
 [clinic start generated code]*/
 
 static int
-os_open_impl(PyModuleDef *module, path_t *path, int flags, int mode,
-             int dir_fd)
-/*[clinic end generated code: output=47e8cc63559f5ddd input=ad8623b29acd2934]*/
+os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
+/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
 {
     int fd;
     int async_err = 0;
@@ -7759,8 +7786,8 @@ Close a file descriptor.
 [clinic start generated code]*/
 
 static PyObject *
-os_close_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=47bf2ea536445a26 input=2bc42451ca5c3223]*/
+os_close_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
 {
     int res;
     if (!_PyVerify_fd(fd))
@@ -7791,8 +7818,8 @@ Closes all file descriptors in [fd_low, fd_high), ignoring errors.
 [clinic start generated code]*/
 
 static PyObject *
-os_closerange_impl(PyModuleDef *module, int fd_low, int fd_high)
-/*[clinic end generated code: output=70e6adb95220ba96 input=5855a3d053ebd4ec]*/
+os_closerange_impl(PyObject *module, int fd_low, int fd_high)
+/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
 {
     int i;
     Py_BEGIN_ALLOW_THREADS
@@ -7816,8 +7843,8 @@ Return a duplicate of a file descriptor.
 [clinic start generated code]*/
 
 static int
-os_dup_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=f4bbac8c7652d05e input=6f10f7ea97f7852a]*/
+os_dup_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
 {
     return _Py_dup(fd);
 }
@@ -7833,8 +7860,8 @@ Duplicate file descriptor.
 [clinic start generated code]*/
 
 static PyObject *
-os_dup2_impl(PyModuleDef *module, int fd, int fd2, int inheritable)
-/*[clinic end generated code: output=9a099d95881a7923 input=76e96f511be0352f]*/
+os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
+/*[clinic end generated code: output=db832a2d872ccc5f input=76e96f511be0352f]*/
 {
     int res;
 #if defined(HAVE_DUP3) && \
@@ -7930,8 +7957,8 @@ Apply, test or remove a POSIX lock on an open file descriptor.
 [clinic start generated code]*/
 
 static PyObject *
-os_lockf_impl(PyModuleDef *module, int fd, int command, Py_off_t length)
-/*[clinic end generated code: output=25ff778f9e2fbf1b input=65da41d2106e9b79]*/
+os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
+/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
 {
     int res;
 
@@ -7962,8 +7989,8 @@ relative to the beginning of the file.
 [clinic start generated code]*/
 
 static Py_off_t
-os_lseek_impl(PyModuleDef *module, int fd, Py_off_t position, int how)
-/*[clinic end generated code: output=65d4ab96d664998c input=902654ad3f96a6d3]*/
+os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
+/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
 {
     Py_off_t result;
 
@@ -8013,8 +8040,8 @@ Read from a file descriptor.  Returns a bytes object.
 [clinic start generated code]*/
 
 static PyObject *
-os_read_impl(PyModuleDef *module, int fd, Py_ssize_t length)
-/*[clinic end generated code: output=be24f44178455e8b input=1df2eaa27c0bf1d3]*/
+os_read_impl(PyObject *module, int fd, Py_ssize_t length)
+/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
 {
     Py_ssize_t n;
     PyObject *buffer;
@@ -8125,8 +8152,8 @@ which may be less than the total capacity of all the buffers.
 [clinic start generated code]*/
 
 static Py_ssize_t
-os_readv_impl(PyModuleDef *module, int fd, PyObject *buffers)
-/*[clinic end generated code: output=00fc56ff1800059f input=e679eb5dbfa0357d]*/
+os_readv_impl(PyObject *module, int fd, PyObject *buffers)
+/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
 {
     int cnt;
     Py_ssize_t n;
@@ -8180,8 +8207,8 @@ the beginning of the file.  The file offset remains unchanged.
 [clinic start generated code]*/
 
 static PyObject *
-os_pread_impl(PyModuleDef *module, int fd, int length, Py_off_t offset)
-/*[clinic end generated code: output=90d1fed87f68fa33 input=084948dcbaa35d4c]*/
+os_pread_impl(PyObject *module, int fd, int length, Py_off_t offset)
+/*[clinic end generated code: output=435b29ee32b54a78 input=084948dcbaa35d4c]*/
 {
     Py_ssize_t n;
     int async_err = 0;
@@ -8229,8 +8256,8 @@ Write a bytes object to a file descriptor.
 [clinic start generated code]*/
 
 static Py_ssize_t
-os_write_impl(PyModuleDef *module, int fd, Py_buffer *data)
-/*[clinic end generated code: output=58845c93c9ee1dda input=3207e28963234f3c]*/
+os_write_impl(PyObject *module, int fd, Py_buffer *data)
+/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
 {
     return _Py_write(fd, data->buf, data->len);
 }
@@ -8400,8 +8427,8 @@ Equivalent to os.stat(fd).
 [clinic start generated code]*/
 
 static PyObject *
-os_fstat_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=d71fe98bf042b626 input=27e0e0ebbe5600c9]*/
+os_fstat_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
 {
     STRUCT_STAT st;
     int res;
@@ -8436,8 +8463,8 @@ connected to the slave end of a terminal.
 [clinic start generated code]*/
 
 static int
-os_isatty_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=acec9d3c29d16d33 input=08ce94aa1eaf7b5e]*/
+os_isatty_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
 {
     int return_value;
     if (!_PyVerify_fd(fd))
@@ -8460,8 +8487,8 @@ Returns a tuple of two file descriptors:
 [clinic start generated code]*/
 
 static PyObject *
-os_pipe_impl(PyModuleDef *module)
-/*[clinic end generated code: output=6b0cd3f868ec3c40 input=02535e8c8fa6c4d4]*/
+os_pipe_impl(PyObject *module)
+/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
 {
     int fds[2];
 #ifdef MS_WINDOWS
@@ -8547,8 +8574,8 @@ O_NONBLOCK, O_CLOEXEC.
 [clinic start generated code]*/
 
 static PyObject *
-os_pipe2_impl(PyModuleDef *module, int flags)
-/*[clinic end generated code: output=c15b6075d0c6b2e7 input=f261b6e7e63c6817]*/
+os_pipe2_impl(PyObject *module, int flags)
+/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
 {
     int fds[2];
     int res;
@@ -8575,8 +8602,8 @@ buffers must be a sequence of bytes-like objects.
 [clinic start generated code]*/
 
 static Py_ssize_t
-os_writev_impl(PyModuleDef *module, int fd, PyObject *buffers)
-/*[clinic end generated code: output=a48925dbf2d5c238 input=5b8d17fe4189d2fe]*/
+os_writev_impl(PyObject *module, int fd, PyObject *buffers)
+/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
 {
     int cnt;
     Py_ssize_t result;
@@ -8627,9 +8654,8 @@ current file offset.
 [clinic start generated code]*/
 
 static Py_ssize_t
-os_pwrite_impl(PyModuleDef *module, int fd, Py_buffer *buffer,
-               Py_off_t offset)
-/*[clinic end generated code: output=93aabdb40e17d325 input=19903f1b3dd26377]*/
+os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
+/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
 {
     Py_ssize_t size;
     int async_err = 0;
@@ -8672,8 +8698,8 @@ dir_fd may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_mkfifo_impl(PyModuleDef *module, path_t *path, int mode, int dir_fd)
-/*[clinic end generated code: output=8f5f5e72c630049a input=73032e98a36e0e19]*/
+os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
+/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
 {
     int result;
     int async_err = 0;
@@ -8723,9 +8749,9 @@ dir_fd may not be implemented on your platform.
 [clinic start generated code]*/
 
 static PyObject *
-os_mknod_impl(PyModuleDef *module, path_t *path, int mode, dev_t device,
+os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
               int dir_fd)
-/*[clinic end generated code: output=5151a8a9f754d272 input=ee44531551a4d83b]*/
+/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
 {
     int result;
     int async_err = 0;
@@ -8760,8 +8786,8 @@ Extracts a device major number from a raw device number.
 [clinic start generated code]*/
 
 static unsigned int
-os_major_impl(PyModuleDef *module, dev_t device)
-/*[clinic end generated code: output=ba55693ab49bac34 input=1e16a4d30c4d4462]*/
+os_major_impl(PyObject *module, dev_t device)
+/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
 {
     return major(device);
 }
@@ -8777,8 +8803,8 @@ Extracts a device minor number from a raw device number.
 [clinic start generated code]*/
 
 static unsigned int
-os_minor_impl(PyModuleDef *module, dev_t device)
-/*[clinic end generated code: output=2867219ebf274e27 input=0842c6d23f24c65e]*/
+os_minor_impl(PyObject *module, dev_t device)
+/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
 {
     return minor(device);
 }
@@ -8795,8 +8821,8 @@ Composes a raw device number from the major and minor device numbers.
 [clinic start generated code]*/
 
 static dev_t
-os_makedev_impl(PyModuleDef *module, int major, int minor)
-/*[clinic end generated code: output=7cb6264352437660 input=4b9fd8fc73cbe48f]*/
+os_makedev_impl(PyObject *module, int major, int minor)
+/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
 {
     return makedev(major, minor);
 }
@@ -8815,8 +8841,8 @@ Truncate a file, specified by file descriptor, to a specific length.
 [clinic start generated code]*/
 
 static PyObject *
-os_ftruncate_impl(PyModuleDef *module, int fd, Py_off_t length)
-/*[clinic end generated code: output=3666f401d76bf834 input=63b43641e52818f2]*/
+os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
+/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
 {
     int result;
     int async_err = 0;
@@ -8856,8 +8882,8 @@ On some platforms, path may also be specified as an open file descriptor.
 [clinic start generated code]*/
 
 static PyObject *
-os_truncate_impl(PyModuleDef *module, path_t *path, Py_off_t length)
-/*[clinic end generated code: output=f60a9e08370e9e2e input=77229cf0b50a9b77]*/
+os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
+/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
 {
     int result;
 #ifdef MS_WINDOWS
@@ -8920,9 +8946,9 @@ starting at offset bytes from the beginning and continuing for length bytes.
 [clinic start generated code]*/
 
 static PyObject *
-os_posix_fallocate_impl(PyModuleDef *module, int fd, Py_off_t offset,
+os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
                         Py_off_t length)
-/*[clinic end generated code: output=7f6f87a8c751e1b4 input=d7a2ef0ab2ca52fb]*/
+/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
 {
     int result;
     int async_err = 0;
@@ -8962,9 +8988,9 @@ POSIX_FADV_DONTNEED.
 [clinic start generated code]*/
 
 static PyObject *
-os_posix_fadvise_impl(PyModuleDef *module, int fd, Py_off_t offset,
+os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
                       Py_off_t length, int advice)
-/*[clinic end generated code: output=457ce6a67189e10d input=0fbe554edc2f04b5]*/
+/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
 {
     int result;
     int async_err = 0;
@@ -9014,8 +9040,8 @@ Change or add an environment variable.
 [clinic start generated code]*/
 
 static PyObject *
-os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value)
-/*[clinic end generated code: output=a2438cf95e5a0c1c input=ba586581c2e6105f]*/
+os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
+/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
 {
     wchar_t *env;
 
@@ -9058,8 +9084,8 @@ Change or add an environment variable.
 [clinic start generated code]*/
 
 static PyObject *
-os_putenv_impl(PyModuleDef *module, PyObject *name, PyObject *value)
-/*[clinic end generated code: output=a2438cf95e5a0c1c input=a97bc6152f688d31]*/
+os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
+/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
 {
     PyObject *bytes = NULL;
     char *env;
@@ -9095,8 +9121,8 @@ Delete an environment variable.
 [clinic start generated code]*/
 
 static PyObject *
-os_unsetenv_impl(PyModuleDef *module, PyObject *name)
-/*[clinic end generated code: output=25994b57016a2dc9 input=2bb5288a599c7107]*/
+os_unsetenv_impl(PyObject *module, PyObject *name)
+/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
 {
 #ifndef HAVE_BROKEN_UNSETENV
     int err;
@@ -9134,8 +9160,8 @@ Translate an error code to a message string.
 [clinic start generated code]*/
 
 static PyObject *
-os_strerror_impl(PyModuleDef *module, int code)
-/*[clinic end generated code: output=0280c6af51e5c9fe input=75a8673d97915a91]*/
+os_strerror_impl(PyObject *module, int code)
+/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
 {
     char *message = strerror(code);
     if (message == NULL) {
@@ -9159,8 +9185,8 @@ Return True if the process returning status was dumped to a core file.
 [clinic start generated code]*/
 
 static int
-os_WCOREDUMP_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=134f70bbe63fbf41 input=8b05e7ab38528d04]*/
+os_WCOREDUMP_impl(PyObject *module, int status)
+/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -9182,8 +9208,8 @@ job control stop.
 [clinic start generated code]*/
 
 static int
-os_WIFCONTINUED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=9cdd26543ebb6dcd input=e777e7d38eb25bd9]*/
+os_WIFCONTINUED_impl(PyObject *module, int status)
+/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -9202,8 +9228,8 @@ Return True if the process returning status was stopped.
 [clinic start generated code]*/
 
 static int
-os_WIFSTOPPED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=73bf35e44994a724 input=043cb7f1289ef904]*/
+os_WIFSTOPPED_impl(PyObject *module, int status)
+/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -9222,8 +9248,8 @@ Return True if the process returning status was terminated by a signal.
 [clinic start generated code]*/
 
 static int
-os_WIFSIGNALED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=2697975771872420 input=d55ba7cc9ce5dc43]*/
+os_WIFSIGNALED_impl(PyObject *module, int status)
+/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -9242,8 +9268,8 @@ Return True if the process returning status exited via the exit() system call.
 [clinic start generated code]*/
 
 static int
-os_WIFEXITED_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=ca8f8c61f0b8532e input=d63775a6791586c0]*/
+os_WIFEXITED_impl(PyObject *module, int status)
+/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -9262,8 +9288,8 @@ Return the process return code from status.
 [clinic start generated code]*/
 
 static int
-os_WEXITSTATUS_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=ea54da23d9e0f6af input=e1fb4944e377585b]*/
+os_WEXITSTATUS_impl(PyObject *module, int status)
+/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -9282,8 +9308,8 @@ Return the signal that terminated the process that provided the status value.
 [clinic start generated code]*/
 
 static int
-os_WTERMSIG_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=4d25367026cb852c input=727fd7f84ec3f243]*/
+os_WTERMSIG_impl(PyObject *module, int status)
+/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -9302,8 +9328,8 @@ Return the signal that stopped the process that provided the status value.
 [clinic start generated code]*/
 
 static int
-os_WSTOPSIG_impl(PyModuleDef *module, int status)
-/*[clinic end generated code: output=54eb9c13b001adb4 input=46ebf1d1b293c5c1]*/
+os_WSTOPSIG_impl(PyObject *module, int status)
+/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
 {
     WAIT_TYPE wait_status;
     WAIT_STATUS_INT(wait_status) = status;
@@ -9376,8 +9402,8 @@ Equivalent to statvfs(fd).
 [clinic start generated code]*/
 
 static PyObject *
-os_fstatvfs_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=584a94a754497ac0 input=d8122243ac50975e]*/
+os_fstatvfs_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
 {
     int result;
     int async_err = 0;
@@ -9412,8 +9438,8 @@ On some platforms, path may also be specified as an open file descriptor.
 [clinic start generated code]*/
 
 static PyObject *
-os_statvfs_impl(PyModuleDef *module, path_t *path)
-/*[clinic end generated code: output=5ced07a2cf931f41 input=3f5c35791c669bd9]*/
+os_statvfs_impl(PyObject *module, path_t *path)
+/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
 {
     int result;
     struct statvfs st;
@@ -9454,8 +9480,8 @@ Return disk usage statistics about the given path as a (total, free) tuple.
 [clinic start generated code]*/
 
 static PyObject *
-os__getdiskusage_impl(PyModuleDef *module, Py_UNICODE *path)
-/*[clinic end generated code: output=60a9cf33449db1dd input=6458133aed893c78]*/
+os__getdiskusage_impl(PyObject *module, Py_UNICODE *path)
+/*[clinic end generated code: output=76d6adcd86b1db0b input=6458133aed893c78]*/
 {
     BOOL retval;
     ULARGE_INTEGER _, total, free;
@@ -9640,8 +9666,8 @@ If there is no limit, return -1.
 [clinic start generated code]*/
 
 static long
-os_fpathconf_impl(PyModuleDef *module, int fd, int name)
-/*[clinic end generated code: output=082b2922d4441de7 input=5942a024d3777810]*/
+os_fpathconf_impl(PyObject *module, int fd, int name)
+/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
 {
     long limit;
 
@@ -9669,8 +9695,8 @@ On some platforms, path may also be specified as an open file descriptor.
 [clinic start generated code]*/
 
 static long
-os_pathconf_impl(PyModuleDef *module, path_t *path, int name)
-/*[clinic end generated code: output=3713029e9501f5ab input=bc3e2a985af27e5e]*/
+os_pathconf_impl(PyObject *module, path_t *path, int name)
+/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
 {
     long limit;
 
@@ -9866,8 +9892,8 @@ Return a string-valued system configuration variable.
 [clinic start generated code]*/
 
 static PyObject *
-os_confstr_impl(PyModuleDef *module, int name)
-/*[clinic end generated code: output=6ff79c9eed8c2daf input=18fb4d0567242e65]*/
+os_confstr_impl(PyObject *module, int name)
+/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
 {
     PyObject *result = NULL;
     char buffer[255];
@@ -10416,8 +10442,8 @@ Return an integer-valued system configuration variable.
 [clinic start generated code]*/
 
 static long
-os_sysconf_impl(PyModuleDef *module, int name)
-/*[clinic end generated code: output=ed567306f58d69c4 input=279e3430a33f29e4]*/
+os_sysconf_impl(PyObject *module, int name)
+/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
 {
     long value;
 
@@ -10514,8 +10540,8 @@ on the hosting operating system.  This function never returns.
 [clinic start generated code]*/
 
 static PyObject *
-os_abort_impl(PyModuleDef *module)
-/*[clinic end generated code: output=486bb96647c299b3 input=cf2c7d98bc504047]*/
+os_abort_impl(PyObject *module)
+/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
 {
     abort();
     /*NOTREACHED*/
@@ -10672,8 +10698,8 @@ Raises OSError if the load average was unobtainable.
 [clinic start generated code]*/
 
 static PyObject *
-os_getloadavg_impl(PyModuleDef *module)
-/*[clinic end generated code: output=2b64c5b675d74c14 input=3d6d826b76d8a34e]*/
+os_getloadavg_impl(PyObject *module)
+/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
 {
     double loadavg[3];
     if (getloadavg(loadavg, 3)!=3) {
@@ -10696,8 +10722,8 @@ If the device is not a terminal, return None.
 [clinic start generated code]*/
 
 static PyObject *
-os_device_encoding_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=34f14e33468419c1 input=9e1d4a42b66df312]*/
+os_device_encoding_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
 {
     return _Py_device_encoding(fd);
 }
@@ -10716,8 +10742,8 @@ Set the current process's real, effective, and saved user ids.
 [clinic start generated code]*/
 
 static PyObject *
-os_setresuid_impl(PyModuleDef *module, uid_t ruid, uid_t euid, uid_t suid)
-/*[clinic end generated code: output=92cc330812c6ed0f input=9e33cb79a82792f3]*/
+os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
+/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
 {
     if (setresuid(ruid, euid, suid) < 0)
         return posix_error();
@@ -10739,8 +10765,8 @@ Set the current process's real, effective, and saved group ids.
 [clinic start generated code]*/
 
 static PyObject *
-os_setresgid_impl(PyModuleDef *module, gid_t rgid, gid_t egid, gid_t sgid)
-/*[clinic end generated code: output=e91dc4842a604429 input=33e9e0785ef426b1]*/
+os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
+/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
 {
     if (setresgid(rgid, egid, sgid) < 0)
         return posix_error();
@@ -10757,8 +10783,8 @@ Return a tuple of the current process's real, effective, and saved user ids.
 [clinic start generated code]*/
 
 static PyObject *
-os_getresuid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=9ddef62faae8e477 input=41ccfa8e1f6517ad]*/
+os_getresuid_impl(PyObject *module)
+/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
 {
     uid_t ruid, euid, suid;
     if (getresuid(&ruid, &euid, &suid) < 0)
@@ -10778,8 +10804,8 @@ Return a tuple of the current process's real, effective, and saved group ids.
 [clinic start generated code]*/
 
 static PyObject *
-os_getresgid_impl(PyModuleDef *module)
-/*[clinic end generated code: output=e1a553cbcf16234c input=517e68db9ca32df6]*/
+os_getresgid_impl(PyObject *module)
+/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
 {
     gid_t rgid, egid, sgid;
     if (getresgid(&rgid, &egid, &sgid) < 0)
@@ -10810,9 +10836,9 @@ If follow_symlinks is False, and the last element of the path is a symbolic
 [clinic start generated code]*/
 
 static PyObject *
-os_getxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute,
+os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
                  int follow_symlinks)
-/*[clinic end generated code: output=cf2cede74bd5d412 input=8c8ea3bab78d89c2]*/
+/*[clinic end generated code: output=5f2f44200a43cff2 input=8c8ea3bab78d89c2]*/
 {
     Py_ssize_t i;
     PyObject *buffer = NULL;
@@ -10882,9 +10908,9 @@ If follow_symlinks is False, and the last element of the path is a symbolic
 [clinic start generated code]*/
 
 static PyObject *
-os_setxattr_impl(PyModuleDef *module, path_t *path, path_t *attribute,
+os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
                  Py_buffer *value, int flags, int follow_symlinks)
-/*[clinic end generated code: output=1b395ef82880fea0 input=f0d26833992015c2]*/
+/*[clinic end generated code: output=98b83f63fdde26bb input=f0d26833992015c2]*/
 {
     ssize_t result;
 
@@ -10930,9 +10956,9 @@ If follow_symlinks is False, and the last element of the path is a symbolic
 [clinic start generated code]*/
 
 static PyObject *
-os_removexattr_impl(PyModuleDef *module, path_t *path, path_t *attribute,
+os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
                     int follow_symlinks)
-/*[clinic end generated code: output=f92bb39ab992650d input=cdb54834161e3329]*/
+/*[clinic end generated code: output=521a51817980cda6 input=cdb54834161e3329]*/
 {
     ssize_t result;
 
@@ -10973,8 +10999,8 @@ If follow_symlinks is False, and the last element of the path is a symbolic
 [clinic start generated code]*/
 
 static PyObject *
-os_listxattr_impl(PyModuleDef *module, path_t *path, int follow_symlinks)
-/*[clinic end generated code: output=a87ad6ce56e42a4f input=08cca53ac0b07c13]*/
+os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
+/*[clinic end generated code: output=bebdb4e2ad0ce435 input=08cca53ac0b07c13]*/
 {
     Py_ssize_t i;
     PyObject *result = NULL;
@@ -11067,8 +11093,8 @@ Return a bytes object containing random bytes suitable for cryptographic use.
 [clinic start generated code]*/
 
 static PyObject *
-os_urandom_impl(PyModuleDef *module, Py_ssize_t size)
-/*[clinic end generated code: output=e0011f021501f03b input=4067cdb1b6776c29]*/
+os_urandom_impl(PyObject *module, Py_ssize_t size)
+/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
 {
     PyObject *bytes;
     int result;
@@ -11204,8 +11230,8 @@ Return the number of CPUs in the system; return None if indeterminable.
 [clinic start generated code]*/
 
 static PyObject *
-os_cpu_count_impl(PyModuleDef *module)
-/*[clinic end generated code: output=c59ee7f6bce832b8 input=d55e2f8f3823a628]*/
+os_cpu_count_impl(PyObject *module)
+/*[clinic end generated code: output=5fc29463c3936a9c input=d55e2f8f3823a628]*/
 {
     int ncpu = 0;
 #ifdef MS_WINDOWS
@@ -11245,8 +11271,8 @@ Get the close-on-exe flag of the specified file descriptor.
 [clinic start generated code]*/
 
 static int
-os_get_inheritable_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=36110bb36efaa21e input=89ac008dc9ab6b95]*/
+os_get_inheritable_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
 {
     int return_value;
     if (!_PyVerify_fd(fd)) {
@@ -11271,8 +11297,8 @@ Set the inheritable flag of the specified file descriptor.
 [clinic start generated code]*/
 
 static PyObject *
-os_set_inheritable_impl(PyModuleDef *module, int fd, int inheritable)
-/*[clinic end generated code: output=2ac5c6ce8623f045 input=9ceaead87a1e2402]*/
+os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
+/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
 {
     int result;
     if (!_PyVerify_fd(fd))
@@ -11297,8 +11323,8 @@ Get the close-on-exe flag of the specified file descriptor.
 [clinic start generated code]*/
 
 static int
-os_get_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle)
-/*[clinic end generated code: output=3b7b3e1b43f312b6 input=5f7759443aae3dc5]*/
+os_get_handle_inheritable_impl(PyObject *module, Py_intptr_t handle)
+/*[clinic end generated code: output=9e5389b0aa0916ce input=5f7759443aae3dc5]*/
 {
     DWORD flags;
 
@@ -11321,9 +11347,9 @@ Set the inheritable flag of the specified handle.
 [clinic start generated code]*/
 
 static PyObject *
-os_set_handle_inheritable_impl(PyModuleDef *module, Py_intptr_t handle,
+os_set_handle_inheritable_impl(PyObject *module, Py_intptr_t handle,
                                int inheritable)
-/*[clinic end generated code: output=d2e111a96c9eb296 input=e64b2b2730469def]*/
+/*[clinic end generated code: output=b1e67bfa3213d745 input=e64b2b2730469def]*/
 {
     DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
     if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
@@ -12752,9 +12778,15 @@ all_ins(PyObject *m)
 #endif
 
 #ifdef HAVE_SCHED_H
+#ifdef SCHED_OTHER
     if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
+#endif
+#ifdef SCHED_FIFO
     if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
+#endif
+#ifdef SCHED_RR
     if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
+#endif
 #ifdef SCHED_SPORADIC
     if (PyModule_AddIntMacro(m, SCHED_SPORADIC) return -1;
 #endif
index 281c30b..7416cf7 100644 (file)
@@ -105,8 +105,8 @@ See `help(pwd)` for more on password database entries.
 [clinic start generated code]*/
 
 static PyObject *
-pwd_getpwuid(PyModuleDef *module, PyObject *uidobj)
-/*[clinic end generated code: output=cba29ae4c2bcb8e1 input=ae64d507a1c6d3e8]*/
+pwd_getpwuid(PyObject *module, PyObject *uidobj)
+/*[clinic end generated code: output=c4ee1d4d429b86c4 input=ae64d507a1c6d3e8]*/
 {
     uid_t uid;
     struct passwd *p;
@@ -141,8 +141,8 @@ See `help(pwd)` for more on password database entries.
 [clinic start generated code]*/
 
 static PyObject *
-pwd_getpwnam_impl(PyModuleDef *module, PyObject *arg)
-/*[clinic end generated code: output=66848d42d386fca3 input=d5f7e700919b02d3]*/
+pwd_getpwnam_impl(PyObject *module, PyObject *arg)
+/*[clinic end generated code: output=6abeee92430e43d2 input=d5f7e700919b02d3]*/
 {
     char *name;
     struct passwd *p;
@@ -173,8 +173,8 @@ See help(pwd) for more on password database entries.
 [clinic start generated code]*/
 
 static PyObject *
-pwd_getpwall_impl(PyModuleDef *module)
-/*[clinic end generated code: output=ab30e37bf26d431d input=d7ecebfd90219b85]*/
+pwd_getpwall_impl(PyObject *module)
+/*[clinic end generated code: output=4853d2f5a0afac8a input=d7ecebfd90219b85]*/
 {
     PyObject *d;
     struct passwd *p;
index 9a6da73..00c96a1 100644 (file)
@@ -1247,8 +1247,7 @@ handlername2int(PyObject *name)
 {
     int i;
     for (i = 0; handler_info[i].name != NULL; i++) {
-        if (PyUnicode_CompareWithASCIIString(
-                name, handler_info[i].name) == 0) {
+        if (_PyUnicode_EqualToASCIIString(name, handler_info[i].name)) {
             return i;
         }
     }
@@ -1286,45 +1285,45 @@ xmlparse_getattro(xmlparseobject *self, PyObject *nameobj)
 
     first_char = PyUnicode_READ_CHAR(nameobj, 0);
     if (first_char == 'E') {
-        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorCode") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "ErrorCode"))
             return PyLong_FromLong((long)
                                   XML_GetErrorCode(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorLineNumber") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "ErrorLineNumber"))
             return PyLong_FromLong((long)
                                   XML_GetErrorLineNumber(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorColumnNumber") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "ErrorColumnNumber"))
             return PyLong_FromLong((long)
                                   XML_GetErrorColumnNumber(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorByteIndex") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "ErrorByteIndex"))
             return PyLong_FromLong((long)
                                   XML_GetErrorByteIndex(self->itself));
     }
     if (first_char == 'C') {
-        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentLineNumber") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "CurrentLineNumber"))
             return PyLong_FromLong((long)
                                   XML_GetCurrentLineNumber(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentColumnNumber") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "CurrentColumnNumber"))
             return PyLong_FromLong((long)
                                   XML_GetCurrentColumnNumber(self->itself));
-        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentByteIndex") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "CurrentByteIndex"))
             return PyLong_FromLong((long)
                                   XML_GetCurrentByteIndex(self->itself));
     }
     if (first_char == 'b') {
-        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_size") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "buffer_size"))
             return PyLong_FromLong((long) self->buffer_size);
-        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_text") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "buffer_text"))
             return get_pybool(self->buffer != NULL);
-        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_used") == 0)
+        if (_PyUnicode_EqualToASCIIString(nameobj, "buffer_used"))
             return PyLong_FromLong((long) self->buffer_used);
     }
-    if (PyUnicode_CompareWithASCIIString(nameobj, "namespace_prefixes") == 0)
+    if (_PyUnicode_EqualToASCIIString(nameobj, "namespace_prefixes"))
         return get_pybool(self->ns_prefixes);
-    if (PyUnicode_CompareWithASCIIString(nameobj, "ordered_attributes") == 0)
+    if (_PyUnicode_EqualToASCIIString(nameobj, "ordered_attributes"))
         return get_pybool(self->ordered_attributes);
-    if (PyUnicode_CompareWithASCIIString(nameobj, "specified_attributes") == 0)
+    if (_PyUnicode_EqualToASCIIString(nameobj, "specified_attributes"))
         return get_pybool((long) self->specified_attributes);
-    if (PyUnicode_CompareWithASCIIString(nameobj, "intern") == 0) {
+    if (_PyUnicode_EqualToASCIIString(nameobj, "intern")) {
         if (self->intern == NULL) {
             Py_INCREF(Py_None);
             return Py_None;
@@ -1388,7 +1387,7 @@ xmlparse_setattro(xmlparseobject *self, PyObject *name, PyObject *v)
         PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
         return -1;
     }
-    if (PyUnicode_CompareWithASCIIString(name, "buffer_text") == 0) {
+    if (_PyUnicode_EqualToASCIIString(name, "buffer_text")) {
         int b = PyObject_IsTrue(v);
         if (b < 0)
             return -1;
@@ -1410,7 +1409,7 @@ xmlparse_setattro(xmlparseobject *self, PyObject *name, PyObject *v)
         }
         return 0;
     }
-    if (PyUnicode_CompareWithASCIIString(name, "namespace_prefixes") == 0) {
+    if (_PyUnicode_EqualToASCIIString(name, "namespace_prefixes")) {
         int b = PyObject_IsTrue(v);
         if (b < 0)
             return -1;
@@ -1418,14 +1417,14 @@ xmlparse_setattro(xmlparseobject *self, PyObject *name, PyObject *v)
         XML_SetReturnNSTriplet(self->itself, self->ns_prefixes);
         return 0;
     }
-    if (PyUnicode_CompareWithASCIIString(name, "ordered_attributes") == 0) {
+    if (_PyUnicode_EqualToASCIIString(name, "ordered_attributes")) {
         int b = PyObject_IsTrue(v);
         if (b < 0)
             return -1;
         self->ordered_attributes = b;
         return 0;
     }
-    if (PyUnicode_CompareWithASCIIString(name, "specified_attributes") == 0) {
+    if (_PyUnicode_EqualToASCIIString(name, "specified_attributes")) {
         int b = PyObject_IsTrue(v);
         if (b < 0)
             return -1;
@@ -1433,7 +1432,7 @@ xmlparse_setattro(xmlparseobject *self, PyObject *name, PyObject *v)
         return 0;
     }
 
-    if (PyUnicode_CompareWithASCIIString(name, "buffer_size") == 0) {
+    if (_PyUnicode_EqualToASCIIString(name, "buffer_size")) {
       long new_buffer_size;
       if (!PyLong_Check(v)) {
         PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
@@ -1479,7 +1478,7 @@ xmlparse_setattro(xmlparseobject *self, PyObject *name, PyObject *v)
       return 0;
     }
 
-    if (PyUnicode_CompareWithASCIIString(name, "CharacterDataHandler") == 0) {
+    if (_PyUnicode_EqualToASCIIString(name, "CharacterDataHandler")) {
         /* If we're changing the character data handler, flush all
          * cached data with the old handler.  Not sure there's a
          * "right" thing to do, though, but this probably won't
@@ -1560,9 +1559,9 @@ Return a new XML parser object.
 [clinic start generated code]*/
 
 static PyObject *
-pyexpat_ParserCreate_impl(PyModuleDef *module, const char *encoding,
+pyexpat_ParserCreate_impl(PyObject *module, const char *encoding,
                           const char *namespace_separator, PyObject *intern)
-/*[clinic end generated code: output=81fccd233e1743a8 input=23d29704acad385d]*/
+/*[clinic end generated code: output=295c0cf01ab1146c input=23d29704acad385d]*/
 {
     PyObject *result;
     int intern_decref = 0;
@@ -1606,8 +1605,8 @@ Returns string error for given number.
 [clinic start generated code]*/
 
 static PyObject *
-pyexpat_ErrorString_impl(PyModuleDef *module, long code)
-/*[clinic end generated code: output=d87668108b6868e5 input=cc67de010d9e62b3]*/
+pyexpat_ErrorString_impl(PyObject *module, long code)
+/*[clinic end generated code: output=2feae50d166f2174 input=cc67de010d9e62b3]*/
 {
     return Py_BuildValue("z", XML_ErrorString((int)code));
 }
index 8c00dec..54f15bc 100644 (file)
@@ -128,20 +128,40 @@ static PyModuleDef readlinemodule;
 #define readlinestate_global ((readlinestate *)PyModule_GetState(PyState_FindModule(&readlinemodule)))
 
 
+/* Convert to/from multibyte C strings */
+
+static PyObject *
+encode(PyObject *b)
+{
+    return PyUnicode_EncodeLocale(b, "surrogateescape");
+}
+
+static PyObject *
+decode(const char *s)
+{
+    return PyUnicode_DecodeLocale(s, "surrogateescape");
+}
+
+
 /* Exported function to send one line to readline's init file parser */
 
 static PyObject *
-parse_and_bind(PyObject *self, PyObject *args)
+parse_and_bind(PyObject *self, PyObject *string)
 {
-    char *s, *copy;
-    if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
+    char *copy;
+    PyObject *encoded = encode(string);
+    if (encoded == NULL) {
         return NULL;
+    }
     /* Make a copy -- rl_parse_and_bind() modifies its argument */
     /* Bernard Herzog */
-    copy = PyMem_Malloc(1 + strlen(s));
-    if (copy == NULL)
+    copy = PyMem_Malloc(1 + PyBytes_GET_SIZE(encoded));
+    if (copy == NULL) {
+        Py_DECREF(encoded);
         return PyErr_NoMemory();
-    strcpy(copy, s);
+    }
+    strcpy(copy, PyBytes_AS_STRING(encoded));
+    Py_DECREF(encoded);
     rl_parse_and_bind(copy);
     PyMem_Free(copy); /* Free the copy */
     Py_RETURN_NONE;
@@ -441,17 +461,18 @@ get the ending index of the completion scope");
 /* Set the tab-completion word-delimiters that readline uses */
 
 static PyObject *
-set_completer_delims(PyObject *self, PyObject *args)
+set_completer_delims(PyObject *self, PyObject *string)
 {
     char *break_chars;
-
-    if (!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
+    PyObject *encoded = encode(string);
+    if (encoded == NULL) {
         return NULL;
     }
     /* Keep a reference to the allocated memory in the module state in case
        some other module modifies rl_completer_word_break_characters
        (see issue #17289). */
-    break_chars = strdup(break_chars);
+    break_chars = strdup(PyBytes_AS_STRING(encoded));
+    Py_DECREF(encoded);
     if (break_chars) {
         free(completer_word_break_characters);
         completer_word_break_characters = break_chars;
@@ -531,10 +552,11 @@ static PyObject *
 py_replace_history(PyObject *self, PyObject *args)
 {
     int entry_number;
-    char *line;
+    PyObject *line;
+    PyObject *encoded;
     HIST_ENTRY *old_entry;
 
-    if (!PyArg_ParseTuple(args, "is:replace_history_item", &entry_number,
+    if (!PyArg_ParseTuple(args, "iU:replace_history_item", &entry_number,
                           &line)) {
         return NULL;
     }
@@ -543,7 +565,12 @@ py_replace_history(PyObject *self, PyObject *args)
                         "History index cannot be negative");
         return NULL;
     }
-    old_entry = replace_history_entry(entry_number, line, (void *)NULL);
+    encoded = encode(line);
+    if (encoded == NULL) {
+        return NULL;
+    }
+    old_entry = replace_history_entry(entry_number, PyBytes_AS_STRING(encoded), (void *)NULL);
+    Py_DECREF(encoded);
     if (!old_entry) {
         PyErr_Format(PyExc_ValueError,
                      "No history item at position %d",
@@ -562,14 +589,14 @@ replaces history item given by its position with contents of line");
 /* Add a line to the history buffer */
 
 static PyObject *
-py_add_history(PyObject *self, PyObject *args)
+py_add_history(PyObject *self, PyObject *string)
 {
-    char *line;
-
-    if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
+    PyObject *encoded = encode(string);
+    if (encoded == NULL) {
         return NULL;
     }
-    add_history(line);
+    add_history(PyBytes_AS_STRING(encoded));
+    Py_DECREF(encoded);
     Py_RETURN_NONE;
 }
 
@@ -583,7 +610,7 @@ add an item to the history buffer");
 static PyObject *
 get_completer_delims(PyObject *self, PyObject *noarg)
 {
-    return PyUnicode_FromString(rl_completer_word_break_characters);
+    return decode(rl_completer_word_break_characters);
 }
 
 PyDoc_STRVAR(doc_get_completer_delims,
@@ -673,7 +700,7 @@ get_history_item(PyObject *self, PyObject *args)
     }
 #endif /* __APPLE__ */
     if ((hist_ent = history_get(idx)))
-        return PyUnicode_FromString(hist_ent->line);
+        return decode(hist_ent->line);
     else {
         Py_RETURN_NONE;
     }
@@ -702,7 +729,7 @@ return the current (not the maximum) length of history.");
 static PyObject *
 get_line_buffer(PyObject *self, PyObject *noarg)
 {
-    return PyUnicode_FromString(rl_line_buffer);
+    return decode(rl_line_buffer);
 }
 
 PyDoc_STRVAR(doc_get_line_buffer,
@@ -730,12 +757,14 @@ Clear the current readline history.");
 /* Exported function to insert text into the line buffer */
 
 static PyObject *
-insert_text(PyObject *self, PyObject *args)
+insert_text(PyObject *self, PyObject *string)
 {
-    char *s;
-    if (!PyArg_ParseTuple(args, "s:insert_text", &s))
+    PyObject *encoded = encode(string);
+    if (encoded == NULL) {
         return NULL;
-    rl_insert_text(s);
+    }
+    rl_insert_text(PyBytes_AS_STRING(encoded));
+    Py_DECREF(encoded);
     Py_RETURN_NONE;
 }
 
@@ -763,9 +792,9 @@ contents of the line buffer.");
 
 static struct PyMethodDef readline_methods[] =
 {
-    {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
+    {"parse_and_bind", parse_and_bind, METH_O, doc_parse_and_bind},
     {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
-    {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
+    {"insert_text", insert_text, METH_O, doc_insert_text},
     {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
     {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
     {"read_history_file", read_history_file,
@@ -792,8 +821,8 @@ static struct PyMethodDef readline_methods[] =
     {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
 
     {"set_completer_delims", set_completer_delims,
-     METH_VARARGS, doc_set_completer_delims},
-    {"add_history", py_add_history, METH_VARARGS, doc_add_history},
+     METH_O, doc_set_completer_delims},
+    {"add_history", py_add_history, METH_O, doc_add_history},
     {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
     {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
     {"get_completer_delims", get_completer_delims,
@@ -890,7 +919,7 @@ on_completion_display_matches_hook(char **matches,
                                    int num_matches, int max_length)
 {
     int i;
-    PyObject *m=NULL, *s=NULL, *r=NULL;
+    PyObject *sub, *m=NULL, *s=NULL, *r=NULL;
 #ifdef WITH_THREAD
     PyGILState_STATE gilstate = PyGILState_Ensure();
 #endif
@@ -898,16 +927,17 @@ on_completion_display_matches_hook(char **matches,
     if (m == NULL)
         goto error;
     for (i = 0; i < num_matches; i++) {
-        s = PyUnicode_FromString(matches[i+1]);
+        s = decode(matches[i+1]);
         if (s == NULL)
             goto error;
         if (PyList_SetItem(m, i, s) == -1)
             goto error;
     }
+    sub = decode(matches[0]);
     r = PyObject_CallFunction(readlinestate_global->completion_display_matches_hook,
-                              "sOi", matches[0], m, max_length);
+                              "NNi", sub, m, max_length);
 
-    Py_DECREF(m); m=NULL;
+    m=NULL;
 
     if (r == NULL ||
         (r != Py_None && PyLong_AsLong(r) == -1 && PyErr_Occurred())) {
@@ -955,22 +985,24 @@ on_completion(const char *text, int state)
 {
     char *result = NULL;
     if (readlinestate_global->completer != NULL) {
-        PyObject *r;
+        PyObject *r = NULL, *t;
 #ifdef WITH_THREAD
         PyGILState_STATE gilstate = PyGILState_Ensure();
 #endif
         rl_attempted_completion_over = 1;
-        r = PyObject_CallFunction(readlinestate_global->completer, "si", text, state);
+        t = decode(text);
+        r = PyObject_CallFunction(readlinestate_global->completer, "Ni", t, state);
         if (r == NULL)
             goto error;
         if (r == Py_None) {
             result = NULL;
         }
         else {
-            char *s = _PyUnicode_AsString(r);
-            if (s == NULL)
+            PyObject *encoded = encode(r);
+            if (encoded == NULL)
                 goto error;
-            result = strdup(s);
+            result = strdup(PyBytes_AS_STRING(encoded));
+            Py_DECREF(encoded);
         }
         Py_DECREF(r);
         goto done;
@@ -994,6 +1026,9 @@ static char **
 flex_complete(const char *text, int start, int end)
 {
     char **result;
+    char saved;
+    size_t start_size, end_size;
+    wchar_t *s;
 #ifdef WITH_THREAD
     PyGILState_STATE gilstate = PyGILState_Ensure();
 #endif
@@ -1003,11 +1038,32 @@ flex_complete(const char *text, int start, int end)
 #ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
     rl_completion_suppress_append = 0;
 #endif
+
+    saved = rl_line_buffer[start];
+    rl_line_buffer[start] = 0;
+    s = Py_DecodeLocale(rl_line_buffer, &start_size);
+    rl_line_buffer[start] = saved;
+    if (s == NULL) {
+        goto done;
+    }
+    PyMem_RawFree(s);
+    saved = rl_line_buffer[end];
+    rl_line_buffer[end] = 0;
+    s = Py_DecodeLocale(rl_line_buffer + start, &end_size);
+    rl_line_buffer[end] = saved;
+    if (s == NULL) {
+        goto done;
+    }
+    PyMem_RawFree(s);
+    start = (int)start_size;
+    end = start + (int)end_size;
+
+done:
     Py_XDECREF(readlinestate_global->begidx);
     Py_XDECREF(readlinestate_global->endidx);
     readlinestate_global->begidx = PyLong_FromLong((long) start);
     readlinestate_global->endidx = PyLong_FromLong((long) end);
-    result = completion_matches(text, *on_completion);
+    result = completion_matches((char *)text, *on_completion);
 #ifdef WITH_THREAD
     PyGILState_Release(gilstate);
 #endif
@@ -1073,19 +1129,22 @@ setup_readline(readlinestate *mod_state)
     mod_state->begidx = PyLong_FromLong(0L);
     mod_state->endidx = PyLong_FromLong(0L);
 
-#ifndef __APPLE__
-    if (!isatty(STDOUT_FILENO)) {
-        /* Issue #19884: stdout is not a terminal. Disable meta modifier
-           keys to not write the ANSI sequence "\033[1034h" into stdout. On
-           terminals supporting 8 bit characters like TERM=xterm-256color
-           (which is now the default Fedora since Fedora 18), the meta key is
-           used to enable support of 8 bit characters (ANSI sequence
-           "\033[1034h").
-
-           With libedit, this call makes readline() crash. */
-        rl_variable_bind ("enable-meta-key", "off");
-    }
+#ifdef __APPLE__
+    if (!using_libedit_emulation)
 #endif
+    {
+        if (!isatty(STDOUT_FILENO)) {
+            /* Issue #19884: stdout is not a terminal. Disable meta modifier
+               keys to not write the ANSI sequence "\033[1034h" into stdout. On
+               terminals supporting 8 bit characters like TERM=xterm-256color
+               (which is now the default Fedora since Fedora 18), the meta key is
+               used to enable support of 8 bit characters (ANSI sequence
+               "\033[1034h").
+
+               With libedit, this call makes readline() crash. */
+            rl_variable_bind ("enable-meta-key", "off");
+        }
+    }
 
     /* Initialize (allows .inputrc to override)
      *
index 3a1cf09..970ee84 100644 (file)
@@ -107,29 +107,46 @@ resource_getrusage(PyObject *self, PyObject *args)
 }
 
 static int
-py2rlimit(PyObject *curobj, PyObject *maxobj, struct rlimit *rl_out)
+py2rlimit(PyObject *limits, struct rlimit *rl_out)
 {
+    PyObject *curobj, *maxobj;
+    limits = PySequence_Tuple(limits);
+    if (!limits)
+        /* Here limits is a borrowed reference */
+        return -1;
+
+    if (PyTuple_GET_SIZE(limits) != 2) {
+        PyErr_SetString(PyExc_ValueError,
+                        "expected a tuple of 2 integers");
+        goto error;
+    }
+    curobj = PyTuple_GET_ITEM(limits, 0);
+    maxobj = PyTuple_GET_ITEM(limits, 1);
 #if !defined(HAVE_LARGEFILE_SUPPORT)
     rl_out->rlim_cur = PyLong_AsLong(curobj);
     if (rl_out->rlim_cur == (rlim_t)-1 && PyErr_Occurred())
-        return -1;
+        goto error;
     rl_out->rlim_max = PyLong_AsLong(maxobj);
     if (rl_out->rlim_max == (rlim_t)-1 && PyErr_Occurred())
-        return -1;
+        goto error;
 #else
     /* The limits are probably bigger than a long */
     rl_out->rlim_cur = PyLong_AsLongLong(curobj);
     if (rl_out->rlim_cur == (rlim_t)-1 && PyErr_Occurred())
-        return -1;
+        goto error;
     rl_out->rlim_max = PyLong_AsLongLong(maxobj);
     if (rl_out->rlim_max == (rlim_t)-1 && PyErr_Occurred())
-        return -1;
+        goto error;
 #endif
 
+    Py_DECREF(limits);
     rl_out->rlim_cur = rl_out->rlim_cur & RLIM_INFINITY;
     rl_out->rlim_max = rl_out->rlim_max & RLIM_INFINITY;
     return 0;
 
+error:
+    Py_DECREF(limits);
+    return -1;
 }
 
 static PyObject*
@@ -172,7 +189,7 @@ resource_setrlimit(PyObject *self, PyObject *args)
 {
     struct rlimit rl;
     int resource;
-    PyObject *limits, *curobj, *maxobj;
+    PyObject *limits;
 
     if (!PyArg_ParseTuple(args, "iO:setrlimit", &resource, &limits))
         return NULL;
@@ -183,21 +200,8 @@ resource_setrlimit(PyObject *self, PyObject *args)
         return NULL;
     }
 
-    limits = PySequence_Tuple(limits);
-    if (!limits)
-        /* Here limits is a borrowed reference */
+    if (py2rlimit(limits, &rl) < 0) {
         return NULL;
-
-    if (PyTuple_GET_SIZE(limits) != 2) {
-        PyErr_SetString(PyExc_ValueError,
-                        "expected a tuple of 2 integers");
-        goto error;
-    }
-    curobj = PyTuple_GET_ITEM(limits, 0);
-    maxobj = PyTuple_GET_ITEM(limits, 1);
-
-    if (py2rlimit(curobj, maxobj, &rl) < 0) {
-        goto error;
     }
 
     if (setrlimit(resource, &rl) == -1) {
@@ -209,15 +213,9 @@ resource_setrlimit(PyObject *self, PyObject *args)
                             "not allowed to raise maximum limit");
         else
             PyErr_SetFromErrno(PyExc_OSError);
-        goto error;
+        return NULL;
     }
-    Py_DECREF(limits);
-    Py_INCREF(Py_None);
-    return Py_None;
-
-  error:
-    Py_DECREF(limits);
-    return NULL;
+    Py_RETURN_NONE;
 }
 
 #ifdef HAVE_PRLIMIT
@@ -227,10 +225,10 @@ resource_prlimit(PyObject *self, PyObject *args)
     struct rlimit old_limit, new_limit;
     int resource, retval;
     pid_t pid;
-    PyObject *curobj=NULL, *maxobj=NULL;
+    PyObject *limits = NULL;
 
-    if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i|(OO):prlimit",
-                          &pid, &resource, &curobj, &maxobj))
+    if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i|O:prlimit",
+                          &pid, &resource, &limits))
         return NULL;
 
     if (resource < 0 || resource >= RLIM_NLIMITS) {
@@ -239,8 +237,8 @@ resource_prlimit(PyObject *self, PyObject *args)
         return NULL;
     }
 
-    if (curobj != NULL) {
-        if (py2rlimit(curobj, maxobj, &new_limit) < 0) {
+    if (limits != NULL) {
+        if (py2rlimit(limits, &new_limit) < 0) {
             return NULL;
         }
         retval = prlimit(pid, resource, &new_limit, &old_limit);
index 74b94ba..6cb32ed 100644 (file)
@@ -486,8 +486,8 @@ Return a new SHA1 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
 static PyObject *
-_sha1_sha1_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=3e4e841386b9e8db input=27ea54281d995ec2]*/
+_sha1_sha1_impl(PyObject *module, PyObject *string)
+/*[clinic end generated code: output=e5982830d1dece51 input=27ea54281d995ec2]*/
 {
     SHA1object *new;
     Py_buffer buf;
index 70c2b5b..8f067f1 100644 (file)
@@ -607,8 +607,8 @@ Return a new SHA-256 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
 static PyObject *
-_sha256_sha256_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=d70e6e2d97112844 input=09cce3fb855056b2]*/
+_sha256_sha256_impl(PyObject *module, PyObject *string)
+/*[clinic end generated code: output=fa644436dcea5c31 input=09cce3fb855056b2]*/
 {
     SHAobject *new;
     Py_buffer buf;
@@ -647,8 +647,8 @@ Return a new SHA-224 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
 static PyObject *
-_sha256_sha224_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=f2822bf28416b42a input=27a04ba24c353a73]*/
+_sha256_sha224_impl(PyObject *module, PyObject *string)
+/*[clinic end generated code: output=21e3ba22c3404f93 input=27a04ba24c353a73]*/
 {
     SHAobject *new;
     Py_buffer buf;
index 76942aa..f9ff0ea 100644 (file)
@@ -678,8 +678,8 @@ Return a new SHA-512 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
 static PyObject *
-_sha512_sha512_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=da13bc0a94da6de3 input=e69bad9ae9b6a308]*/
+_sha512_sha512_impl(PyObject *module, PyObject *string)
+/*[clinic end generated code: output=8b865a2df73bd387 input=e69bad9ae9b6a308]*/
 {
     SHAobject *new;
     Py_buffer buf;
@@ -718,8 +718,8 @@ Return a new SHA-384 hash object; optionally initialized with a string.
 [clinic start generated code]*/
 
 static PyObject *
-_sha512_sha384_impl(PyModuleDef *module, PyObject *string)
-/*[clinic end generated code: output=ac731aea5509174d input=c9327788d4ea4545]*/
+_sha512_sha384_impl(PyObject *module, PyObject *string)
+/*[clinic end generated code: output=ae4b2e26decf81e8 input=c9327788d4ea4545]*/
 {
     SHAobject *new;
     Py_buffer buf;
index da454de..753d987 100644 (file)
@@ -154,18 +154,18 @@ itimer_retval(struct itimerval *iv)
 
     r = PyTuple_New(2);
     if (r == NULL)
-    return NULL;
+        return NULL;
 
     if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
-    Py_DECREF(r);
-    return NULL;
+        Py_DECREF(r);
+        return NULL;
     }
 
     PyTuple_SET_ITEM(r, 0, v);
 
     if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) {
-    Py_DECREF(r);
-    return NULL;
+        Py_DECREF(r);
+        return NULL;
     }
 
     PyTuple_SET_ITEM(r, 1, v);
@@ -340,8 +340,8 @@ Arrange for SIGALRM to arrive after the given number of seconds.
 [clinic start generated code]*/
 
 static long
-signal_alarm_impl(PyModuleDef *module, int seconds)
-/*[clinic end generated code: output=f5f9badaab25d3e7 input=0d5e97e0e6f39e86]*/
+signal_alarm_impl(PyObject *module, int seconds)
+/*[clinic end generated code: output=144232290814c298 input=0d5e97e0e6f39e86]*/
 {
     /* alarm() returns the number of seconds remaining */
     return (long)alarm(seconds);
@@ -358,8 +358,8 @@ Wait until a signal arrives.
 [clinic start generated code]*/
 
 static PyObject *
-signal_pause_impl(PyModuleDef *module)
-/*[clinic end generated code: output=9245704caa63bbe9 input=f03de0f875752062]*/
+signal_pause_impl(PyObject *module)
+/*[clinic end generated code: output=391656788b3c3929 input=f03de0f875752062]*/
 {
     Py_BEGIN_ALLOW_THREADS
     (void)pause();
@@ -394,8 +394,8 @@ the first is the signal number, the second is the interrupted stack frame.
 [clinic start generated code]*/
 
 static PyObject *
-signal_signal_impl(PyModuleDef *module, int signalnum, PyObject *handler)
-/*[clinic end generated code: output=622d7d0beebea546 input=deee84af5fa0432c]*/
+signal_signal_impl(PyObject *module, int signalnum, PyObject *handler)
+/*[clinic end generated code: output=b44cfda43780f3a1 input=deee84af5fa0432c]*/
 {
     PyObject *old_handler;
     void (*func)(int);
@@ -472,8 +472,8 @@ The return value can be:
 [clinic start generated code]*/
 
 static PyObject *
-signal_getsignal_impl(PyModuleDef *module, int signalnum)
-/*[clinic end generated code: output=d50ec355757e360c input=ac23a00f19dfa509]*/
+signal_getsignal_impl(PyObject *module, int signalnum)
+/*[clinic end generated code: output=35b3e0e796fd555e input=ac23a00f19dfa509]*/
 {
     PyObject *old_handler;
     if (signalnum < 1 || signalnum >= NSIG) {
@@ -507,8 +507,8 @@ signal sig, else system calls will be interrupted.
 [clinic start generated code]*/
 
 static PyObject *
-signal_siginterrupt_impl(PyModuleDef *module, int signalnum, int flag)
-/*[clinic end generated code: output=5dcf8b031b0e8044 input=4160acacca3e2099]*/
+signal_siginterrupt_impl(PyObject *module, int signalnum, int flag)
+/*[clinic end generated code: output=063816243d85dd19 input=4160acacca3e2099]*/
 {
     if (signalnum < 1 || signalnum >= NSIG) {
         PyErr_SetString(PyExc_ValueError,
@@ -682,9 +682,9 @@ Returns old values as a tuple: (delay, interval).
 [clinic start generated code]*/
 
 static PyObject *
-signal_setitimer_impl(PyModuleDef *module, int which, double seconds,
+signal_setitimer_impl(PyObject *module, int which, double seconds,
                       double interval)
-/*[clinic end generated code: output=9a9227a27bd05988 input=0d27d417cfcbd51a]*/
+/*[clinic end generated code: output=6f51da0fe0787f2c input=0d27d417cfcbd51a]*/
 {
     struct itimerval new, old;
 
@@ -714,8 +714,8 @@ Returns current value of given itimer.
 [clinic start generated code]*/
 
 static PyObject *
-signal_getitimer_impl(PyModuleDef *module, int which)
-/*[clinic end generated code: output=d1349ab18aadc569 input=f7d21d38f3490627]*/
+signal_getitimer_impl(PyObject *module, int which)
+/*[clinic end generated code: output=9e053175d517db40 input=f7d21d38f3490627]*/
 {
     struct itimerval old;
 
@@ -829,8 +829,8 @@ Fetch and/or change the signal mask of the calling thread.
 [clinic start generated code]*/
 
 static PyObject *
-signal_pthread_sigmask_impl(PyModuleDef *module, int how, PyObject *mask)
-/*[clinic end generated code: output=b043a9f0eeb1e075 input=f3b7d7a61b7b8283]*/
+signal_pthread_sigmask_impl(PyObject *module, int how, PyObject *mask)
+/*[clinic end generated code: output=ff640fe092bc9181 input=f3b7d7a61b7b8283]*/
 {
     sigset_t newmask, previous;
     int err;
@@ -867,8 +867,8 @@ the calling thread.
 [clinic start generated code]*/
 
 static PyObject *
-signal_sigpending_impl(PyModuleDef *module)
-/*[clinic end generated code: output=bf4ced803e7e51dd input=e0036c016f874e29]*/
+signal_sigpending_impl(PyObject *module)
+/*[clinic end generated code: output=53375ffe89325022 input=e0036c016f874e29]*/
 {
     int err;
     sigset_t mask;
@@ -897,8 +897,8 @@ and returns the signal number.
 [clinic start generated code]*/
 
 static PyObject *
-signal_sigwait(PyModuleDef *module, PyObject *sigset)
-/*[clinic end generated code: output=dae53048b0336a5c input=11af2d82d83c2e94]*/
+signal_sigwait(PyObject *module, PyObject *sigset)
+/*[clinic end generated code: output=557173647424f6e4 input=11af2d82d83c2e94]*/
 {
     sigset_t set;
     int err, signum;
@@ -986,8 +986,8 @@ Returns a struct_siginfo containing information about the signal.
 [clinic start generated code]*/
 
 static PyObject *
-signal_sigwaitinfo(PyModuleDef *module, PyObject *sigset)
-/*[clinic end generated code: output=0bb53b07e5e926b5 input=f3779a74a991e171]*/
+signal_sigwaitinfo(PyObject *module, PyObject *sigset)
+/*[clinic end generated code: output=c40f27b269cd2309 input=f3779a74a991e171]*/
 {
     sigset_t set;
     siginfo_t si;
@@ -1026,9 +1026,9 @@ The timeout is specified in seconds, with floating point numbers allowed.
 [clinic start generated code]*/
 
 static PyObject *
-signal_sigtimedwait_impl(PyModuleDef *module, PyObject *sigset,
+signal_sigtimedwait_impl(PyObject *module, PyObject *sigset,
                          PyObject *timeout_obj)
-/*[clinic end generated code: output=c1960b5cea139929 input=53fd4ea3e3724eb8]*/
+/*[clinic end generated code: output=f7eff31e679f4312 input=53fd4ea3e3724eb8]*/
 {
     struct timespec ts;
     sigset_t set;
@@ -1097,8 +1097,8 @@ Send a signal to a thread.
 [clinic start generated code]*/
 
 static PyObject *
-signal_pthread_kill_impl(PyModuleDef *module, long thread_id, int signalnum)
-/*[clinic end generated code: output=35aed2713c756d7a input=77ed6a3b6f2a8122]*/
+signal_pthread_kill_impl(PyObject *module, long thread_id, int signalnum)
+/*[clinic end generated code: output=2a09ce41f1c4228a input=77ed6a3b6f2a8122]*/
 {
     int err;
 
@@ -1479,9 +1479,9 @@ PyInit__signal(void)
 
 #if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER)
     ItimerError = PyErr_NewException("signal.ItimerError",
-     PyExc_IOError, NULL);
+            PyExc_IOError, NULL);
     if (ItimerError != NULL)
-    PyDict_SetItemString(d, "ItimerError", ItimerError);
+        PyDict_SetItemString(d, "ItimerError", ItimerError);
 #endif
 
 #ifdef CTRL_C_EVENT
index 8f571a2..af6cc94 100644 (file)
@@ -168,12 +168,14 @@ if_indextoname(index) -- return the corresponding interface name\n\
 #endif
 
 #ifdef HAVE_GETHOSTBYNAME_R
-# if defined(_AIX)
+# if defined(_AIX) && !defined(_LINUX_SOURCE_COMPAT)
 #  define HAVE_GETHOSTBYNAME_R_3_ARG
 # elif defined(__sun) || defined(__sgi)
 #  define HAVE_GETHOSTBYNAME_R_5_ARG
 # elif defined(linux)
 /* Rely on the configure script */
+# elif defined(_LINUX_SOURCE_COMPAT) /* Linux compatibility on AIX */
+#  define HAVE_GETHOSTBYNAME_R_6_ARG
 # else
 #  undef HAVE_GETHOSTBYNAME_R
 # endif
@@ -648,7 +650,7 @@ internal_select(PySocketSockObject *s, int writing, _PyTime_t interval,
     assert(!(connect && !writing));
 
     /* Guard against closed socket */
-    if (s->sock_fd < 0)
+    if (s->sock_fd == INVALID_SOCKET)
         return 0;
 
     /* Prefer poll, if available, since you can poll() any fd
@@ -1967,12 +1969,13 @@ getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
         return 1;
     }
 #endif /* AF_UNIX */
+
 #if defined(AF_NETLINK)
-       case AF_NETLINK:
-       {
-           *len_ret = sizeof (struct sockaddr_nl);
-           return 1;
-       }
+    case AF_NETLINK:
+    {
+        *len_ret = sizeof (struct sockaddr_nl);
+        return 1;
+    }
 #endif
 
 #ifdef AF_RDS
@@ -2568,8 +2571,9 @@ sock_close(PySocketSockObject *s)
      * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
      * for more details.
      */
-    if ((fd = s->sock_fd) != -1) {
-        s->sock_fd = -1;
+    fd = s->sock_fd;
+    if (fd != INVALID_SOCKET) {
+        s->sock_fd = INVALID_SOCKET;
         Py_BEGIN_ALLOW_THREADS
         (void) SOCKETCLOSE(fd);
         Py_END_ALLOW_THREADS
@@ -2587,7 +2591,7 @@ static PyObject *
 sock_detach(PySocketSockObject *s)
 {
     SOCKET_T fd = s->sock_fd;
-    s->sock_fd = -1;
+    s->sock_fd = INVALID_SOCKET;
     return PyLong_FromSocket_t(fd);
 }
 
@@ -4165,7 +4169,7 @@ static PyGetSetDef sock_getsetlist[] = {
 static void
 sock_dealloc(PySocketSockObject *s)
 {
-    if (s->sock_fd != -1) {
+    if (s->sock_fd != INVALID_SOCKET) {
         PyObject *exc, *val, *tb;
         Py_ssize_t old_refcount = Py_REFCNT(s);
         ++Py_REFCNT(s);
@@ -4221,7 +4225,7 @@ sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 
     new = type->tp_alloc(type, 0);
     if (new != NULL) {
-        ((PySocketSockObject *)new)->sock_fd = -1;
+        ((PySocketSockObject *)new)->sock_fd = INVALID_SOCKET;
         ((PySocketSockObject *)new)->sock_timeout = _PyTime_FromSeconds(-1);
         ((PySocketSockObject *)new)->errorhandler = &set_error;
     }
@@ -6537,7 +6541,7 @@ PyInit__socket(void)
     PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
 #endif
 
-    /* Ancilliary message types */
+    /* Ancillary message types */
 #ifdef  SCM_RIGHTS
     PyModule_AddIntMacro(m, SCM_RIGHTS);
 #endif
index 49324d5..4b9f3cd 100644 (file)
@@ -125,8 +125,8 @@ See `help(spwd)` for more on shadow password database entries.
 [clinic start generated code]*/
 
 static PyObject *
-spwd_getspnam_impl(PyModuleDef *module, PyObject *arg)
-/*[clinic end generated code: output=9f6bbe51a4eb3b21 input=dd89429e6167a00f]*/
+spwd_getspnam_impl(PyObject *module, PyObject *arg)
+/*[clinic end generated code: output=701250cf57dc6ebe input=dd89429e6167a00f]*/
 {
     char *name;
     struct spwd *p;
@@ -159,8 +159,8 @@ See `help(spwd)` for more on shadow password database entries.
 [clinic start generated code]*/
 
 static PyObject *
-spwd_getspall_impl(PyModuleDef *module)
-/*[clinic end generated code: output=b12d8ec7bdb29612 input=b2c84b7857d622bd]*/
+spwd_getspall_impl(PyObject *module)
+/*[clinic end generated code: output=4fda298d6bf6d057 input=b2c84b7857d622bd]*/
 {
     PyObject *d;
     struct spwd *p;
index fe4e908..1f9ba78 100644 (file)
@@ -1041,8 +1041,8 @@ _cmpname(PyObject *self, int code, const char* name, int namelen)
 {
     /* check if code corresponds to the given name */
     int i;
-    char buffer[NAME_MAXLEN];
-    if (!_getucname(self, code, buffer, sizeof(buffer), 1))
+    char buffer[NAME_MAXLEN+1];
+    if (!_getucname(self, code, buffer, NAME_MAXLEN, 1))
         return 0;
     for (i = 0; i < namelen; i++) {
         if (Py_TOUPPER(Py_CHARMASK(name[i])) != buffer[i])
@@ -1195,10 +1195,10 @@ static PyObject *
 unicodedata_UCD_name_impl(PyObject *self, int chr, PyObject *default_value)
 /*[clinic end generated code: output=6bbb37a326407707 input=3e0367f534de56d9]*/
 {
-    char name[NAME_MAXLEN];
+    char name[NAME_MAXLEN+1];
     Py_UCS4 c = (Py_UCS4)chr;
 
-    if (!_getucname(self, c, name, sizeof(name), 0)) {
+    if (!_getucname(self, c, name, NAME_MAXLEN, 0)) {
         if (default_value == NULL) {
             PyErr_SetString(PyExc_ValueError, "no such name");
             return NULL;
@@ -1232,7 +1232,7 @@ unicodedata_UCD_lookup_impl(PyObject *self, const char *name,
 {
     Py_UCS4 code;
     unsigned int index;
-    if (name_length > INT_MAX) {
+    if (name_length > NAME_MAXLEN) {
         PyErr_SetString(PyExc_KeyError, "name too long");
         return NULL;
     }
index e840271..7473a8f 100644 (file)
@@ -1315,7 +1315,7 @@ unmarshal_code(PyObject *pathname, PyObject *data, time_t mtime)
     return code;
 }
 
-/* Replace any occurances of "\r\n?" in the input string with "\n".
+/* Replace any occurrences of "\r\n?" in the input string with "\n".
    This converts DOS and Mac line endings to Unix line endings.
    Also append a trailing "\n" to be compatible with
    PyParser_SimpleParseFile(). Returns a new reference. */
@@ -1362,22 +1362,16 @@ normalize_line_endings(PyObject *source)
 static PyObject *
 compile_source(PyObject *pathname, PyObject *source)
 {
-    PyObject *code, *fixed_source, *pathbytes;
-
-    pathbytes = PyUnicode_EncodeFSDefault(pathname);
-    if (pathbytes == NULL)
-        return NULL;
+    PyObject *code, *fixed_source;
 
     fixed_source = normalize_line_endings(source);
     if (fixed_source == NULL) {
-        Py_DECREF(pathbytes);
         return NULL;
     }
 
-    code = Py_CompileString(PyBytes_AsString(fixed_source),
-                            PyBytes_AsString(pathbytes),
-                            Py_file_input);
-    Py_DECREF(pathbytes);
+    code = Py_CompileStringObject(PyBytes_AsString(fixed_source),
+                                  pathname, Py_file_input, NULL, -1);
+
     Py_DECREF(fixed_source);
     return code;
 }
index 16cc178..fccb616 100644 (file)
@@ -1,5 +1,5 @@
 /* zlibmodule.c -- gzip-compatible data compression */
-/* See http://www.gzip.org/zlib/ */
+/* See http://zlib.net/ */
 
 /* Windows users:  read Python's PCbuild\readme.txt */
 
@@ -23,7 +23,7 @@
 #endif
 
 #if defined(ZLIB_VERNUM) && ZLIB_VERNUM >= 0x1221
-#define AT_LEAST_ZLIB_1_2_2_1
+#  define AT_LEAST_ZLIB_1_2_2_1
 #endif
 
 /* The following parameters are copied from zutil.h, version 0.95 */
@@ -115,6 +115,7 @@ newcompobject(PyTypeObject *type)
 #ifdef WITH_THREAD
     self->lock = PyThread_allocate_lock();
     if (self->lock == NULL) {
+        Py_DECREF(self);
         PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
         return NULL;
     }
@@ -138,6 +139,63 @@ PyZlib_Free(voidpf ctx, void *ptr)
     PyMem_RawFree(ptr);
 }
 
+static void
+arrange_input_buffer(z_stream *zst, Py_ssize_t *remains)
+{
+    zst->avail_in = Py_MIN((size_t)*remains, UINT_MAX);
+    *remains -= zst->avail_in;
+}
+
+static Py_ssize_t
+arrange_output_buffer_with_maximum(z_stream *zst, PyObject **buffer,
+                                   Py_ssize_t length,
+                                   Py_ssize_t max_length)
+{
+    Py_ssize_t occupied;
+
+    if (*buffer == NULL) {
+        if (!(*buffer = PyBytes_FromStringAndSize(NULL, length)))
+            return -1;
+        occupied = 0;
+    }
+    else {
+        occupied = zst->next_out - (Byte *)PyBytes_AS_STRING(*buffer);
+
+        if (length == occupied) {
+            Py_ssize_t new_length;
+            assert(length <= max_length);
+            /* can not scale the buffer over max_length */
+            if (length == max_length)
+                return -2;
+            if (length <= (max_length >> 1))
+                new_length = length << 1;
+            else
+                new_length = max_length;
+            if (_PyBytes_Resize(buffer, new_length) < 0)
+                return -1;
+            length = new_length;
+        }
+    }
+
+    zst->avail_out = Py_MIN((size_t)(length - occupied), UINT_MAX);
+    zst->next_out = (Byte *)PyBytes_AS_STRING(*buffer) + occupied;
+
+    return length;
+}
+
+static Py_ssize_t
+arrange_output_buffer(z_stream *zst, PyObject **buffer, Py_ssize_t length)
+{
+    Py_ssize_t ret;
+
+    ret = arrange_output_buffer_with_maximum(zst, buffer, length,
+                                             PY_SSIZE_T_MAX);
+    if (ret == -2)
+        PyErr_NoMemory();
+
+    return ret;
+}
+
 /*[clinic input]
 zlib.compress
 
@@ -151,53 +209,33 @@ Returns a bytes object containing compressed data.
 [clinic start generated code]*/
 
 static PyObject *
-zlib_compress_impl(PyModuleDef *module, Py_buffer *bytes, int level)
-/*[clinic end generated code: output=5d7dd4588788efd3 input=be3abe9934bda4b3]*/
+zlib_compress_impl(PyObject *module, Py_buffer *bytes, int level)
+/*[clinic end generated code: output=ae64c2c3076321a0 input=be3abe9934bda4b3]*/
 {
-    PyObject *ReturnVal = NULL;
-    Byte *input, *output = NULL;
-    unsigned int length;
-    int err;
+    PyObject *RetVal = NULL;
+    Byte *ibuf;
+    Py_ssize_t ibuflen, obuflen = DEF_BUF_SIZE;
+    int err, flush;
     z_stream zst;
 
-    if ((size_t)bytes->len > UINT_MAX) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "Size does not fit in an unsigned int");
-        goto error;
-    }
-    input = bytes->buf;
-    length = (unsigned int)bytes->len;
-
-    zst.avail_out = length + length/1000 + 12 + 1;
-
-    output = (Byte*)PyMem_Malloc(zst.avail_out);
-    if (output == NULL) {
-        PyErr_SetString(PyExc_MemoryError,
-                        "Can't allocate memory to compress data");
-        goto error;
-    }
-
-    /* Past the point of no return.  From here on out, we need to make sure
-       we clean up mallocs & INCREFs. */
+    ibuf = bytes->buf;
+    ibuflen = bytes->len;
 
     zst.opaque = NULL;
     zst.zalloc = PyZlib_Malloc;
     zst.zfree = PyZlib_Free;
-    zst.next_out = (Byte *)output;
-    zst.next_in = (Byte *)input;
-    zst.avail_in = length;
+    zst.next_in = ibuf;
     err = deflateInit(&zst, level);
 
-    switch(err) {
-    case(Z_OK):
+    switch (err) {
+    case Z_OK:
         break;
-    case(Z_MEM_ERROR):
+    case Z_MEM_ERROR:
         PyErr_SetString(PyExc_MemoryError,
                         "Out of memory while compressing data");
         goto error;
-    case(Z_STREAM_ERROR):
-        PyErr_SetString(ZlibError,
-                        "Bad compression level");
+    case Z_STREAM_ERROR:
+        PyErr_SetString(ZlibError, "Bad compression level");
         goto error;
     default:
         deflateEnd(&zst);
@@ -205,41 +243,59 @@ zlib_compress_impl(PyModuleDef *module, Py_buffer *bytes, int level)
         goto error;
     }
 
-    Py_BEGIN_ALLOW_THREADS;
-    err = deflate(&zst, Z_FINISH);
-    Py_END_ALLOW_THREADS;
+    do {
+        arrange_input_buffer(&zst, &ibuflen);
+        flush = ibuflen == 0 ? Z_FINISH : Z_NO_FLUSH;
 
-    if (err != Z_STREAM_END) {
-        zlib_error(zst, err, "while compressing data");
-        deflateEnd(&zst);
-        goto error;
-    }
+        do {
+            obuflen = arrange_output_buffer(&zst, &RetVal, obuflen);
+            if (obuflen < 0) {
+                deflateEnd(&zst);
+                goto error;
+            }
+
+            Py_BEGIN_ALLOW_THREADS
+            err = deflate(&zst, flush);
+            Py_END_ALLOW_THREADS
+
+            if (err == Z_STREAM_ERROR) {
+                deflateEnd(&zst);
+                zlib_error(zst, err, "while compressing data");
+                goto error;
+            }
 
-    err=deflateEnd(&zst);
-    if (err == Z_OK)
-        ReturnVal = PyBytes_FromStringAndSize((char *)output,
-                                              zst.total_out);
+        } while (zst.avail_out == 0);
+        assert(zst.avail_in == 0);
+
+    } while (flush != Z_FINISH);
+    assert(err == Z_STREAM_END);
+
+    err = deflateEnd(&zst);
+    if (err == Z_OK) {
+        if (_PyBytes_Resize(&RetVal, zst.next_out -
+                            (Byte *)PyBytes_AS_STRING(RetVal)) < 0)
+            goto error;
+        return RetVal;
+    }
     else
         zlib_error(zst, err, "while finishing compression");
-
  error:
-    PyMem_Free(output);
-
-    return ReturnVal;
+    Py_XDECREF(RetVal);
+    return NULL;
 }
 
 /*[python input]
 
-class capped_uint_converter(CConverter):
-    type = 'unsigned int'
-    converter = 'capped_uint_converter'
+class ssize_t_converter(CConverter):
+    type = 'Py_ssize_t'
+    converter = 'ssize_t_converter'
     c_ignored_default = "0"
 
 [python start generated code]*/
-/*[python end generated code: output=da39a3ee5e6b4b0d input=35521e4e733823c7]*/
+/*[python end generated code: output=da39a3ee5e6b4b0d input=5f34ba1b394cb8e7]*/
 
 static int
-capped_uint_converter(PyObject *obj, void *ptr)
+ssize_t_converter(PyObject *obj, void *ptr)
 {
     PyObject *long_obj;
     Py_ssize_t val;
@@ -253,19 +309,7 @@ capped_uint_converter(PyObject *obj, void *ptr)
     if (val == -1 && PyErr_Occurred()) {
         return 0;
     }
-    if (val < 0) {
-        PyErr_SetString(PyExc_ValueError,
-                        "value must be positive");
-        return 0;
-    }
-
-    if ((size_t)val > UINT_MAX) {
-        *(unsigned int *)ptr = UINT_MAX;
-    }
-    else {
-        *(unsigned int *)ptr = Py_SAFE_DOWNCAST(val, Py_ssize_t,
-            unsigned int);
-    }
+    *(Py_ssize_t *)ptr = val;
     return 1;
 }
 
@@ -276,7 +320,7 @@ zlib.decompress
         Compressed data.
     wbits: int(c_default="MAX_WBITS") = MAX_WBITS
         The window buffer size and container format.
-    bufsize: capped_uint(c_default="DEF_BUF_SIZE") = DEF_BUF_SIZE
+    bufsize: ssize_t(c_default="DEF_BUF_SIZE") = DEF_BUF_SIZE
         The initial output buffer size.
     /
 
@@ -284,45 +328,37 @@ Returns a bytes object containing the uncompressed data.
 [clinic start generated code]*/
 
 static PyObject *
-zlib_decompress_impl(PyModuleDef *module, Py_buffer *data, int wbits,
-                     unsigned int bufsize)
-/*[clinic end generated code: output=444d0987f3429574 input=75123b0d4ff0541d]*/
+zlib_decompress_impl(PyObject *module, Py_buffer *data, int wbits,
+                     Py_ssize_t bufsize)
+/*[clinic end generated code: output=77c7e35111dc8c42 input=c13dd2c5696cd17f]*/
 {
-    PyObject *result_str = NULL;
-    Byte *input;
-    unsigned int length;
-    int err;
-    unsigned int new_bufsize;
+    PyObject *RetVal = NULL;
+    Byte *ibuf;
+    Py_ssize_t ibuflen;
+    int err, flush;
     z_stream zst;
 
-    if ((size_t)data->len > UINT_MAX) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "Size does not fit in an unsigned int");
-        goto error;
-    }
-    input = data->buf;
-    length = (unsigned int)data->len;
-
-    if (bufsize == 0)
+    if (bufsize < 0) {
+        PyErr_SetString(PyExc_ValueError, "bufsize must be non-negative");
+        return NULL;
+    } else if (bufsize == 0) {
         bufsize = 1;
+    }
 
-    zst.avail_in = length;
-    zst.avail_out = bufsize;
-
-    if (!(result_str = PyBytes_FromStringAndSize(NULL, bufsize)))
-        goto error;
+    ibuf = data->buf;
+    ibuflen = data->len;
 
     zst.opaque = NULL;
     zst.zalloc = PyZlib_Malloc;
     zst.zfree = PyZlib_Free;
-    zst.next_out = (Byte *)PyBytes_AS_STRING(result_str);
-    zst.next_in = (Byte *)input;
+    zst.avail_in = 0;
+    zst.next_in = ibuf;
     err = inflateInit2(&zst, wbits);
 
-    switch(err) {
-    case(Z_OK):
+    switch (err) {
+    case Z_OK:
         break;
-    case(Z_MEM_ERROR):
+    case Z_MEM_ERROR:
         PyErr_SetString(PyExc_MemoryError,
                         "Out of memory while decompressing data");
         goto error;
@@ -333,46 +369,46 @@ zlib_decompress_impl(PyModuleDef *module, Py_buffer *data, int wbits,
     }
 
     do {
-        Py_BEGIN_ALLOW_THREADS
-        err=inflate(&zst, Z_FINISH);
-        Py_END_ALLOW_THREADS
+        arrange_input_buffer(&zst, &ibuflen);
+        flush = ibuflen == 0 ? Z_FINISH : Z_NO_FLUSH;
 
-        switch(err) {
-        case(Z_STREAM_END):
-            break;
-        case(Z_BUF_ERROR):
-            /*
-             * If there is at least 1 byte of room according to zst.avail_out
-             * and we get this error, assume that it means zlib cannot
-             * process the inflate call() due to an error in the data.
-             */
-            if (zst.avail_out > 0) {
-                zlib_error(zst, err, "while decompressing data");
+        do {
+            bufsize = arrange_output_buffer(&zst, &RetVal, bufsize);
+            if (bufsize < 0) {
                 inflateEnd(&zst);
                 goto error;
             }
-            /* fall through */
-        case(Z_OK):
-            /* need more memory */
-            if (bufsize <= (UINT_MAX >> 1))
-                new_bufsize = bufsize << 1;
-            else
-                new_bufsize = UINT_MAX;
-            if (_PyBytes_Resize(&result_str, new_bufsize) < 0) {
+
+            Py_BEGIN_ALLOW_THREADS
+            err = inflate(&zst, flush);
+            Py_END_ALLOW_THREADS
+
+            switch (err) {
+            case Z_OK:            /* fall through */
+            case Z_BUF_ERROR:     /* fall through */
+            case Z_STREAM_END:
+                break;
+            case Z_MEM_ERROR:
                 inflateEnd(&zst);
+                PyErr_SetString(PyExc_MemoryError,
+                                "Out of memory while decompressing data");
+                goto error;
+            default:
+                inflateEnd(&zst);
+                zlib_error(zst, err, "while decompressing data");
                 goto error;
             }
-            zst.next_out =
-                (unsigned char *)PyBytes_AS_STRING(result_str) + bufsize;
-            zst.avail_out = bufsize;
-            bufsize = new_bufsize;
-            break;
-        default:
-            inflateEnd(&zst);
-            zlib_error(zst, err, "while decompressing data");
-            goto error;
-        }
-    } while (err != Z_STREAM_END);
+
+        } while (zst.avail_out == 0);
+
+    } while (err != Z_STREAM_END && ibuflen != 0);
+
+
+    if (err != Z_STREAM_END) {
+        inflateEnd(&zst);
+        zlib_error(zst, err, "while decompressing data");
+        goto error;
+    }
 
     err = inflateEnd(&zst);
     if (err != Z_OK) {
@@ -380,13 +416,14 @@ zlib_decompress_impl(PyModuleDef *module, Py_buffer *data, int wbits,
         goto error;
     }
 
-    if (_PyBytes_Resize(&result_str, zst.total_out) < 0)
+    if (_PyBytes_Resize(&RetVal, zst.next_out -
+                        (Byte *)PyBytes_AS_STRING(RetVal)) < 0)
         goto error;
 
-    return result_str;
+    return RetVal;
 
  error:
-    Py_XDECREF(result_str);
+    Py_XDECREF(RetVal);
     return NULL;
 }
 
@@ -419,9 +456,9 @@ Return a compressor object.
 [clinic start generated code]*/
 
 static PyObject *
-zlib_compressobj_impl(PyModuleDef *module, int level, int method, int wbits,
+zlib_compressobj_impl(PyObject *module, int level, int method, int wbits,
                       int memLevel, int strategy, Py_buffer *zdict)
-/*[clinic end generated code: output=2949bbb9a5723ccd input=2fa3d026f90ab8d5]*/
+/*[clinic end generated code: output=8b5bed9c8fc3814d input=2fa3d026f90ab8d5]*/
 {
     compobject *self = NULL;
     int err;
@@ -433,7 +470,7 @@ zlib_compressobj_impl(PyModuleDef *module, int level, int method, int wbits,
     }
 
     self = newcompobject(&Comptype);
-    if (self==NULL)
+    if (self == NULL)
         goto error;
     self->zst.opaque = NULL;
     self->zst.zalloc = PyZlib_Malloc;
@@ -441,8 +478,8 @@ zlib_compressobj_impl(PyModuleDef *module, int level, int method, int wbits,
     self->zst.next_in = NULL;
     self->zst.avail_in = 0;
     err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy);
-    switch(err) {
-    case (Z_OK):
+    switch (err) {
+    case Z_OK:
         self->is_initialised = 1;
         if (zdict->buf == NULL) {
             goto success;
@@ -450,9 +487,9 @@ zlib_compressobj_impl(PyModuleDef *module, int level, int method, int wbits,
             err = deflateSetDictionary(&self->zst,
                                        zdict->buf, (unsigned int)zdict->len);
             switch (err) {
-            case (Z_OK):
+            case Z_OK:
                 goto success;
-            case (Z_STREAM_ERROR):
+            case Z_STREAM_ERROR:
                 PyErr_SetString(PyExc_ValueError, "Invalid dictionary");
                 goto error;
             default:
@@ -460,11 +497,11 @@ zlib_compressobj_impl(PyModuleDef *module, int level, int method, int wbits,
                 goto error;
             }
        }
-    case (Z_MEM_ERROR):
+    case Z_MEM_ERROR:
         PyErr_SetString(PyExc_MemoryError,
                         "Can't allocate memory for compression object");
         goto error;
-    case(Z_STREAM_ERROR):
+    case Z_STREAM_ERROR:
         PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
         goto error;
     default:
@@ -475,7 +512,7 @@ zlib_compressobj_impl(PyModuleDef *module, int level, int method, int wbits,
  error:
     Py_CLEAR(self);
  success:
-    return (PyObject*)self;
+    return (PyObject *)self;
 }
 
 static int
@@ -493,7 +530,7 @@ set_inflate_zdict(compobject *self)
         PyBuffer_Release(&zdict_buf);
         return -1;
     }
-    err = inflateSetDictionary(&(self->zst),
+    err = inflateSetDictionary(&self->zst,
                                zdict_buf.buf, (unsigned int)zdict_buf.len);
     PyBuffer_Release(&zdict_buf);
     if (err != Z_OK) {
@@ -516,8 +553,8 @@ Return a decompressor object.
 [clinic start generated code]*/
 
 static PyObject *
-zlib_decompressobj_impl(PyModuleDef *module, int wbits, PyObject *zdict)
-/*[clinic end generated code: output=8ccd583fbd631798 input=d3832b8511fc977b]*/
+zlib_decompressobj_impl(PyObject *module, int wbits, PyObject *zdict)
+/*[clinic end generated code: output=3069b99994f36906 input=d3832b8511fc977b]*/
 {
     int err;
     compobject *self;
@@ -530,7 +567,7 @@ zlib_decompressobj_impl(PyModuleDef *module, int wbits, PyObject *zdict)
 
     self = newcompobject(&Decomptype);
     if (self == NULL)
-        return(NULL);
+        return NULL;
     self->zst.opaque = NULL;
     self->zst.zalloc = PyZlib_Malloc;
     self->zst.zfree = PyZlib_Free;
@@ -541,8 +578,8 @@ zlib_decompressobj_impl(PyModuleDef *module, int wbits, PyObject *zdict)
         self->zdict = zdict;
     }
     err = inflateInit2(&self->zst, wbits);
-    switch(err) {
-    case (Z_OK):
+    switch (err) {
+    case Z_OK:
         self->is_initialised = 1;
         if (self->zdict != NULL && wbits < 0) {
 #ifdef AT_LEAST_ZLIB_1_2_2_1
@@ -558,12 +595,12 @@ zlib_decompressobj_impl(PyModuleDef *module, int wbits, PyObject *zdict)
             return NULL;
 #endif
         }
-        return (PyObject*)self;
-    case(Z_STREAM_ERROR):
+        return (PyObject *)self;
+    case Z_STREAM_ERROR:
         Py_DECREF(self);
         PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
         return NULL;
-    case (Z_MEM_ERROR):
+    case Z_MEM_ERROR:
         Py_DECREF(self);
         PyErr_SetString(PyExc_MemoryError,
                         "Can't allocate memory for decompression object");
@@ -621,113 +658,90 @@ static PyObject *
 zlib_Compress_compress_impl(compobject *self, Py_buffer *data)
 /*[clinic end generated code: output=5d5cd791cbc6a7f4 input=0d95908d6e64fab8]*/
 {
+    PyObject *RetVal = NULL;
+    Py_ssize_t ibuflen, obuflen = DEF_BUF_SIZE;
     int err;
-    unsigned int inplen;
-    unsigned int length = DEF_BUF_SIZE, new_length;
-    PyObject *RetVal;
-    Byte *input;
-    unsigned long start_total_out;
-
-    if ((size_t)data->len > UINT_MAX) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "Size does not fit in an unsigned int");
-        return NULL;
-    }
-    input = data->buf;
-    inplen = (unsigned int)data->len;
 
-    if (!(RetVal = PyBytes_FromStringAndSize(NULL, length)))
-        return NULL;
+    self->zst.next_in = data->buf;
+    ibuflen = data->len;
 
     ENTER_ZLIB(self);
 
-    start_total_out = self->zst.total_out;
-    self->zst.avail_in = inplen;
-    self->zst.next_in = input;
-    self->zst.avail_out = length;
-    self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal);
-
-    Py_BEGIN_ALLOW_THREADS
-    err = deflate(&(self->zst), Z_NO_FLUSH);
-    Py_END_ALLOW_THREADS
-
-    /* while Z_OK and the output buffer is full, there might be more output,
-       so extend the output buffer and try again */
-    while (err == Z_OK && self->zst.avail_out == 0) {
-        if (length <= (UINT_MAX >> 1))
-            new_length = length << 1;
-        else
-            new_length = UINT_MAX;
-        if (_PyBytes_Resize(&RetVal, new_length) < 0) {
-            Py_CLEAR(RetVal);
-            goto done;
-        }
-        self->zst.next_out =
-            (unsigned char *)PyBytes_AS_STRING(RetVal) + length;
-        self->zst.avail_out = length;
-        length = new_length;
+    do {
+        arrange_input_buffer(&self->zst, &ibuflen);
 
-        Py_BEGIN_ALLOW_THREADS
-        err = deflate(&(self->zst), Z_NO_FLUSH);
-        Py_END_ALLOW_THREADS
-    }
-    /* We will only get Z_BUF_ERROR if the output buffer was full but
-       there wasn't more output when we tried again, so it is not an error
-       condition.
-    */
+        do {
+            obuflen = arrange_output_buffer(&self->zst, &RetVal, obuflen);
+            if (obuflen < 0)
+                goto error;
 
-    if (err != Z_OK && err != Z_BUF_ERROR) {
-        zlib_error(self->zst, err, "while compressing data");
-        Py_CLEAR(RetVal);
-        goto done;
-    }
-    if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) {
-        Py_CLEAR(RetVal);
-    }
+            Py_BEGIN_ALLOW_THREADS
+            err = deflate(&self->zst, Z_NO_FLUSH);
+            Py_END_ALLOW_THREADS
+
+            if (err == Z_STREAM_ERROR) {
+                zlib_error(self->zst, err, "while compressing data");
+                goto error;
+            }
+
+        } while (self->zst.avail_out == 0);
+        assert(self->zst.avail_in == 0);
+
+    } while (ibuflen != 0);
+
+    if (_PyBytes_Resize(&RetVal, self->zst.next_out -
+                        (Byte *)PyBytes_AS_STRING(RetVal)) == 0)
+        goto success;
 
- done:
+ error:
+    Py_CLEAR(RetVal);
+ success:
     LEAVE_ZLIB(self);
     return RetVal;
 }
 
-/* Helper for objdecompress() and unflush(). Saves any unconsumed input data in
+/* Helper for objdecompress() and flush(). Saves any unconsumed input data in
    self->unused_data or self->unconsumed_tail, as appropriate. */
 static int
-save_unconsumed_input(compobject *self, int err)
+save_unconsumed_input(compobject *self, Py_buffer *data, int err)
 {
     if (err == Z_STREAM_END) {
         /* The end of the compressed data has been reached. Store the leftover
            input data in self->unused_data. */
         if (self->zst.avail_in > 0) {
             Py_ssize_t old_size = PyBytes_GET_SIZE(self->unused_data);
-            Py_ssize_t new_size;
+            Py_ssize_t new_size, left_size;
             PyObject *new_data;
-            if ((size_t)self->zst.avail_in > (size_t)UINT_MAX - (size_t)old_size) {
+            left_size = (Byte *)data->buf + data->len - self->zst.next_in;
+            if (left_size > (PY_SSIZE_T_MAX - old_size)) {
                 PyErr_NoMemory();
                 return -1;
             }
-            new_size = old_size + self->zst.avail_in;
+            new_size = old_size + left_size;
             new_data = PyBytes_FromStringAndSize(NULL, new_size);
             if (new_data == NULL)
                 return -1;
             Py_MEMCPY(PyBytes_AS_STRING(new_data),
                       PyBytes_AS_STRING(self->unused_data), old_size);
             Py_MEMCPY(PyBytes_AS_STRING(new_data) + old_size,
-                      self->zst.next_in, self->zst.avail_in);
+                      self->zst.next_in, left_size);
             Py_SETREF(self->unused_data, new_data);
             self->zst.avail_in = 0;
         }
     }
+
     if (self->zst.avail_in > 0 || PyBytes_GET_SIZE(self->unconsumed_tail)) {
         /* This code handles two distinct cases:
            1. Output limit was reached. Save leftover input in unconsumed_tail.
            2. All input data was consumed. Clear unconsumed_tail. */
+        Py_ssize_t left_size = (Byte *)data->buf + data->len - self->zst.next_in;
         PyObject *new_data = PyBytes_FromStringAndSize(
-                (char *)self->zst.next_in, self->zst.avail_in);
+                (char *)self->zst.next_in, left_size);
         if (new_data == NULL)
             return -1;
         Py_SETREF(self->unconsumed_tail, new_data);
     }
+
     return 0;
 }
 
@@ -736,7 +750,7 @@ zlib.Decompress.decompress
 
     data: Py_buffer
         The binary data to decompress.
-    max_length: capped_uint = 0
+    max_length: ssize_t = 0
         The maximum allowable length of the decompressed data.
         Unconsumed input data will be stored in
         the unconsumed_tail attribute.
@@ -751,85 +765,72 @@ Call the flush() method to clear these buffers.
 
 static PyObject *
 zlib_Decompress_decompress_impl(compobject *self, Py_buffer *data,
-                                unsigned int max_length)
-/*[clinic end generated code: output=b82e2a2c19f5fe7b input=68b6508ab07c2cf0]*/
+                                Py_ssize_t max_length)
+/*[clinic end generated code: output=6e5173c74e710352 input=d6de9b53c4566b8a]*/
 {
-    int err;
-    unsigned int old_length, length = DEF_BUF_SIZE;
+    int err = Z_OK;
+    Py_ssize_t ibuflen, obuflen = DEF_BUF_SIZE, hard_limit;
     PyObject *RetVal = NULL;
-    unsigned long start_total_out;
 
-    if ((size_t)data->len > UINT_MAX) {
-        PyErr_SetString(PyExc_OverflowError,
-                        "Size does not fit in an unsigned int");
+    if (max_length < 0) {
+        PyErr_SetString(PyExc_ValueError, "max_length must be non-negative");
         return NULL;
-    }
-
-    /* limit amount of data allocated to max_length */
-    if (max_length && length > max_length)
-        length = max_length;
-    if (!(RetVal = PyBytes_FromStringAndSize(NULL, length)))
-        return NULL;
-
-    ENTER_ZLIB(self);
+    } else if (max_length == 0)
+        hard_limit = PY_SSIZE_T_MAX;
+    else
+        hard_limit = max_length;
 
-    start_total_out = self->zst.total_out;
-    self->zst.avail_in = (unsigned int)data->len;
     self->zst.next_in = data->buf;
-    self->zst.avail_out = length;
-    self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal);
+    ibuflen = data->len;
 
-    Py_BEGIN_ALLOW_THREADS
-    err = inflate(&(self->zst), Z_SYNC_FLUSH);
-    Py_END_ALLOW_THREADS
+    /* limit amount of data allocated to max_length */
+    if (max_length && obuflen > max_length)
+        obuflen = max_length;
 
-    if (err == Z_NEED_DICT && self->zdict != NULL) {
-        if (set_inflate_zdict(self) < 0) {
-            Py_DECREF(RetVal);
-            RetVal = NULL;
-            goto error;
-        }
+    ENTER_ZLIB(self);
 
-        /* Repeat the call to inflate. */
-        Py_BEGIN_ALLOW_THREADS
-        err = inflate(&(self->zst), Z_SYNC_FLUSH);
-        Py_END_ALLOW_THREADS
-    }
+    do {
+        arrange_input_buffer(&self->zst, &ibuflen);
+
+        do {
+            obuflen = arrange_output_buffer_with_maximum(&self->zst, &RetVal,
+                                                         obuflen, hard_limit);
+            if (obuflen == -2) {
+                if (max_length > 0) {
+                    goto save;
+                }
+                PyErr_NoMemory();
+            }
+            if (obuflen < 0) {
+                goto abort;
+            }
 
-    /* While Z_OK and the output buffer is full, there might be more output.
-       So extend the output buffer and try again.
-    */
-    while (err == Z_OK && self->zst.avail_out == 0) {
-        /* If max_length set, don't continue decompressing if we've already
-           reached the limit.
-        */
-        if (max_length && length >= max_length)
-            break;
+            Py_BEGIN_ALLOW_THREADS
+            err = inflate(&self->zst, Z_SYNC_FLUSH);
+            Py_END_ALLOW_THREADS
 
-        /* otherwise, ... */
-        old_length = length;
-        length = length << 1;
-        if (max_length && length > max_length)
-            length = max_length;
+            switch (err) {
+            case Z_OK:            /* fall through */
+            case Z_BUF_ERROR:     /* fall through */
+            case Z_STREAM_END:
+                break;
+            default:
+                if (err == Z_NEED_DICT && self->zdict != NULL) {
+                    if (set_inflate_zdict(self) < 0)
+                        goto abort;
+                    else
+                        break;
+                }
+                goto save;
+            }
 
-        if (_PyBytes_Resize(&RetVal, length) < 0) {
-            Py_CLEAR(RetVal);
-            goto error;
-        }
-        self->zst.next_out =
-            (unsigned char *)PyBytes_AS_STRING(RetVal) + old_length;
-        self->zst.avail_out = length - old_length;
+        } while (self->zst.avail_out == 0 || err == Z_NEED_DICT);
 
-        Py_BEGIN_ALLOW_THREADS
-        err = inflate(&(self->zst), Z_SYNC_FLUSH);
-        Py_END_ALLOW_THREADS
-    }
+    } while (err != Z_STREAM_END && ibuflen != 0);
 
-    if (save_unconsumed_input(self, err) < 0) {
-        Py_DECREF(RetVal);
-        RetVal = NULL;
-        goto error;
-    }
+ save:
+    if (save_unconsumed_input(self, data, err) < 0)
+        goto abort;
 
     if (err == Z_STREAM_END) {
         /* This is the logical place to call inflateEnd, but the old behaviour
@@ -841,16 +842,16 @@ zlib_Decompress_decompress_impl(compobject *self, Py_buffer *data,
            not an error condition.
         */
         zlib_error(self->zst, err, "while decompressing data");
-        Py_DECREF(RetVal);
-        RetVal = NULL;
-        goto error;
+        goto abort;
     }
 
-    if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) {
-        Py_CLEAR(RetVal);
-    }
+    if (_PyBytes_Resize(&RetVal, self->zst.next_out -
+                        (Byte *)PyBytes_AS_STRING(RetVal)) == 0)
+        goto success;
 
- error:
+ abort:
+    Py_CLEAR(RetVal);
+ success:
     LEAVE_ZLIB(self);
     return RetVal;
 }
@@ -873,9 +874,8 @@ zlib_Compress_flush_impl(compobject *self, int mode)
 /*[clinic end generated code: output=a203f4cefc9de727 input=73ed066794bd15bc]*/
 {
     int err;
-    unsigned int length = DEF_BUF_SIZE, new_length;
-    PyObject *RetVal;
-    unsigned long start_total_out;
+    Py_ssize_t length = DEF_BUF_SIZE;
+    PyObject *RetVal = NULL;
 
     /* Flushing with Z_NO_FLUSH is a no-op, so there's no point in
        doing any work at all; just return an empty string. */
@@ -883,50 +883,37 @@ zlib_Compress_flush_impl(compobject *self, int mode)
         return PyBytes_FromStringAndSize(NULL, 0);
     }
 
-    if (!(RetVal = PyBytes_FromStringAndSize(NULL, length)))
-        return NULL;
-
     ENTER_ZLIB(self);
 
-    start_total_out = self->zst.total_out;
     self->zst.avail_in = 0;
-    self->zst.avail_out = length;
-    self->zst.next_out = (unsigned char *)PyBytes_AS_STRING(RetVal);
-
-    Py_BEGIN_ALLOW_THREADS
-    err = deflate(&(self->zst), mode);
-    Py_END_ALLOW_THREADS
-
-    /* while Z_OK and the output buffer is full, there might be more output,
-       so extend the output buffer and try again */
-    while (err == Z_OK && self->zst.avail_out == 0) {
-        if (length <= (UINT_MAX >> 1))
-            new_length = length << 1;
-        else
-            new_length = UINT_MAX;
-        if (_PyBytes_Resize(&RetVal, new_length) < 0) {
+
+    do {
+        length = arrange_output_buffer(&self->zst, &RetVal, length);
+        if (length < 0) {
             Py_CLEAR(RetVal);
             goto error;
         }
-        self->zst.next_out =
-            (unsigned char *)PyBytes_AS_STRING(RetVal) + length;
-        self->zst.avail_out = length;
-        length = new_length;
 
         Py_BEGIN_ALLOW_THREADS
-        err = deflate(&(self->zst), mode);
+        err = deflate(&self->zst, mode);
         Py_END_ALLOW_THREADS
-    }
+
+        if (err == Z_STREAM_ERROR) {
+            zlib_error(self->zst, err, "while flushing");
+            Py_CLEAR(RetVal);
+            goto error;
+        }
+    } while (self->zst.avail_out == 0);
+    assert(self->zst.avail_in == 0);
 
     /* If mode is Z_FINISH, we also have to call deflateEnd() to free
        various data structures. Note we should only get Z_STREAM_END when
        mode is Z_FINISH, but checking both for safety*/
     if (err == Z_STREAM_END && mode == Z_FINISH) {
-        err = deflateEnd(&(self->zst));
+        err = deflateEnd(&self->zst);
         if (err != Z_OK) {
             zlib_error(self->zst, err, "while finishing compression");
-            Py_DECREF(RetVal);
-            RetVal = NULL;
+            Py_CLEAR(RetVal);
             goto error;
         }
         else
@@ -936,20 +923,18 @@ zlib_Compress_flush_impl(compobject *self, int mode)
            but there wasn't more output when we tried again, so it is
            not an error condition.
         */
-    } else if (err!=Z_OK && err!=Z_BUF_ERROR) {
+    } else if (err != Z_OK && err != Z_BUF_ERROR) {
         zlib_error(self->zst, err, "while flushing");
-        Py_DECREF(RetVal);
-        RetVal = NULL;
+        Py_CLEAR(RetVal);
         goto error;
     }
 
-    if (_PyBytes_Resize(&RetVal, self->zst.total_out - start_total_out) < 0) {
+    if (_PyBytes_Resize(&RetVal, self->zst.next_out -
+                        (Byte *)PyBytes_AS_STRING(RetVal)) < 0)
         Py_CLEAR(RetVal);
-    }
 
  error:
     LEAVE_ZLIB(self);
-
     return RetVal;
 }
 
@@ -976,13 +961,13 @@ zlib_Compress_copy_impl(compobject *self)
      */
     ENTER_ZLIB(self);
     err = deflateCopy(&retval->zst, &self->zst);
-    switch(err) {
-    case(Z_OK):
+    switch (err) {
+    case Z_OK:
         break;
-    case(Z_STREAM_ERROR):
+    case Z_STREAM_ERROR:
         PyErr_SetString(PyExc_ValueError, "Inconsistent stream state");
         goto error;
-    case(Z_MEM_ERROR):
+    case Z_MEM_ERROR:
         PyErr_SetString(PyExc_MemoryError,
                         "Can't allocate memory for compression object");
         goto error;
@@ -1031,13 +1016,13 @@ zlib_Decompress_copy_impl(compobject *self)
      */
     ENTER_ZLIB(self);
     err = inflateCopy(&retval->zst, &self->zst);
-    switch(err) {
-    case(Z_OK):
+    switch (err) {
+    case Z_OK:
         break;
-    case(Z_STREAM_ERROR):
+    case Z_STREAM_ERROR:
         PyErr_SetString(PyExc_ValueError, "Inconsistent stream state");
         goto error;
-    case(Z_MEM_ERROR):
+    case Z_MEM_ERROR:
         PyErr_SetString(PyExc_MemoryError,
                         "Can't allocate memory for decompression object");
         goto error;
@@ -1070,7 +1055,7 @@ error:
 /*[clinic input]
 zlib.Decompress.flush
 
-    length: capped_uint(c_default="DEF_BUF_SIZE") = zlib.DEF_BUF_SIZE
+    length: ssize_t(c_default="DEF_BUF_SIZE") = zlib.DEF_BUF_SIZE
         the initial size of the output buffer.
     /
 
@@ -1078,88 +1063,84 @@ Return a bytes object containing any remaining decompressed data.
 [clinic start generated code]*/
 
 static PyObject *
-zlib_Decompress_flush_impl(compobject *self, unsigned int length)
-/*[clinic end generated code: output=db6fb753ab698e22 input=1bb961eb21b62aa0]*/
+zlib_Decompress_flush_impl(compobject *self, Py_ssize_t length)
+/*[clinic end generated code: output=68c75ea127cbe654 input=aa4ec37f3aef4da0]*/
 {
-    int err;
-    unsigned int new_length;
-    PyObject * retval = NULL;
-    unsigned long start_total_out;
-    Py_ssize_t size;
+    int err, flush;
+    Py_buffer data;
+    PyObject *RetVal = NULL;
+    Py_ssize_t ibuflen;
 
-    if (length == 0) {
+    if (length <= 0) {
         PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
         return NULL;
     }
 
-    if (!(retval = PyBytes_FromStringAndSize(NULL, length)))
+    if (PyObject_GetBuffer(self->unconsumed_tail, &data, PyBUF_SIMPLE) == -1)
         return NULL;
 
-
     ENTER_ZLIB(self);
 
-    size = PyBytes_GET_SIZE(self->unconsumed_tail);
-
-    start_total_out = self->zst.total_out;
-    /* save_unconsumed_input() ensures that unconsumed_tail length is lesser
-       or equal than UINT_MAX */
-    self->zst.avail_in = Py_SAFE_DOWNCAST(size, Py_ssize_t, unsigned int);
-    self->zst.next_in = (Byte *)PyBytes_AS_STRING(self->unconsumed_tail);
-    self->zst.avail_out = length;
-    self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval);
-
-    Py_BEGIN_ALLOW_THREADS
-    err = inflate(&(self->zst), Z_FINISH);
-    Py_END_ALLOW_THREADS
-
-    /* while Z_OK and the output buffer is full, there might be more output,
-       so extend the output buffer and try again */
-    while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) {
-        if (length <= (UINT_MAX >> 1))
-            new_length = length << 1;
-        else
-            new_length = UINT_MAX;
-        if (_PyBytes_Resize(&retval, new_length) < 0) {
-            Py_CLEAR(retval);
-            goto error;
-        }
-        self->zst.next_out = (Byte *)PyBytes_AS_STRING(retval) + length;
-        self->zst.avail_out = length;
-        length = new_length;
+    self->zst.next_in = data.buf;
+    ibuflen = data.len;
 
-        Py_BEGIN_ALLOW_THREADS
-        err = inflate(&(self->zst), Z_FINISH);
-        Py_END_ALLOW_THREADS
-    }
+    do {
+        arrange_input_buffer(&self->zst, &ibuflen);
+        flush = ibuflen == 0 ? Z_FINISH : Z_NO_FLUSH;
 
-    if (save_unconsumed_input(self, err) < 0) {
-        Py_DECREF(retval);
-        retval = NULL;
-        goto error;
-    }
+        do {
+            length = arrange_output_buffer(&self->zst, &RetVal, length);
+            if (length < 0)
+                goto abort;
+
+            Py_BEGIN_ALLOW_THREADS
+            err = inflate(&self->zst, flush);
+            Py_END_ALLOW_THREADS
+
+            switch (err) {
+            case Z_OK:            /* fall through */
+            case Z_BUF_ERROR:     /* fall through */
+            case Z_STREAM_END:
+                break;
+            default:
+                if (err == Z_NEED_DICT && self->zdict != NULL) {
+                    if (set_inflate_zdict(self) < 0)
+                        goto abort;
+                    else
+                        break;
+                }
+                goto save;
+            }
+
+        } while (self->zst.avail_out == 0 || err == Z_NEED_DICT);
+
+    } while (err != Z_STREAM_END && ibuflen != 0);
+
+ save:
+    if (save_unconsumed_input(self, &data, err) < 0)
+        goto abort;
 
     /* If at end of stream, clean up any memory allocated by zlib. */
     if (err == Z_STREAM_END) {
         self->eof = 1;
         self->is_initialised = 0;
-        err = inflateEnd(&(self->zst));
+        err = inflateEnd(&self->zst);
         if (err != Z_OK) {
             zlib_error(self->zst, err, "while finishing decompression");
-            Py_DECREF(retval);
-            retval = NULL;
-            goto error;
+            goto abort;
         }
     }
 
-    if (_PyBytes_Resize(&retval, self->zst.total_out - start_total_out) < 0) {
-        Py_CLEAR(retval);
-    }
-
-error:
+    if (_PyBytes_Resize(&RetVal, self->zst.next_out -
+                        (Byte *)PyBytes_AS_STRING(RetVal)) == 0)
+        goto success;
 
+ abort:
+    Py_CLEAR(RetVal);
+ success:
+    PyBuffer_Release(&data);
     LEAVE_ZLIB(self);
-
-    return retval;
+    return RetVal;
 }
 
 #include "clinic/zlibmodule.c.h"
@@ -1206,8 +1187,8 @@ The returned checksum is an integer.
 [clinic start generated code]*/
 
 static PyObject *
-zlib_adler32_impl(PyModuleDef *module, Py_buffer *data, unsigned int value)
-/*[clinic end generated code: output=51d6d75ee655c78a input=6ff4557872160e88]*/
+zlib_adler32_impl(PyObject *module, Py_buffer *data, unsigned int value)
+/*[clinic end generated code: output=422106f5ca8c92c0 input=6ff4557872160e88]*/
 {
     /* Releasing the GIL for very small buffers is inefficient
        and may lower performance */
@@ -1245,8 +1226,8 @@ The returned checksum is an integer.
 [clinic start generated code]*/
 
 static PyObject *
-zlib_crc32_impl(PyModuleDef *module, Py_buffer *data, unsigned int value)
-/*[clinic end generated code: output=c1e986e74fe7b623 input=26c3ed430fa00b4c]*/
+zlib_crc32_impl(PyObject *module, Py_buffer *data, unsigned int value)
+/*[clinic end generated code: output=63499fa20af7ea25 input=26c3ed430fa00b4c]*/
 {
     int signed_val;
 
index a0362e7..88205bd 100644 (file)
@@ -1724,21 +1724,22 @@ PySequence_Tuple(PyObject *v)
             break;
         }
         if (j >= n) {
-            Py_ssize_t oldn = n;
+            size_t newn = (size_t)n;
             /* The over-allocation strategy can grow a bit faster
                than for lists because unlike lists the
                over-allocation isn't permanent -- we reclaim
                the excess before the end of this routine.
                So, grow by ten and then add 25%.
             */
-            n += 10;
-            n += n >> 2;
-            if (n < oldn) {
+            newn += 10u;
+            newn += newn >> 2;
+            if (newn > PY_SSIZE_T_MAX) {
                 /* Check for overflow */
                 PyErr_NoMemory();
                 Py_DECREF(item);
                 goto Fail;
             }
+            n = (Py_ssize_t)newn;
             if (_PyTuple_Resize(&result, n) != 0) {
                 Py_DECREF(item);
                 goto Fail;
@@ -2109,7 +2110,7 @@ _Py_CheckFunctionResult(PyObject *func, PyObject *result, const char *where)
                              "%s returned NULL without setting an error",
                              where);
 #ifdef Py_DEBUG
-            /* Ensure that the bug is catched in debug mode */
+            /* Ensure that the bug is caught in debug mode */
             Py_FatalError("a function returned NULL without setting an error");
 #endif
             return NULL;
@@ -2132,7 +2133,7 @@ _Py_CheckFunctionResult(PyObject *func, PyObject *result, const char *where)
                              where);
             _PyErr_ChainExceptions(exc, val, tb);
 #ifdef Py_DEBUG
-            /* Ensure that the bug is catched in debug mode */
+            /* Ensure that the bug is caught in debug mode */
             Py_FatalError("a function returned a result with an error set");
 #endif
             return NULL;
index 277be59..3fad6d8 100644 (file)
@@ -246,7 +246,6 @@ PyByteArray_Resize(PyObject *self, Py_ssize_t requested_size)
 PyObject *
 PyByteArray_Concat(PyObject *a, PyObject *b)
 {
-    Py_ssize_t size;
     Py_buffer va, vb;
     PyByteArrayObject *result = NULL;
 
@@ -259,13 +258,13 @@ PyByteArray_Concat(PyObject *a, PyObject *b)
             goto done;
     }
 
-    size = va.len + vb.len;
-    if (size < 0) {
-            PyErr_NoMemory();
-            goto done;
+    if (va.len > PY_SSIZE_T_MAX - vb.len) {
+        PyErr_NoMemory();
+        goto done;
     }
 
-    result = (PyByteArrayObject *) PyByteArray_FromStringAndSize(NULL, size);
+    result = (PyByteArrayObject *) \
+        PyByteArray_FromStringAndSize(NULL, va.len + vb.len);
     if (result != NULL) {
         memcpy(result->ob_bytes, va.buf, va.len);
         memcpy(result->ob_bytes + va.len, vb.buf, vb.len);
@@ -284,13 +283,15 @@ bytearray_format(PyByteArrayObject *self, PyObject *args)
 {
     PyObject *bytes_in, *bytes_out, *res;
     char *bytestring;
+    Py_ssize_t bytesize;
 
     if (self == NULL || !PyByteArray_Check(self) || args == NULL) {
         PyErr_BadInternalCall();
         return NULL;
     }
     bytestring = PyByteArray_AS_STRING(self);
-    bytes_in = PyBytes_FromString(bytestring);
+    bytesize = PyByteArray_GET_SIZE(self);
+    bytes_in = PyBytes_FromStringAndSize(bytestring, bytesize);
     if (bytes_in == NULL)
         return NULL;
     bytes_out = _PyBytes_Format(bytes_in, args);
@@ -315,7 +316,6 @@ bytearray_length(PyByteArrayObject *self)
 static PyObject *
 bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
 {
-    Py_ssize_t mysize;
     Py_ssize_t size;
     Py_buffer vo;
 
@@ -325,17 +325,16 @@ bytearray_iconcat(PyByteArrayObject *self, PyObject *other)
         return NULL;
     }
 
-    mysize = Py_SIZE(self);
-    size = mysize + vo.len;
-    if (size < 0) {
+    size = Py_SIZE(self);
+    if (size > PY_SSIZE_T_MAX - vo.len) {
         PyBuffer_Release(&vo);
         return PyErr_NoMemory();
     }
-    if (PyByteArray_Resize((PyObject *)self, size) < 0) {
+    if (PyByteArray_Resize((PyObject *)self, size + vo.len) < 0) {
         PyBuffer_Release(&vo);
         return NULL;
     }
-    memcpy(PyByteArray_AS_STRING(self) + mysize, vo.buf, vo.len);
+    memcpy(PyByteArray_AS_STRING(self) + size, vo.buf, vo.len);
     PyBuffer_Release(&vo);
     Py_INCREF(self);
     return (PyObject *)self;
@@ -509,7 +508,7 @@ bytearray_setslice_linear(PyByteArrayObject *self,
 
                If growth < 0 and lo != 0, the operation is completed, but a
                MemoryError is still raised and the memory block is not
-               shrinked. Otherwise, the bytearray is restored in its previous
+               shrunk. Otherwise, the bytearray is restored in its previous
                state and a MemoryError is raised. */
             if (lo == 0) {
                 self->ob_start += growth;
@@ -2477,7 +2476,17 @@ bytearray_extend(PyByteArrayObject *self, PyObject *iterable_of_ints)
         Py_DECREF(item);
 
         if (len >= buf_size) {
-            buf_size = len + (len >> 1) + 1;
+            Py_ssize_t addition;
+            if (len == PY_SSIZE_T_MAX) {
+                Py_DECREF(it);
+                Py_DECREF(bytearray_obj);
+                return PyErr_NoMemory();
+            }
+            addition = len >> 1;
+            if (addition > PY_SSIZE_T_MAX - len - 1)
+                buf_size = PY_SSIZE_T_MAX;
+            else
+                buf_size = len + addition + 1;
             if (PyByteArray_Resize((PyObject *)bytearray_obj, buf_size) < 0) {
                 Py_DECREF(it);
                 Py_DECREF(bytearray_obj);
@@ -3192,8 +3201,12 @@ static PyObject *
 bytearrayiter_length_hint(bytesiterobject *it)
 {
     Py_ssize_t len = 0;
-    if (it->it_seq)
+    if (it->it_seq) {
         len = PyByteArray_GET_SIZE(it->it_seq) - it->it_index;
+        if (len < 0) {
+            len = 0;
+        }
+    }
     return PyLong_FromSsize_t(len);
 }
 
index c2aa65c..673bb00 100644 (file)
@@ -882,7 +882,7 @@ _PyBytes_Format(PyObject *format, PyObject *args)
                 if (width > len)
                     width--;
             }
-            if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
+            if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) {
                 assert(pbuf[0] == '0');
                 assert(pbuf[1] == c);
                 if (fill != ' ') {
@@ -904,8 +904,7 @@ _PyBytes_Format(PyObject *format, PyObject *args)
             if (fill == ' ') {
                 if (sign)
                     *res++ = sign;
-                if ((flags & F_ALT) &&
-                    (c == 'x' || c == 'X')) {
+                if ((flags & F_ALT) && (c == 'o' || c == 'x' || c == 'X')) {
                     assert(pbuf[0] == '0');
                     assert(pbuf[1] == c);
                     *res++ = *pbuf++;
@@ -1265,7 +1264,6 @@ bytes_length(PyBytesObject *a)
 static PyObject *
 bytes_concat(PyObject *a, PyObject *b)
 {
-    Py_ssize_t size;
     Py_buffer va, vb;
     PyObject *result = NULL;
 
@@ -1290,13 +1288,12 @@ bytes_concat(PyObject *a, PyObject *b)
         goto done;
     }
 
-    size = va.len + vb.len;
-    if (size < 0) {
+    if (va.len > PY_SSIZE_T_MAX - vb.len) {
         PyErr_NoMemory();
         goto done;
     }
 
-    result = PyBytes_FromStringAndSize(NULL, size);
+    result = PyBytes_FromStringAndSize(NULL, va.len + vb.len);
     if (result != NULL) {
         memcpy(PyBytes_AS_STRING(result), va.buf, va.len);
         memcpy(PyBytes_AS_STRING(result) + va.len, vb.buf, vb.len);
@@ -3552,11 +3549,15 @@ _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
     PyObject *v;
     PyBytesObject *sv;
     v = *pv;
-    if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
-        *pv = 0;
-        Py_DECREF(v);
-        PyErr_BadInternalCall();
-        return -1;
+    if (!PyBytes_Check(v) || newsize < 0) {
+        goto error;
+    }
+    if (Py_SIZE(v) == newsize) {
+        /* return early if newsize equals to v->ob_size */
+        return 0;
+    }
+    if (Py_REFCNT(v) != 1) {
+        goto error;
     }
     /* XXX UNREF/NEWREF interface should be more symmetrical */
     _Py_DEC_REFTOTAL;
@@ -3574,6 +3575,11 @@ _PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
     sv->ob_sval[newsize] = '\0';
     sv->ob_shash = -1;          /* invalidate cached hash value */
     return 0;
+error:
+    *pv = 0;
+    Py_DECREF(v);
+    PyErr_BadInternalCall();
+    return -1;
 }
 
 void
index 964ae62..c334626 100644 (file)
@@ -11,21 +11,21 @@ static int
 all_name_chars(PyObject *o)
 {
     static char ok_name_char[256];
-    static unsigned char *name_chars = (unsigned char *)NAME_CHARS;
-    PyUnicodeObject *u = (PyUnicodeObject *)o;
-    const unsigned char *s;
+    static const unsigned char *name_chars = (unsigned char *)NAME_CHARS;
+    const unsigned char *s, *e;
 
-    if (!PyUnicode_Check(o) || PyUnicode_READY(u) == -1 ||
-        PyUnicode_MAX_CHAR_VALUE(u) >= 128)
+    if (!PyUnicode_Check(o) || PyUnicode_READY(o) == -1 ||
+        !PyUnicode_IS_ASCII(o))
         return 0;
 
     if (ok_name_char[*name_chars] == 0) {
-        unsigned char *p;
+        const unsigned char *p;
         for (p = name_chars; *p; p++)
             ok_name_char[*p] = 1;
     }
-    s = PyUnicode_1BYTE_DATA(u);
-    while (*s) {
+    s = PyUnicode_1BYTE_DATA(o);
+    e = s + PyUnicode_GET_LENGTH(o);
+    while (s != e) {
         if (ok_name_char[*s++] == 0)
             return 0;
     }
@@ -46,6 +46,52 @@ intern_strings(PyObject *tuple)
     }
 }
 
+/* Intern selected string constants */
+static int
+intern_string_constants(PyObject *tuple)
+{
+    int modified = 0;
+    Py_ssize_t i;
+
+    for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
+        PyObject *v = PyTuple_GET_ITEM(tuple, i);
+        if (PyUnicode_CheckExact(v)) {
+            if (all_name_chars(v)) {
+                PyObject *w = v;
+                PyUnicode_InternInPlace(&v);
+                if (w != v) {
+                    PyTuple_SET_ITEM(tuple, i, v);
+                    modified = 1;
+                }
+            }
+        }
+        else if (PyTuple_CheckExact(v)) {
+            intern_string_constants(v);
+        }
+        else if (PyFrozenSet_CheckExact(v)) {
+            PyObject *w = v;
+            PyObject *tmp = PySequence_Tuple(v);
+            if (tmp == NULL) {
+                PyErr_Clear();
+                continue;
+            }
+            if (intern_string_constants(tmp)) {
+                v = PyFrozenSet_New(tmp);
+                if (v == NULL) {
+                    PyErr_Clear();
+                }
+                else {
+                    PyTuple_SET_ITEM(tuple, i, v);
+                    Py_DECREF(w);
+                    modified = 1;
+                }
+            }
+            Py_DECREF(tmp);
+        }
+    }
+    return modified;
+}
+
 
 PyCodeObject *
 PyCode_New(int argcount, int kwonlyargcount,
@@ -84,13 +130,7 @@ PyCode_New(int argcount, int kwonlyargcount,
     intern_strings(varnames);
     intern_strings(freevars);
     intern_strings(cellvars);
-    /* Intern selected string constants */
-    for (i = PyTuple_GET_SIZE(consts); --i >= 0; ) {
-        PyObject *v = PyTuple_GetItem(consts, i);
-        if (!all_name_chars(v))
-            continue;
-        PyUnicode_InternInPlace(&PyTuple_GET_ITEM(consts, i));
-    }
+    intern_string_constants(consts);
     /* Create mapping between cells and arguments if needed. */
     if (n_cellvars) {
         Py_ssize_t total_args = argcount + kwonlyargcount +
@@ -718,7 +758,7 @@ _PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
     /* possible optimization: if f->f_lasti == instr_ub
        (likely to be a common case) then we already know
        instr_lb -- if we stored the matching value of p
-       somwhere we could skip the first while loop. */
+       somewhere we could skip the first while loop. */
 
     /* See lnotab_notes.txt for the description of
        co_lnotab.  A point to remember: increments to p
index a5bfb66..d82c5eb 100644 (file)
@@ -954,18 +954,29 @@ complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
     }
 
     nbr = r->ob_type->tp_as_number;
-    if (i != NULL)
-        nbi = i->ob_type->tp_as_number;
-    if (nbr == NULL || nbr->nb_float == NULL ||
-        ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
+    if (nbr == NULL || nbr->nb_float == NULL) {
         PyErr_Format(PyExc_TypeError,
-            "complex() argument must be a string or a number, not '%.200s'",
-            Py_TYPE(r)->tp_name);
+                     "complex() first argument must be a string or a number, "
+                     "not '%.200s'",
+                     Py_TYPE(r)->tp_name);
         if (own_r) {
             Py_DECREF(r);
         }
         return NULL;
     }
+    if (i != NULL) {
+        nbi = i->ob_type->tp_as_number;
+        if (nbi == NULL || nbi->nb_float == NULL) {
+            PyErr_Format(PyExc_TypeError,
+                         "complex() second argument must be a number, "
+                         "not '%.200s'",
+                         Py_TYPE(i)->tp_name);
+            if (own_r) {
+                Py_DECREF(r);
+            }
+            return NULL;
+        }
+    }
 
     /* If we get this far, then the "real" and "imag" parts should
        both be treated as numbers, and the constructor should return a
index d774586..747d218 100644 (file)
@@ -88,20 +88,17 @@ it's USABLE_FRACTION (currently two-thirds) full.
 /*
 Major subtleties ahead:  Most hash schemes depend on having a "good" hash
 function, in the sense of simulating randomness.  Python doesn't:  its most
-important hash functions (for strings and ints) are very regular in common
+important hash functions (for ints) are very regular in common
 cases:
 
-  >>> map(hash, (0, 1, 2, 3))
+  >>>[hash(i) for i in range(4)]
   [0, 1, 2, 3]
-  >>> map(hash, ("namea", "nameb", "namec", "named"))
-  [-1658398457, -1658398460, -1658398459, -1658398462]
-  >>>
 
 This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
 the low-order i bits as the initial table index is extremely fast, and there
-are no collisions at all for dicts indexed by a contiguous range of ints.
-The same is approximately true when keys are "consecutive" strings.  So this
-gives better-than-random behavior in common cases, and that's very desirable.
+are no collisions at all for dicts indexed by a contiguous range of ints. So
+this gives better-than-random behavior in common cases, and that's very
+desirable.
 
 OTOH, when collisions occur, the tendency to fill contiguous slices of the
 hash table makes a good collision resolution strategy crucial.  Taking only
@@ -988,8 +985,10 @@ make_keys_shared(PyObject *op)
             return NULL;
         }
         else if (mp->ma_keys->dk_lookup == lookdict_unicode) {
-            /* Remove dummy keys */
-            if (dictresize(mp, DK_SIZE(mp->ma_keys)))
+            /* Remove dummy keys
+             * -1 is required since dictresize() uses key size > minused
+             */
+            if (dictresize(mp, DK_SIZE(mp->ma_keys) - 1))
                 return NULL;
         }
         assert(mp->ma_keys->dk_lookup == lookdict_unicode_nodummy);
@@ -1247,13 +1246,31 @@ _PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
     return insertdict(mp, key, hash, value);
 }
 
+static int
+delitem_common(PyDictObject *mp, PyDictKeyEntry *ep, PyObject **value_addr)
+{
+    PyObject *old_key, *old_value;
+
+    old_value = *value_addr;
+    *value_addr = NULL;
+    mp->ma_used--;
+    if (!_PyDict_HasSplitTable(mp)) {
+        ENSURE_ALLOWS_DELETIONS(mp);
+        old_key = ep->me_key;
+        Py_INCREF(dummy);
+        ep->me_key = dummy;
+        Py_DECREF(old_key);
+    }
+    Py_DECREF(old_value);
+    return 0;
+}
+
 int
 PyDict_DelItem(PyObject *op, PyObject *key)
 {
     PyDictObject *mp;
     Py_hash_t hash;
     PyDictKeyEntry *ep;
-    PyObject *old_key, *old_value;
     PyObject **value_addr;
 
     if (!PyDict_Check(op)) {
@@ -1275,18 +1292,7 @@ PyDict_DelItem(PyObject *op, PyObject *key)
         _PyErr_SetKeyError(key);
         return -1;
     }
-    old_value = *value_addr;
-    *value_addr = NULL;
-    mp->ma_used--;
-    if (!_PyDict_HasSplitTable(mp)) {
-        ENSURE_ALLOWS_DELETIONS(mp);
-        old_key = ep->me_key;
-        Py_INCREF(dummy);
-        ep->me_key = dummy;
-        Py_DECREF(old_key);
-    }
-    Py_DECREF(old_value);
-    return 0;
+    return delitem_common(mp, ep, value_addr);
 }
 
 int
@@ -1294,7 +1300,6 @@ _PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
 {
     PyDictObject *mp;
     PyDictKeyEntry *ep;
-    PyObject *old_key, *old_value;
     PyObject **value_addr;
 
     if (!PyDict_Check(op)) {
@@ -1311,20 +1316,45 @@ _PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
         _PyErr_SetKeyError(key);
         return -1;
     }
-    old_value = *value_addr;
-    *value_addr = NULL;
-    mp->ma_used--;
-    if (!_PyDict_HasSplitTable(mp)) {
-        ENSURE_ALLOWS_DELETIONS(mp);
-        old_key = ep->me_key;
-        Py_INCREF(dummy);
-        ep->me_key = dummy;
-        Py_DECREF(old_key);
+    return delitem_common(mp, ep, value_addr);
+}
+
+int
+_PyDict_DelItemIf(PyObject *op, PyObject *key,
+                  int (*predicate)(PyObject *value))
+{
+    PyDictObject *mp;
+    Py_hash_t hash;
+    PyDictKeyEntry *ep;
+    PyObject **value_addr;
+    int res;
+
+    if (!PyDict_Check(op)) {
+        PyErr_BadInternalCall();
+        return -1;
     }
-    Py_DECREF(old_value);
-    return 0;
+    assert(key);
+    hash = PyObject_Hash(key);
+    if (hash == -1)
+        return -1;
+    mp = (PyDictObject *)op;
+    ep = (mp->ma_keys->dk_lookup)(mp, key, hash, &value_addr);
+    if (ep == NULL)
+        return -1;
+    if (*value_addr == NULL) {
+        _PyErr_SetKeyError(key);
+        return -1;
+    }
+    res = predicate(*value_addr);
+    if (res == -1)
+        return -1;
+    if (res > 0)
+        return delitem_common(mp, ep, value_addr);
+    else
+        return 0;
 }
 
+
 void
 PyDict_Clear(PyObject *op)
 {
@@ -2476,7 +2506,8 @@ dict_popitem(PyDictObject *mp)
     }
     /* Convert split table to combined table */
     if (mp->ma_keys->dk_lookup == lookdict_split) {
-        if (dictresize(mp, DK_SIZE(mp->ma_keys))) {
+        /* -1 is required since dictresize() uses key size > minused */
+        if (dictresize(mp, DK_SIZE(mp->ma_keys) - 1)) {
             Py_DECREF(res);
             return NULL;
         }
@@ -3657,7 +3688,7 @@ dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
         return 0;
     key = PyTuple_GET_ITEM(obj, 0);
     value = PyTuple_GET_ITEM(obj, 1);
-    found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
+    found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
     if (found == NULL) {
         if (PyErr_Occurred())
             return -1;
@@ -3851,10 +3882,16 @@ _PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
                 CACHED_KEYS(tp) = NULL;
                 DK_DECREF(cached);
             }
-        } else {
+        }
+        else {
+            int was_shared = cached == ((PyDictObject *)dict)->ma_keys;
             res = PyDict_SetItem(dict, key, value);
-            if (cached != ((PyDictObject *)dict)->ma_keys) {
-                /* Either update tp->ht_cached_keys or delete it */
+            /* PyDict_SetItem() may call dictresize() and convert split table
+             * into combined table.  In such case, convert it to split
+             * table again and update type's shared key only when this is
+             * the only dict sharing key with the type.
+             */
+            if (was_shared && cached != ((PyDictObject *)dict)->ma_keys) {
                 if (cached->dk_refcnt == 1) {
                     CACHED_KEYS(tp) = make_keys_shared(dict);
                 } else {
index aaff0bc..981ead2 100644 (file)
@@ -618,36 +618,38 @@ SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
 static int
 ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
 {
+    static char *kwlist[] = {"name", "path", 0};
+    PyObject *empty_tuple;
     PyObject *msg = NULL;
     PyObject *name = NULL;
     PyObject *path = NULL;
 
-/* Macro replacement doesn't allow ## to start the first line of a macro,
-   so we move the assignment and NULL check into the if-statement. */
-#define GET_KWD(kwd) { \
-    kwd = PyDict_GetItemString(kwds, #kwd); \
-    if (kwd) { \
-        Py_INCREF(kwd); \
-        Py_XSETREF(self->kwd, kwd); \
-        if (PyDict_DelItemString(kwds, #kwd)) \
-            return -1; \
-    } \
-    }
-
-    if (kwds) {
-        GET_KWD(name);
-        GET_KWD(path);
-    }
+    if (BaseException_init((PyBaseExceptionObject *)self, args, NULL) == -1)
+        return -1;
 
-    if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
+    empty_tuple = PyTuple_New(0);
+    if (!empty_tuple)
         return -1;
-    if (PyTuple_GET_SIZE(args) != 1)
-        return 0;
-    if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
+    if (!PyArg_ParseTupleAndKeywords(empty_tuple, kwds, "|$OO:ImportError", kwlist,
+                                     &name, &path)) {
+        Py_DECREF(empty_tuple);
         return -1;
+    }
+    Py_DECREF(empty_tuple);
 
-    Py_INCREF(msg);
-    Py_XSETREF(self->msg, msg);
+    if (name) {
+        Py_INCREF(name);
+        Py_XSETREF(self->name, name);
+    }
+    if (path) {
+        Py_INCREF(path);
+        Py_XSETREF(self->path, path);
+    }
+    if (PyTuple_GET_SIZE(args) == 1) {
+        msg = PyTuple_GET_ITEM(args, 0);
+        Py_INCREF(msg);
+        Py_XSETREF(self->msg, msg);
+    }
 
     return 0;
 }
@@ -1263,7 +1265,7 @@ SimpleExtendsException(PyExc_Exception, AttributeError,
  *    SyntaxError extends Exception
  */
 
-/* Helper function to customise error message for some syntax errors */
+/* Helper function to customize error message for some syntax errors */
 static int _report_missing_parentheses(PySyntaxErrorObject *self);
 
 static int
@@ -1855,7 +1857,7 @@ UnicodeEncodeError_str(PyObject *self)
         return PyUnicode_FromString("");
 
     /* Get reason and encoding as strings, which they might not be if
-       they've been modified after we were contructed. */
+       they've been modified after we were constructed. */
     reason_str = PyObject_Str(uself->reason);
     if (reason_str == NULL)
         goto done;
@@ -1980,7 +1982,7 @@ UnicodeDecodeError_str(PyObject *self)
         return PyUnicode_FromString("");
 
     /* Get reason and encoding as strings, which they might not be if
-       they've been modified after we were contructed. */
+       they've been modified after we were constructed. */
     reason_str = PyObject_Str(uself->reason);
     if (reason_str == NULL)
         goto done;
@@ -2078,7 +2080,7 @@ UnicodeTranslateError_str(PyObject *self)
         return PyUnicode_FromString("");
 
     /* Get reason as a string, which it might not be if it's been
-       modified after we were contructed. */
+       modified after we were constructed. */
     reason_str = PyObject_Str(uself->reason);
     if (reason_str == NULL)
         goto done;
index e6c327d..4cd6590 100644 (file)
@@ -697,8 +697,9 @@ PyTypeObject PyFunction_Type = {
    To declare a class method, use this idiom:
 
      class C:
-     def f(cls, arg1, arg2, ...): ...
-     f = classmethod(f)
+         @classmethod
+         def f(cls, arg1, arg2, ...):
+             ...
 
    It can be called either on the class (e.g. C.f()) or on an instance
    (e.g. C().f()); the instance is ignored except for its class.
@@ -808,8 +809,9 @@ just like an instance method receives the instance.\n\
 To declare a class method, use this idiom:\n\
 \n\
   class C:\n\
-      def f(cls, arg1, arg2, ...): ...\n\
-      f = classmethod(f)\n\
+      @classmethod\n\
+      def f(cls, arg1, arg2, ...):\n\
+          ...\n\
 \n\
 It can be called either on the class (e.g. C.f()) or on an instance\n\
 (e.g. C().f()).  The instance is ignored except for its class.\n\
@@ -880,8 +882,9 @@ PyClassMethod_New(PyObject *callable)
    To declare a static method, use this idiom:
 
      class C:
-     def f(arg1, arg2, ...): ...
-     f = staticmethod(f)
+         @staticmethod
+         def f(arg1, arg2, ...):
+             ...
 
    It can be called either on the class (e.g. C.f()) or on an instance
    (e.g. C().f()); the instance is ignored except for its class.
@@ -986,8 +989,9 @@ A static method does not receive an implicit first argument.\n\
 To declare a static method, use this idiom:\n\
 \n\
      class C:\n\
-     def f(arg1, arg2, ...): ...\n\
-     f = staticmethod(f)\n\
+         @staticmethod\n\
+         def f(arg1, arg2, ...):\n\
+             ...\n\
 \n\
 It can be called either on the class (e.g. C.f()) or on an instance\n\
 (e.g. C().f()).  The instance is ignored except for its class.\n\
index b3e0a46..d403598 100644 (file)
@@ -21,21 +21,9 @@ void
 _PyGen_Finalize(PyObject *self)
 {
     PyGenObject *gen = (PyGenObject *)self;
-    PyObject *res;
+    PyObject *res = NULL;
     PyObject *error_type, *error_value, *error_traceback;
 
-    /* If `gen` is a coroutine, and if it was never awaited on,
-       issue a RuntimeWarning. */
-    if (gen->gi_code != NULL
-            && ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE
-            && gen->gi_frame != NULL
-            && gen->gi_frame->f_lasti == -1
-            && !PyErr_Occurred()
-            && PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
-                                "coroutine '%.50S' was never awaited",
-                                gen->gi_qualname))
-        return;
-
     if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
         /* Generator isn't paused, so no need to close */
         return;
@@ -43,12 +31,28 @@ _PyGen_Finalize(PyObject *self)
     /* Save the current exception, if any. */
     PyErr_Fetch(&error_type, &error_value, &error_traceback);
 
-    res = gen_close(gen, NULL);
+    /* If `gen` is a coroutine, and if it was never awaited on,
+       issue a RuntimeWarning. */
+    if (gen->gi_code != NULL &&
+        ((PyCodeObject *)gen->gi_code)->co_flags & CO_COROUTINE &&
+        gen->gi_frame->f_lasti == -1) {
+        if (!error_value) {
+            PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
+                             "coroutine '%.50S' was never awaited",
+                             gen->gi_qualname);
+        }
+    }
+    else {
+        res = gen_close(gen, NULL);
+    }
 
-    if (res == NULL)
-        PyErr_WriteUnraisable(self);
-    else
+    if (res == NULL) {
+        if (PyErr_Occurred())
+            PyErr_WriteUnraisable(self);
+    }
+    else {
         Py_DECREF(res);
+    }
 
     /* Restore the saved exception. */
     PyErr_Restore(error_type, error_value, error_traceback);
@@ -70,7 +74,10 @@ gen_dealloc(PyGenObject *gen)
         return;                     /* resurrected.  :( */
 
     _PyObject_GC_UNTRACK(self);
-    Py_CLEAR(gen->gi_frame);
+    if (gen->gi_frame != NULL) {
+        gen->gi_frame->f_gen = NULL;
+        Py_CLEAR(gen->gi_frame);
+    }
     Py_CLEAR(gen->gi_code);
     Py_CLEAR(gen->gi_name);
     Py_CLEAR(gen->gi_qualname);
@@ -147,12 +154,7 @@ gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
             /* Delay exception instantiation if we can */
             PyErr_SetNone(PyExc_StopIteration);
         } else {
-            PyObject *e = PyObject_CallFunctionObjArgs(
-                               PyExc_StopIteration, result, NULL);
-            if (e != NULL) {
-                PyErr_SetObject(PyExc_StopIteration, e);
-                Py_DECREF(e);
-            }
+            _PyGen_SetStopIterationValue(result);
         }
         Py_CLEAR(result);
     }
@@ -453,6 +455,43 @@ gen_iternext(PyGenObject *gen)
 }
 
 /*
+ * Set StopIteration with specified value.  Value can be arbitrary object
+ * or NULL.
+ *
+ * Returns 0 if StopIteration is set and -1 if any other exception is set.
+ */
+int
+_PyGen_SetStopIterationValue(PyObject *value)
+{
+    PyObject *e;
+
+    if (value == NULL ||
+        (!PyTuple_Check(value) &&
+         !PyObject_TypeCheck(value, (PyTypeObject *) PyExc_StopIteration)))
+    {
+        /* Delay exception instantiation if we can */
+        PyErr_SetObject(PyExc_StopIteration, value);
+        return 0;
+    }
+    /* Construct an exception instance manually with
+     * PyObject_CallFunctionObjArgs and pass it to PyErr_SetObject.
+     *
+     * We do this to handle a situation when "value" is a tuple, in which
+     * case PyErr_SetObject would set the value of StopIteration to
+     * the first element of the tuple.
+     *
+     * (See PyErr_SetObject/_PyErr_CreateException code for details.)
+     */
+    e = PyObject_CallFunctionObjArgs(PyExc_StopIteration, value, NULL);
+    if (e == NULL) {
+        return -1;
+    }
+    PyErr_SetObject(PyExc_StopIteration, e);
+    Py_DECREF(e);
+    return 0;
+}
+
+/*
  *   If StopIteration exception is set, fetches its 'value'
  *   attribute if any, otherwise sets pvalue to None.
  *
@@ -462,7 +501,8 @@ gen_iternext(PyGenObject *gen)
  */
 
 int
-_PyGen_FetchStopIterationValue(PyObject **pvalue) {
+_PyGen_FetchStopIterationValue(PyObject **pvalue)
+{
     PyObject *et, *ev, *tb;
     PyObject *value = NULL;
 
@@ -474,8 +514,15 @@ _PyGen_FetchStopIterationValue(PyObject **pvalue) {
                 value = ((PyStopIterationObject *)ev)->value;
                 Py_INCREF(value);
                 Py_DECREF(ev);
-            } else if (et == PyExc_StopIteration) {
-                /* avoid normalisation and take ev as value */
+            } else if (et == PyExc_StopIteration && !PyTuple_Check(ev)) {
+                /* Avoid normalisation and take ev as value.
+                 *
+                 * Normalization is required if the value is a tuple, in
+                 * that case the value of StopIteration would be set to
+                 * the first element of the tuple.
+                 *
+                 * (See _PyErr_CreateException code for details.)
+                 */
                 value = ev;
             } else {
                 /* normalisation required */
@@ -984,7 +1031,7 @@ PyTypeObject _PyCoroWrapper_Type = {
     0,                                          /* tp_init */
     0,                                          /* tp_alloc */
     0,                                          /* tp_new */
-    PyObject_Del,                               /* tp_free */
+    0,                                          /* tp_free */
 };
 
 PyObject *
@@ -1005,7 +1052,7 @@ typedef struct {
 static PyObject *
 aiter_wrapper_iternext(PyAIterWrapper *aw)
 {
-    PyErr_SetObject(PyExc_StopIteration, aw->aw_aiter);
+    _PyGen_SetStopIterationValue(aw->aw_aiter);
     return NULL;
 }
 
@@ -1069,7 +1116,7 @@ PyTypeObject _PyAIterWrapper_Type = {
     0,                                          /* tp_init */
     0,                                          /* tp_alloc */
     0,                                          /* tp_new */
-    PyObject_Del,                               /* tp_free */
+    0,                                          /* tp_free */
 };
 
 
index d688179..815a1b9 100644 (file)
@@ -634,14 +634,17 @@ list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
     item = a->ob_item;
     /* recycle the items that we are about to remove */
     s = norig * sizeof(PyObject *);
-    if (s > sizeof(recycle_on_stack)) {
-        recycle = (PyObject **)PyMem_MALLOC(s);
-        if (recycle == NULL) {
-            PyErr_NoMemory();
-            goto Error;
+    /* If norig == 0, item might be NULL, in which case we may not memcpy from it. */
+    if (s) {
+        if (s > sizeof(recycle_on_stack)) {
+            recycle = (PyObject **)PyMem_MALLOC(s);
+            if (recycle == NULL) {
+                PyErr_NoMemory();
+                goto Error;
+            }
         }
+        memcpy(recycle, &item[ilow], s);
     }
-    memcpy(recycle, &item[ilow], s);
 
     if (d < 0) { /* Delete -d items */
         Py_ssize_t tail;
index 832e4f2..152a270 100644 (file)
@@ -694,7 +694,7 @@ search doesn't reduce the quadratic data movement costs.
 
 But in CPython's case, comparisons are extraordinarily expensive compared to
 moving data, and the details matter.  Moving objects is just copying
-pointers.  Comparisons can be arbitrarily expensive (can invoke arbitary
+pointers.  Comparisons can be arbitrarily expensive (can invoke arbitrary
 user-supplied Python code), but even in simple cases (like 3 < 4) _all_
 decisions are made at runtime:  what's the type of the left comparand?  the
 type of the right?  do they need to be coerced to a common type?  where's the
index f68d15e..8510e90 100644 (file)
@@ -234,7 +234,7 @@ PyLong_FromLong(long ival)
     unsigned long abs_ival;
     unsigned long t;  /* unsigned so >> doesn't propagate sign bit */
     int ndigits = 0;
-    int sign = 1;
+    int sign;
 
     CHECK_SMALL_INT(ival);
 
@@ -246,6 +246,7 @@ PyLong_FromLong(long ival)
     }
     else {
         abs_ival = (unsigned long)ival;
+        sign = ival == 0 ? 0 : 1;
     }
 
     /* Fast path for single-digit ints */
@@ -368,7 +369,7 @@ PyLong_FromDouble(double dval)
 /* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
  * anything about what happens when a signed integer operation overflows,
  * and some compilers think they're doing you a favor by being "clever"
- * then.  The bit pattern for the largest postive signed long is
+ * then.  The bit pattern for the largest positive signed long is
  * (unsigned long)LONG_MAX, and for the smallest negative signed long
  * it is abs(LONG_MIN), which we could write -(unsigned long)LONG_MIN.
  * However, some other compilers warn about applying unary minus to an
@@ -775,10 +776,10 @@ _PyLong_FromByteArray(const unsigned char* bytes, size_t n,
         size_t i;
         const unsigned char* p = pendbyte;
         const int pincr = -incr;  /* search MSB to LSB */
-        const unsigned char insignficant = is_signed ? 0xff : 0x00;
+        const unsigned char insignificant = is_signed ? 0xff : 0x00;
 
         for (i = 0; i < n; ++i, p += pincr) {
-            if (*p != insignficant)
+            if (*p != insignificant)
                 break;
         }
         numsignificantbytes = n - i;
@@ -4935,9 +4936,9 @@ long_to_bytes(PyLongObject *v, PyObject *args, PyObject *kwds)
         return NULL;
     }
 
-    if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
+    if (_PyUnicode_EqualToASCIIString(byteorder_str, "little"))
         little_endian = 1;
-    else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
+    else if (_PyUnicode_EqualToASCIIString(byteorder_str, "big"))
         little_endian = 0;
     else {
         PyErr_SetString(PyExc_ValueError,
@@ -5018,9 +5019,9 @@ long_from_bytes(PyTypeObject *type, PyObject *args, PyObject *kwds)
         return NULL;
     }
 
-    if (!PyUnicode_CompareWithASCIIString(byteorder_str, "little"))
+    if (_PyUnicode_EqualToASCIIString(byteorder_str, "little"))
         little_endian = 1;
-    else if (!PyUnicode_CompareWithASCIIString(byteorder_str, "big"))
+    else if (_PyUnicode_EqualToASCIIString(byteorder_str, "big"))
         little_endian = 0;
     else {
         PyErr_SetString(PyExc_ValueError,
index 10162cb..e261ee0 100644 (file)
@@ -221,7 +221,7 @@ PyTypeObject _PyManagedBuffer_Type = {
 
 
 PyDoc_STRVAR(memory_doc,
-"memoryview($module, object)\n--\n\
+"memoryview(object)\n--\n\
 \n\
 Create a new memoryview object which references the given object.");
 
index a4cdc20..ae72da6 100644 (file)
@@ -130,6 +130,34 @@ check_api_version(const char *name, int module_api_version)
     return 1;
 }
 
+static int
+_add_methods_to_object(PyObject *module, PyObject *name, PyMethodDef *functions)
+{
+    PyObject *func;
+    PyMethodDef *fdef;
+
+    for (fdef = functions; fdef->ml_name != NULL; fdef++) {
+        if ((fdef->ml_flags & METH_CLASS) ||
+            (fdef->ml_flags & METH_STATIC)) {
+            PyErr_SetString(PyExc_ValueError,
+                            "module functions cannot set"
+                            " METH_CLASS or METH_STATIC");
+            return -1;
+        }
+        func = PyCFunction_NewEx(fdef, (PyObject*)module, name);
+        if (func == NULL) {
+            return -1;
+        }
+        if (PyObject_SetAttrString(module, fdef->ml_name, func) != 0) {
+            Py_DECREF(func);
+            return -1;
+        }
+        Py_DECREF(func);
+    }
+
+    return 0;
+}
+
 PyObject *
 PyModule_Create2(struct PyModuleDef* module, int module_api_version)
 {
@@ -269,7 +297,7 @@ PyModule_FromDefAndSpec2(struct PyModuleDef* def, PyObject *spec, int module_api
             }
         }
     } else {
-        m = PyModule_New(name);
+        m = PyModule_NewObject(nameobj);
         if (m == NULL) {
             goto error;
         }
@@ -297,7 +325,7 @@ PyModule_FromDefAndSpec2(struct PyModuleDef* def, PyObject *spec, int module_api
     }
 
     if (def->m_methods != NULL) {
-        ret = PyModule_AddFunctions(m, def->m_methods);
+        ret = _add_methods_to_object(m, nameobj, def->m_methods);
         if (ret != 0) {
             goto error;
         }
@@ -331,7 +359,7 @@ PyModule_ExecDef(PyObject *module, PyModuleDef *def)
         return -1;
     }
 
-    if (PyModule_Check(module) && def->m_size >= 0) {
+    if (def->m_size >= 0) {
         PyModuleObject *md = (PyModuleObject*)module;
         if (md->md_state == NULL) {
             /* Always set a state pointer; this serves as a marker to skip
@@ -387,37 +415,15 @@ PyModule_ExecDef(PyObject *module, PyModuleDef *def)
 int
 PyModule_AddFunctions(PyObject *m, PyMethodDef *functions)
 {
-    PyObject *name, *func;
-    PyMethodDef *fdef;
-
-    name = PyModule_GetNameObject(m);
+    int res;
+    PyObject *name = PyModule_GetNameObject(m);
     if (name == NULL) {
         return -1;
     }
 
-    for (fdef = functions; fdef->ml_name != NULL; fdef++) {
-        if ((fdef->ml_flags & METH_CLASS) ||
-            (fdef->ml_flags & METH_STATIC)) {
-            PyErr_SetString(PyExc_ValueError,
-                            "module functions cannot set"
-                            " METH_CLASS or METH_STATIC");
-            Py_DECREF(name);
-            return -1;
-        }
-        func = PyCFunction_NewEx(fdef, (PyObject*)m, name);
-        if (func == NULL) {
-            Py_DECREF(name);
-            return -1;
-        }
-        if (PyObject_SetAttrString(m, fdef->ml_name, func) != 0) {
-            Py_DECREF(func);
-            Py_DECREF(name);
-            return -1;
-        }
-        Py_DECREF(func);
-    }
+    res = _add_methods_to_object(m, name, functions);
     Py_DECREF(name);
-    return 0;
+    return res;
 }
 
 int
@@ -581,7 +587,7 @@ _PyModule_ClearDict(PyObject *d)
     while (PyDict_Next(d, &pos, &key, &value)) {
         if (value != Py_None && PyUnicode_Check(key)) {
             if (PyUnicode_READ_CHAR(key, 0) != '_' ||
-                PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0)
+                !_PyUnicode_EqualToASCIIString(key, "__builtins__"))
             {
                 if (Py_VerboseFlag > 1) {
                     const char *s = _PyUnicode_AsString(key);
index 8024889..d21fd90 100644 (file)
@@ -1607,6 +1607,15 @@ _Py_ReadyTypes(void)
     if (PyType_Ready(&PyDict_Type) < 0)
         Py_FatalError("Can't initialize dict type");
 
+    if (PyType_Ready(&PyDictKeys_Type) < 0)
+        Py_FatalError("Can't initialize dict keys type");
+
+    if (PyType_Ready(&PyDictValues_Type) < 0)
+        Py_FatalError("Can't initialize dict values type");
+
+    if (PyType_Ready(&PyDictItems_Type) < 0)
+        Py_FatalError("Can't initialize dict items type");
+
     if (PyType_Ready(&PyODict_Type) < 0)
         Py_FatalError("Can't initialize OrderedDict type");
 
index 1abdd02..a6963d7 100644 (file)
@@ -194,7 +194,7 @@ the concrete API.
 Here are some ways to address this challenge:
 
 1. Change the relevant usage of the concrete API in CPython and add
-   PyDict_CheckExact() calls to each of the concrete API funcions.
+   PyDict_CheckExact() calls to each of the concrete API functions.
 2. Adjust the relevant concrete API functions to explicitly accommodate
    OrderedDict.
 3. As with #1, add the checks, but improve the abstract API with smart fast
index 0e9eb20..899697a 100644 (file)
@@ -406,7 +406,7 @@ range_contains_long(rangeobject *r, PyObject *ob)
     tmp2 = PyNumber_Remainder(tmp1, r->step);
     if (tmp2 == NULL)
         goto end;
-    /* result = (int(ob) - start % step) == 0 */
+    /* result = ((int(ob) - start) % step) == 0 */
     result = PyObject_RichCompareBool(tmp2, zero, Py_EQ);
   end:
     Py_XDECREF(tmp1);
@@ -937,12 +937,20 @@ rangeiter_new(PyTypeObject *type, PyObject *args, PyObject *kw)
 {
     long start, stop, step;
 
-    if (!_PyArg_NoKeywords("rangeiter()", kw))
+    if (!_PyArg_NoKeywords("range_iterator()", kw)) {
         return NULL;
+    }
 
-    if (!PyArg_ParseTuple(args, "lll;rangeiter() requires 3 int arguments",
-                          &start, &stop, &step))
+    if (!PyArg_ParseTuple(args,
+                          "lll;range_iterator() requires 3 int arguments",
+                          &start, &stop, &step)) {
+        return NULL;
+    }
+    if (step == 0) {
+        PyErr_SetString(PyExc_ValueError,
+                        "range_iterator() arg 3 must not be zero");
         return NULL;
+    }
 
     return fast_range_iter(start, stop, step);
 }
index 317334f..7b76e5c 100644 (file)
@@ -858,7 +858,7 @@ type_repr(PyTypeObject *type)
         return NULL;
     }
 
-    if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
+    if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
         rtn = PyUnicode_FromFormat("<class '%U.%U'>", mod, name);
     else
         rtn = PyUnicode_FromFormat("<class '%s'>", type->tp_name);
@@ -1123,11 +1123,6 @@ subtype_dealloc(PyObject *self)
     Py_TRASHCAN_SAFE_BEGIN(self);
     --_PyTrash_delete_nesting;
     -- tstate->trash_delete_nesting;
-    /* DO NOT restore GC tracking at this point.  weakref callbacks
-     * (if any, and whether directly here or indirectly in something we
-     * call) may trigger GC, and if self is tracked at that point, it
-     * will look like trash to GC and GC will try to delete self again.
-     */
 
     /* Find the nearest base with a different tp_dealloc */
     base = type;
@@ -1138,30 +1133,36 @@ subtype_dealloc(PyObject *self)
 
     has_finalizer = type->tp_finalize || type->tp_del;
 
-    /* Maybe call finalizer; exit early if resurrected */
-    if (has_finalizer)
-        _PyObject_GC_TRACK(self);
-
     if (type->tp_finalize) {
+        _PyObject_GC_TRACK(self);
         if (PyObject_CallFinalizerFromDealloc(self) < 0) {
             /* Resurrected */
             goto endlabel;
         }
+        _PyObject_GC_UNTRACK(self);
     }
-    /* If we added a weaklist, we clear it.      Do this *before* calling
-       tp_del, clearing slots, or clearing the instance dict. */
+    /*
+      If we added a weaklist, we clear it. Do this *before* calling tp_del,
+      clearing slots, or clearing the instance dict.
+
+      GC tracking must be off at this point. weakref callbacks (if any, and
+      whether directly here or indirectly in something we call) may trigger GC,
+      and if self is tracked at that point, it will look like trash to GC and GC
+      will try to delete self again.
+    */
     if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
         PyObject_ClearWeakRefs(self);
 
     if (type->tp_del) {
+        _PyObject_GC_TRACK(self);
         type->tp_del(self);
         if (self->ob_refcnt > 0) {
             /* Resurrected */
             goto endlabel;
         }
+        _PyObject_GC_UNTRACK(self);
     }
     if (has_finalizer) {
-        _PyObject_GC_UNTRACK(self);
         /* New weakrefs could be created during the finalizer call.
            If this occurs, clear them out without calling their
            finalizers since they might rely on part of the object
@@ -1432,8 +1433,10 @@ call_method(PyObject *o, _Py_Identifier *nameid, char *format, ...)
 
     va_end(va);
 
-    if (args == NULL)
+    if (args == NULL) {
+        Py_DECREF(func);
         return NULL;
+    }
 
     assert(PyTuple_Check(args));
     retval = PyObject_Call(func, args, NULL);
@@ -1468,8 +1471,10 @@ call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
 
     va_end(va);
 
-    if (args == NULL)
+    if (args == NULL) {
+        Py_DECREF(func);
         return NULL;
+    }
 
     assert(PyTuple_Check(args));
     retval = PyObject_Call(func, args, NULL);
@@ -1494,7 +1499,7 @@ call_maybe(PyObject *o, _Py_Identifier *nameid, char *format, ...)
 
     The next three properties are the 3 constraints in "C3".
 
-    Local precendece order.
+    Local precedence order.
     If A precedes B in C's MRO, then A will precede B in the MRO of all
     subclasses of C.
 
@@ -2381,7 +2386,7 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
             if (!valid_identifier(tmp))
                 goto error;
             assert(PyUnicode_Check(tmp));
-            if (_PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) {
+            if (_PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) {
                 if (!may_add_dict || add_dict) {
                     PyErr_SetString(PyExc_TypeError,
                         "__dict__ slot disallowed: "
@@ -2390,7 +2395,7 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
                 }
                 add_dict++;
             }
-            if (PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0) {
+            if (_PyUnicode_EqualToASCIIString(tmp, "__weakref__")) {
                 if (!may_add_weak || add_weak) {
                     PyErr_SetString(PyExc_TypeError,
                         "__weakref__ slot disallowed: "
@@ -2412,9 +2417,9 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
         for (i = j = 0; i < nslots; i++) {
             tmp = PyTuple_GET_ITEM(slots, i);
             if ((add_dict &&
-                 _PyUnicode_CompareWithId(tmp, &PyId___dict__) == 0) ||
+                 _PyUnicode_EqualToASCIIId(tmp, &PyId___dict__)) ||
                 (add_weak &&
-                 PyUnicode_CompareWithASCIIString(tmp, "__weakref__") == 0))
+                 _PyUnicode_EqualToASCIIString(tmp, "__weakref__")))
                 continue;
             tmp =_Py_Mangle(name, tmp);
             if (!tmp) {
@@ -2864,11 +2869,25 @@ _PyType_Lookup(PyTypeObject *type, PyObject *name)
     /* Look in tp_dict of types in MRO */
     mro = type->tp_mro;
 
-    /* If mro is NULL, the type is either not yet initialized
-       by PyType_Ready(), or already cleared by type_clear().
-       Either way the safest thing to do is to return NULL. */
-    if (mro == NULL)
-        return NULL;
+    if (mro == NULL) {
+        if ((type->tp_flags & Py_TPFLAGS_READYING) == 0 &&
+            PyType_Ready(type) < 0) {
+            /* It's not ideal to clear the error condition,
+               but this function is documented as not setting
+               an exception, and I don't want to change that.
+               When PyType_Ready() can't proceed, it won't
+               set the "ready" flag, so future attempts to ready
+               the same type will call it again -- hopefully
+               in a context that propagates the exception out.
+            */
+            PyErr_Clear();
+            return NULL;
+        }
+        mro = type->tp_mro;
+        if (mro == NULL) {
+            return NULL;
+        }
+    }
 
     res = NULL;
     /* keep a strong reference to mro because type->tp_mro can be replaced
@@ -3471,7 +3490,7 @@ object_repr(PyObject *self)
         Py_XDECREF(mod);
         return NULL;
     }
-    if (mod != NULL && _PyUnicode_CompareWithId(mod, &PyId_builtins))
+    if (mod != NULL && !_PyUnicode_EqualToASCIIId(mod, &PyId_builtins))
         rtn = PyUnicode_FromFormat("<%U.%U object at %p>", mod, name, self);
     else
         rtn = PyUnicode_FromFormat("<%s object at %p>",
@@ -3755,7 +3774,7 @@ import_copyreg(void)
     /* Try to fetch cached copy of copyreg from sys.modules first in an
        attempt to avoid the import overhead. Previously this was implemented
        by storing a reference to the cached module in a static variable, but
-       this broke when multiple embeded interpreters were in use (see issue
+       this broke when multiple embedded interpreters were in use (see issue
        #17408 and #19088). */
     copyreg_module = PyDict_GetItemWithError(interp->modules, copyreg_str);
     if (copyreg_module != NULL) {
@@ -4299,13 +4318,6 @@ PyDoc_STRVAR(object_subclasshook_doc,
 "NotImplemented, the normal algorithm is used.  Otherwise, it\n"
 "overrides the normal algorithm (and the outcome is cached).\n");
 
-/*
-   from PEP 3101, this code implements:
-
-   class object:
-       def __format__(self, format_spec):
-           return format(str(self), format_spec)
-*/
 static PyObject *
 object_format(PyObject *self, PyObject *args)
 {
@@ -4316,22 +4328,19 @@ object_format(PyObject *self, PyObject *args)
     if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
         return NULL;
 
+    /* Issue 7994: If we're converting to a string, we
+       should reject format specifications */
+    if (PyUnicode_GET_LENGTH(format_spec) > 0) {
+        PyErr_Format(PyExc_TypeError,
+                     "unsupported format string passed to %.200s.__format__",
+                     self->ob_type->tp_name);
+        return NULL;
+    }
     self_as_str = PyObject_Str(self);
     if (self_as_str != NULL) {
-        /* Issue 7994: If we're converting to a string, we
-           should reject format specifications */
-        if (PyUnicode_GET_LENGTH(format_spec) > 0) {
-            PyErr_SetString(PyExc_TypeError,
-               "non-empty format string passed to object.__format__");
-            goto done;
-        }
-
         result = PyObject_Format(self_as_str, format_spec);
+        Py_DECREF(self_as_str);
     }
-
-done:
-    Py_XDECREF(self_as_str);
-
     return result;
 }
 
@@ -4509,8 +4518,10 @@ add_members(PyTypeObject *type, PyMemberDef *memb)
         descr = PyDescr_NewMember(type, memb);
         if (descr == NULL)
             return -1;
-        if (PyDict_SetItemString(dict, memb->name, descr) < 0)
+        if (PyDict_SetItemString(dict, memb->name, descr) < 0) {
+            Py_DECREF(descr);
             return -1;
+        }
         Py_DECREF(descr);
     }
     return 0;
@@ -4529,8 +4540,10 @@ add_getset(PyTypeObject *type, PyGetSetDef *gsp)
 
         if (descr == NULL)
             return -1;
-        if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
+        if (PyDict_SetItemString(dict, gsp->name, descr) < 0) {
+            Py_DECREF(descr);
             return -1;
+        }
         Py_DECREF(descr);
     }
     return 0;
@@ -4811,6 +4824,12 @@ PyType_Ready(PyTypeObject *type)
     _Py_AddToAllObjects((PyObject *)type, 0);
 #endif
 
+    if (type->tp_name == NULL) {
+        PyErr_Format(PyExc_SystemError,
+                     "Type does not define the tp_name field.");
+        goto error;
+    }
+
     /* Initialize tp_base (defaults to BaseObject unless that's us) */
     base = type->tp_base;
     if (base == NULL && type != &PyBaseObject_Type) {
@@ -7010,8 +7029,10 @@ add_operators(PyTypeObject *type)
             descr = PyDescr_NewWrapper(type, p, *ptr);
             if (descr == NULL)
                 return -1;
-            if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
+            if (PyDict_SetItem(dict, p->name_strobj, descr) < 0) {
+                Py_DECREF(descr);
                 return -1;
+            }
             Py_DECREF(descr);
         }
     }
@@ -7086,7 +7107,7 @@ super_getattro(PyObject *self, PyObject *name)
        (i.e. super, or a subclass), not the class of su->obj. */
     if (PyUnicode_Check(name) &&
         PyUnicode_GET_LENGTH(name) == 9 &&
-        _PyUnicode_CompareWithId(name, &PyId___class__) == 0)
+        _PyUnicode_EqualToASCIIId(name, &PyId___class__))
         goto skip;
 
     mro = starttype->tp_mro;
@@ -7298,7 +7319,7 @@ super_init(PyObject *self, PyObject *args, PyObject *kwds)
         for (i = 0; i < n; i++) {
             PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
             assert(PyUnicode_Check(name));
-            if (!_PyUnicode_CompareWithId(name, &PyId___class__)) {
+            if (_PyUnicode_EqualToASCIIId(name, &PyId___class__)) {
                 Py_ssize_t index = co->co_nlocals +
                     PyTuple_GET_SIZE(co->co_cellvars) + i;
                 PyObject *cell = f->f_localsplus[index];
index ba37c40..9b6d4ad 100755 (executable)
@@ -1,32 +1,43 @@
 #!/usr/bin/python
-# Usage: typeslots.py < Include/typeslots.h typeslots.inc
+# Usage: typeslots.py < Include/typeslots.h typeslots.inc
 
 import sys, re
 
-print("/* Generated by typeslots.py */")
-res = {}
-for line in sys.stdin:
-    m = re.match("#define Py_([a-z_]+) ([0-9]+)", line)
-    if not m:
-        continue
-    member = m.group(1)
-    if member.startswith("tp_"):
-        member = "ht_type."+member
-    elif member.startswith("am_"):
-        member = "as_async."+member
-    elif member.startswith("nb_"):
-        member = "as_number."+member
-    elif member.startswith("mp_"):
-        member = "as_mapping."+member
-    elif member.startswith("sq_"):
-        member = "as_sequence."+member
-    elif member.startswith("bf_"):
-        member = "as_buffer."+member
-    res[int(m.group(2))] = member
+def generate_typeslots(out=sys.stdout):
+    out.write("/* Generated by typeslots.py */\n")
+    res = {}
+    for line in sys.stdin:
+        m = re.match("#define Py_([a-z_]+) ([0-9]+)", line)
+        if not m:
+            continue
+        member = m.group(1)
+        if member.startswith("tp_"):
+            member = "ht_type."+member
+        elif member.startswith("am_"):
+            member = "as_async."+member
+        elif member.startswith("nb_"):
+            member = "as_number."+member
+        elif member.startswith("mp_"):
+            member = "as_mapping."+member
+        elif member.startswith("sq_"):
+            member = "as_sequence."+member
+        elif member.startswith("bf_"):
+            member = "as_buffer."+member
+        res[int(m.group(2))] = member
 
-M = max(res.keys())+1
-for i in range(1,M):
-    if i in res:
-        print("offsetof(PyHeapTypeObject, %s)," % res[i])
+    M = max(res.keys())+1
+    for i in range(1,M):
+        if i in res:
+            out.write("offsetof(PyHeapTypeObject, %s),\n" % res[i])
+        else:
+            out.write("0,\n")
+
+def main():
+    if len(sys.argv) == 2:
+        with open(sys.argv[1], "w") as f:
+            generate_typeslots(f)
     else:
-        print("0,")
+        generate_typeslots()
+
+if __name__ == "__main__":
+    main()
index f11a082..5787830 100644 (file)
@@ -1366,15 +1366,19 @@ PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
     if (PyUnicode_READY(to) == -1)
         return -1;
 
-    if (from_start < 0) {
+    if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
         PyErr_SetString(PyExc_IndexError, "string index out of range");
         return -1;
     }
-    if (to_start < 0) {
+    if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
         PyErr_SetString(PyExc_IndexError, "string index out of range");
         return -1;
     }
-    how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
+    if (how_many < 0) {
+        PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
+        return -1;
+    }
+    how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
     if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
         PyErr_Format(PyExc_SystemError,
                      "Cannot write %zi characters at %zi "
@@ -2719,7 +2723,7 @@ PyUnicode_FromFormatV(const char *format, va_list vargs)
                         "PyUnicode_FromFormatV() expects an ASCII-encoded format "
                         "string, got a non-ASCII byte: 0x%02x",
                         (unsigned char)*p);
-                    return NULL;
+                    goto fail;
                 }
                 p++;
             }
@@ -3005,7 +3009,7 @@ PyUnicode_Decode(const char *s,
                      "'%.400s' decoder returned '%.400s' instead of 'str'; "
                      "use codecs.decode() to decode to arbitrary types",
                      encoding,
-                     Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
+                     Py_TYPE(unicode)->tp_name);
         Py_DECREF(unicode);
         goto onError;
     }
@@ -3022,24 +3026,16 @@ PyUnicode_AsDecodedObject(PyObject *unicode,
                           const char *encoding,
                           const char *errors)
 {
-    PyObject *v;
-
     if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
-        goto onError;
+        return NULL;
     }
 
     if (encoding == NULL)
         encoding = PyUnicode_GetDefaultEncoding();
 
     /* Decode via the codec registry */
-    v = PyCodec_Decode(unicode, encoding, errors);
-    if (v == NULL)
-        goto onError;
-    return unicode_result(v);
-
-  onError:
-    return NULL;
+    return PyCodec_Decode(unicode, encoding, errors);
 }
 
 PyObject *
@@ -3066,7 +3062,7 @@ PyUnicode_AsDecodedUnicode(PyObject *unicode,
                      "'%.400s' decoder returned '%.400s' instead of 'str'; "
                      "use codecs.decode() to decode to arbitrary types",
                      encoding,
-                     Py_TYPE(unicode)->tp_name, Py_TYPE(unicode)->tp_name);
+                     Py_TYPE(unicode)->tp_name);
         Py_DECREF(v);
         goto onError;
     }
@@ -3394,7 +3390,7 @@ PyUnicode_AsEncodedString(PyObject *unicode,
                  "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
                  "use codecs.encode() to encode to arbitrary types",
                  encoding,
-                 Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
+                 Py_TYPE(v)->tp_name);
     Py_DECREF(v);
     return NULL;
 }
@@ -3423,7 +3419,7 @@ PyUnicode_AsEncodedUnicode(PyObject *unicode,
                      "'%.400s' encoder returned '%.400s' instead of 'str'; "
                      "use codecs.encode() to encode to arbitrary types",
                      encoding,
-                     Py_TYPE(v)->tp_name, Py_TYPE(v)->tp_name);
+                     Py_TYPE(v)->tp_name);
         Py_DECREF(v);
         goto onError;
     }
@@ -3666,7 +3662,7 @@ PyUnicode_FSDecoder(PyObject* arg, void* addr)
         output = arg;
         Py_INCREF(output);
     }
-    else {
+    else if (PyObject_CheckBuffer(arg)) {
         arg = PyBytes_FromObject(arg);
         if (!arg)
             return 0;
@@ -3681,6 +3677,12 @@ PyUnicode_FSDecoder(PyObject* arg, void* addr)
             return 0;
         }
     }
+    else {
+        PyErr_Format(PyExc_TypeError,
+                     "path should be string or bytes, not %.200s",
+                     Py_TYPE(arg)->tp_name);
+        return 0;
+    }
     if (PyUnicode_READY(output) == -1) {
         Py_DECREF(output);
         return 0;
@@ -4814,7 +4816,7 @@ _Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
 #if SIZEOF_WCHAR_T == 4
             assert(0);
 #else
-            assert(Py_UNICODE_IS_SURROGATE(ch));
+            assert(ch > 0xFFFF && ch <= MAX_UNICODE);
             /*  compute and append the two surrogates: */
             unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
             unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
@@ -4938,7 +4940,7 @@ PyUnicode_DecodeUTF32Stateful(const char *s,
        mark is skipped, in all other modes, it is copied to the output
        stream as-is (giving a ZWNBSP character). */
     if (bo == 0 && size >= 4) {
-        Py_UCS4 bom = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
+        Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
         if (bom == 0x0000FEFF) {
             bo = -1;
             q += 4;
@@ -4980,7 +4982,7 @@ PyUnicode_DecodeUTF32Stateful(const char *s,
             Py_ssize_t pos = writer.pos;
             if (le) {
                 do {
-                    ch = (q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
+                    ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
                     if (ch > maxch)
                         break;
                     if (kind != PyUnicode_1BYTE_KIND &&
@@ -4992,7 +4994,7 @@ PyUnicode_DecodeUTF32Stateful(const char *s,
             }
             else {
                 do {
-                    ch = (q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
+                    ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
                     if (ch > maxch)
                         break;
                     if (kind != PyUnicode_1BYTE_KIND &&
@@ -10791,10 +10793,24 @@ PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
     Py_ssize_t i;
     int kind;
     Py_UCS4 chr;
+    const unsigned char *ustr = (const unsigned char *)str;
 
     assert(_PyUnicode_CHECK(uni));
-    if (PyUnicode_READY(uni) == -1)
-        return -1;
+    if (!PyUnicode_IS_READY(uni)) {
+        const wchar_t *ws = _PyUnicode_WSTR(uni);
+        /* Compare Unicode string and source character set string */
+        for (i = 0; (chr = ws[i]) && ustr[i]; i++) {
+            if (chr != ustr[i])
+                return (chr < ustr[i]) ? -1 : 1;
+        }
+        /* This check keeps Python strings that end in '\0' from comparing equal
+         to C strings identical up to that point. */
+        if (_PyUnicode_WSTR_LENGTH(uni) != i || chr)
+            return 1; /* uni is longer */
+        if (ustr[i])
+            return -1; /* str is longer */
+        return 0;
+    }
     kind = PyUnicode_KIND(uni);
     if (kind == PyUnicode_1BYTE_KIND) {
         const void *data = PyUnicode_1BYTE_DATA(uni);
@@ -10832,6 +10848,79 @@ PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
     }
 }
 
+static int
+non_ready_unicode_equal_to_ascii_string(PyObject *unicode, const char *str)
+{
+    size_t i, len;
+    const wchar_t *p;
+    len = (size_t)_PyUnicode_WSTR_LENGTH(unicode);
+    if (strlen(str) != len)
+        return 0;
+    p = _PyUnicode_WSTR(unicode);
+    assert(p);
+    for (i = 0; i < len; i++) {
+        unsigned char c = (unsigned char)str[i];
+        if (c >= 128 || p[i] != (wchar_t)c)
+            return 0;
+    }
+    return 1;
+}
+
+int
+_PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
+{
+    size_t len;
+    assert(_PyUnicode_CHECK(unicode));
+    if (PyUnicode_READY(unicode) == -1) {
+        /* Memory error or bad data */
+        PyErr_Clear();
+        return non_ready_unicode_equal_to_ascii_string(unicode, str);
+    }
+    if (!PyUnicode_IS_ASCII(unicode))
+        return 0;
+    len = (size_t)PyUnicode_GET_LENGTH(unicode);
+    return strlen(str) == len &&
+           memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
+}
+
+int
+_PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
+{
+    PyObject *right_uni;
+    Py_hash_t hash;
+
+    assert(_PyUnicode_CHECK(left));
+    assert(right->string);
+
+    if (PyUnicode_READY(left) == -1) {
+        /* memory error or bad data */
+        PyErr_Clear();
+        return non_ready_unicode_equal_to_ascii_string(left, right->string);
+    }
+
+    if (!PyUnicode_IS_ASCII(left))
+        return 0;
+
+    right_uni = _PyUnicode_FromId(right);       /* borrowed */
+    if (right_uni == NULL) {
+        /* memory error or bad data */
+        PyErr_Clear();
+        return _PyUnicode_EqualToASCIIString(left, right->string);
+    }
+
+    if (left == right_uni)
+        return 1;
+
+    if (PyUnicode_CHECK_INTERNED(left))
+        return 0;
+
+    assert(_PyUnicode_HASH(right_uni) != 1);
+    hash = _PyUnicode_HASH(left);
+    if (hash != -1 && hash != _PyUnicode_HASH(right_uni))
+        return 0;
+
+    return unicode_compare_eq(left, right_uni);
+}
 
 #define TEST_COND(cond)                         \
     ((cond) ? Py_True : Py_False)
@@ -14124,11 +14213,12 @@ formatchar(PyObject *v)
             if (iobj == NULL) {
                 goto onError;
             }
-            v = iobj;
+            x = PyLong_AsLong(iobj);
             Py_DECREF(iobj);
         }
-        /* Integer input truncated to a character */
-        x = PyLong_AsLong(v);
+        else {
+            x = PyLong_AsLong(v);
+        }
         if (x == -1 && PyErr_Occurred())
             goto onError;
 
index 86a5943..9e7e36d 100644 (file)
--- a/PC/_msi.c
+++ b/PC/_msi.c
@@ -955,6 +955,17 @@ static PyTypeObject msidb_Type = {
         0,                      /*tp_is_gc*/
 };
 
+#define Py_NOT_PERSIST(x, flag)                        \
+    (x != (int)(flag) &&                      \
+    x != ((int)(flag) | MSIDBOPEN_PATCHFILE))
+
+#define Py_INVALID_PERSIST(x)                \
+    (Py_NOT_PERSIST(x, MSIDBOPEN_READONLY) &&  \
+    Py_NOT_PERSIST(x, MSIDBOPEN_TRANSACT) &&   \
+    Py_NOT_PERSIST(x, MSIDBOPEN_DIRECT) &&     \
+    Py_NOT_PERSIST(x, MSIDBOPEN_CREATE) &&     \
+    Py_NOT_PERSIST(x, MSIDBOPEN_CREATEDIRECT))
+
 static PyObject* msiopendb(PyObject *obj, PyObject *args)
 {
     int status;
@@ -962,11 +973,14 @@ static PyObject* msiopendb(PyObject *obj, PyObject *args)
     int persist;
     MSIHANDLE h;
     msiobj *result;
-
     if (!PyArg_ParseTuple(args, "si:MSIOpenDatabase", &path, &persist))
         return NULL;
-
-        status = MsiOpenDatabase(path, (LPCSTR)persist, &h);
+    /* We need to validate that persist is a valid MSIDBOPEN_* value. Otherwise,
+       MsiOpenDatabase may treat the value as a pointer, leading to unexpected
+       behavior. */
+    if (Py_INVALID_PERSIST(persist))
+        return msierror(ERROR_INVALID_PARAMETER);
+    status = MsiOpenDatabase(path, (LPCSTR)persist, &h);
     if (status != ERROR_SUCCESS)
         return msierror(status);
 
index cb037ff..adbb733 100644 (file)
@@ -154,7 +154,7 @@ HANDLE hBitmap;
 char *bitmap_bytes;
 
 static const char *REGISTRY_SUFFIX_6432 =
-#ifdef MS_WIN64
+#ifdef _WIN64
                                           "";
 #else
                                           "-32";
@@ -1657,16 +1657,16 @@ SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
                     PropSheet_SetWizButtons(GetParent(hwnd),
                                             PSWIZB_BACK | PSWIZB_NEXT);
                     /* Get the python directory */
-            ivi = (InstalledVersionInfo *)
+                    ivi = (InstalledVersionInfo *)
                         SendDlgItemMessage(hwnd,
-                                                                IDC_VERSIONS_LIST,
-                                                                LB_GETITEMDATA,
-                                                                id,
-                                                                0);
-            hkey_root = ivi->hkey;
-                                strcpy(python_dir, ivi->prefix);
-                                SetDlgItemText(hwnd, IDC_PATH, python_dir);
-                                /* retrieve the python version and pythondll to use */
+                            IDC_VERSIONS_LIST,
+                            LB_GETITEMDATA,
+                            id,
+                            0);
+                    hkey_root = ivi->hkey;
+                    strcpy(python_dir, ivi->prefix);
+                    SetDlgItemText(hwnd, IDC_PATH, python_dir);
+                    /* retrieve the python version and pythondll to use */
                     result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
                                                  LB_GETTEXTLEN, (WPARAM)id, 0);
                     pbuf = (char *)malloc(result + 1);
index c8e6ed8..e7a72c4 100644 (file)
@@ -15,10 +15,10 @@ PyDoc_STRVAR(msvcrt_heapmin__doc__,
     {"heapmin", (PyCFunction)msvcrt_heapmin, METH_NOARGS, msvcrt_heapmin__doc__},
 
 static PyObject *
-msvcrt_heapmin_impl(PyModuleDef *module);
+msvcrt_heapmin_impl(PyObject *module);
 
 static PyObject *
-msvcrt_heapmin(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+msvcrt_heapmin(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return msvcrt_heapmin_impl(module);
 }
@@ -40,10 +40,10 @@ PyDoc_STRVAR(msvcrt_locking__doc__,
     {"locking", (PyCFunction)msvcrt_locking, METH_VARARGS, msvcrt_locking__doc__},
 
 static PyObject *
-msvcrt_locking_impl(PyModuleDef *module, int fd, int mode, long nbytes);
+msvcrt_locking_impl(PyObject *module, int fd, int mode, long nbytes);
 
 static PyObject *
-msvcrt_locking(PyModuleDef *module, PyObject *args)
+msvcrt_locking(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -74,10 +74,10 @@ PyDoc_STRVAR(msvcrt_setmode__doc__,
     {"setmode", (PyCFunction)msvcrt_setmode, METH_VARARGS, msvcrt_setmode__doc__},
 
 static long
-msvcrt_setmode_impl(PyModuleDef *module, int fd, int flags);
+msvcrt_setmode_impl(PyObject *module, int fd, int flags);
 
 static PyObject *
-msvcrt_setmode(PyModuleDef *module, PyObject *args)
+msvcrt_setmode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -110,11 +110,10 @@ PyDoc_STRVAR(msvcrt_open_osfhandle__doc__,
     {"open_osfhandle", (PyCFunction)msvcrt_open_osfhandle, METH_VARARGS, msvcrt_open_osfhandle__doc__},
 
 static long
-msvcrt_open_osfhandle_impl(PyModuleDef *module, Py_intptr_t handle,
-                           int flags);
+msvcrt_open_osfhandle_impl(PyObject *module, Py_intptr_t handle, int flags);
 
 static PyObject *
-msvcrt_open_osfhandle(PyModuleDef *module, PyObject *args)
+msvcrt_open_osfhandle(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_intptr_t handle;
@@ -145,10 +144,10 @@ PyDoc_STRVAR(msvcrt_get_osfhandle__doc__,
     {"get_osfhandle", (PyCFunction)msvcrt_get_osfhandle, METH_O, msvcrt_get_osfhandle__doc__},
 
 static Py_intptr_t
-msvcrt_get_osfhandle_impl(PyModuleDef *module, int fd);
+msvcrt_get_osfhandle_impl(PyObject *module, int fd);
 
 static PyObject *
-msvcrt_get_osfhandle(PyModuleDef *module, PyObject *arg)
+msvcrt_get_osfhandle(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int fd;
@@ -175,10 +174,10 @@ PyDoc_STRVAR(msvcrt_kbhit__doc__,
     {"kbhit", (PyCFunction)msvcrt_kbhit, METH_NOARGS, msvcrt_kbhit__doc__},
 
 static long
-msvcrt_kbhit_impl(PyModuleDef *module);
+msvcrt_kbhit_impl(PyObject *module);
 
 static PyObject *
-msvcrt_kbhit(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+msvcrt_kbhit(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     long _return_value;
@@ -208,10 +207,10 @@ PyDoc_STRVAR(msvcrt_getch__doc__,
     {"getch", (PyCFunction)msvcrt_getch, METH_NOARGS, msvcrt_getch__doc__},
 
 static int
-msvcrt_getch_impl(PyModuleDef *module);
+msvcrt_getch_impl(PyObject *module);
 
 static PyObject *
-msvcrt_getch(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+msvcrt_getch(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     char s[1];
@@ -232,10 +231,10 @@ PyDoc_STRVAR(msvcrt_getwch__doc__,
     {"getwch", (PyCFunction)msvcrt_getwch, METH_NOARGS, msvcrt_getwch__doc__},
 
 static wchar_t
-msvcrt_getwch_impl(PyModuleDef *module);
+msvcrt_getwch_impl(PyObject *module);
 
 static PyObject *
-msvcrt_getwch(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+msvcrt_getwch(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     wchar_t _return_value;
@@ -256,10 +255,10 @@ PyDoc_STRVAR(msvcrt_getche__doc__,
     {"getche", (PyCFunction)msvcrt_getche, METH_NOARGS, msvcrt_getche__doc__},
 
 static int
-msvcrt_getche_impl(PyModuleDef *module);
+msvcrt_getche_impl(PyObject *module);
 
 static PyObject *
-msvcrt_getche(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+msvcrt_getche(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     char s[1];
@@ -280,10 +279,10 @@ PyDoc_STRVAR(msvcrt_getwche__doc__,
     {"getwche", (PyCFunction)msvcrt_getwche, METH_NOARGS, msvcrt_getwche__doc__},
 
 static wchar_t
-msvcrt_getwche_impl(PyModuleDef *module);
+msvcrt_getwche_impl(PyObject *module);
 
 static PyObject *
-msvcrt_getwche(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+msvcrt_getwche(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     PyObject *return_value = NULL;
     wchar_t _return_value;
@@ -304,10 +303,10 @@ PyDoc_STRVAR(msvcrt_putch__doc__,
     {"putch", (PyCFunction)msvcrt_putch, METH_O, msvcrt_putch__doc__},
 
 static PyObject *
-msvcrt_putch_impl(PyModuleDef *module, char char_value);
+msvcrt_putch_impl(PyObject *module, char char_value);
 
 static PyObject *
-msvcrt_putch(PyModuleDef *module, PyObject *arg)
+msvcrt_putch(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     char char_value;
@@ -330,10 +329,10 @@ PyDoc_STRVAR(msvcrt_putwch__doc__,
     {"putwch", (PyCFunction)msvcrt_putwch, METH_O, msvcrt_putwch__doc__},
 
 static PyObject *
-msvcrt_putwch_impl(PyModuleDef *module, int unicode_char);
+msvcrt_putwch_impl(PyObject *module, int unicode_char);
 
 static PyObject *
-msvcrt_putwch(PyModuleDef *module, PyObject *arg)
+msvcrt_putwch(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int unicode_char;
@@ -360,10 +359,10 @@ PyDoc_STRVAR(msvcrt_ungetch__doc__,
     {"ungetch", (PyCFunction)msvcrt_ungetch, METH_O, msvcrt_ungetch__doc__},
 
 static PyObject *
-msvcrt_ungetch_impl(PyModuleDef *module, char char_value);
+msvcrt_ungetch_impl(PyObject *module, char char_value);
 
 static PyObject *
-msvcrt_ungetch(PyModuleDef *module, PyObject *arg)
+msvcrt_ungetch(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     char char_value;
@@ -386,10 +385,10 @@ PyDoc_STRVAR(msvcrt_ungetwch__doc__,
     {"ungetwch", (PyCFunction)msvcrt_ungetwch, METH_O, msvcrt_ungetwch__doc__},
 
 static PyObject *
-msvcrt_ungetwch_impl(PyModuleDef *module, int unicode_char);
+msvcrt_ungetwch_impl(PyObject *module, int unicode_char);
 
 static PyObject *
-msvcrt_ungetwch(PyModuleDef *module, PyObject *arg)
+msvcrt_ungetwch(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int unicode_char;
@@ -416,10 +415,10 @@ PyDoc_STRVAR(msvcrt_CrtSetReportFile__doc__,
     {"CrtSetReportFile", (PyCFunction)msvcrt_CrtSetReportFile, METH_VARARGS, msvcrt_CrtSetReportFile__doc__},
 
 static long
-msvcrt_CrtSetReportFile_impl(PyModuleDef *module, int type, int file);
+msvcrt_CrtSetReportFile_impl(PyObject *module, int type, int file);
 
 static PyObject *
-msvcrt_CrtSetReportFile(PyModuleDef *module, PyObject *args)
+msvcrt_CrtSetReportFile(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int type;
@@ -454,10 +453,10 @@ PyDoc_STRVAR(msvcrt_CrtSetReportMode__doc__,
     {"CrtSetReportMode", (PyCFunction)msvcrt_CrtSetReportMode, METH_VARARGS, msvcrt_CrtSetReportMode__doc__},
 
 static long
-msvcrt_CrtSetReportMode_impl(PyModuleDef *module, int type, int mode);
+msvcrt_CrtSetReportMode_impl(PyObject *module, int type, int mode);
 
 static PyObject *
-msvcrt_CrtSetReportMode(PyModuleDef *module, PyObject *args)
+msvcrt_CrtSetReportMode(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int type;
@@ -492,10 +491,10 @@ PyDoc_STRVAR(msvcrt_set_error_mode__doc__,
     {"set_error_mode", (PyCFunction)msvcrt_set_error_mode, METH_O, msvcrt_set_error_mode__doc__},
 
 static long
-msvcrt_set_error_mode_impl(PyModuleDef *module, int mode);
+msvcrt_set_error_mode_impl(PyObject *module, int mode);
 
 static PyObject *
-msvcrt_set_error_mode(PyModuleDef *module, PyObject *arg)
+msvcrt_set_error_mode(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int mode;
@@ -524,10 +523,10 @@ PyDoc_STRVAR(msvcrt_SetErrorMode__doc__,
     {"SetErrorMode", (PyCFunction)msvcrt_SetErrorMode, METH_O, msvcrt_SetErrorMode__doc__},
 
 static PyObject *
-msvcrt_SetErrorMode_impl(PyModuleDef *module, unsigned int mode);
+msvcrt_SetErrorMode_impl(PyObject *module, unsigned int mode);
 
 static PyObject *
-msvcrt_SetErrorMode(PyModuleDef *module, PyObject *arg)
+msvcrt_SetErrorMode(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     unsigned int mode;
@@ -551,4 +550,4 @@ exit:
 #ifndef MSVCRT_SET_ERROR_MODE_METHODDEF
     #define MSVCRT_SET_ERROR_MODE_METHODDEF
 #endif /* !defined(MSVCRT_SET_ERROR_MODE_METHODDEF) */
-/*[clinic end generated code: output=16613d3119a1fd44 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=2a794c520d6ae887 input=a9049054013a1b77]*/
index 338e33d..f6ae2c0 100644 (file)
@@ -135,11 +135,11 @@ PyDoc_STRVAR(winreg_ConnectRegistry__doc__,
     {"ConnectRegistry", (PyCFunction)winreg_ConnectRegistry, METH_VARARGS, winreg_ConnectRegistry__doc__},
 
 static HKEY
-winreg_ConnectRegistry_impl(PyModuleDef *module, Py_UNICODE *computer_name,
+winreg_ConnectRegistry_impl(PyObject *module, Py_UNICODE *computer_name,
                             HKEY key);
 
 static PyObject *
-winreg_ConnectRegistry(PyModuleDef *module, PyObject *args)
+winreg_ConnectRegistry(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_UNICODE *computer_name;
@@ -181,10 +181,10 @@ PyDoc_STRVAR(winreg_CreateKey__doc__,
     {"CreateKey", (PyCFunction)winreg_CreateKey, METH_VARARGS, winreg_CreateKey__doc__},
 
 static HKEY
-winreg_CreateKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key);
+winreg_CreateKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key);
 
 static PyObject *
-winreg_CreateKey(PyModuleDef *module, PyObject *args)
+winreg_CreateKey(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -232,11 +232,11 @@ PyDoc_STRVAR(winreg_CreateKeyEx__doc__,
     {"CreateKeyEx", (PyCFunction)winreg_CreateKeyEx, METH_VARARGS|METH_KEYWORDS, winreg_CreateKeyEx__doc__},
 
 static HKEY
-winreg_CreateKeyEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_CreateKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                         int reserved, REGSAM access);
 
 static PyObject *
-winreg_CreateKeyEx(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+winreg_CreateKeyEx(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"key", "sub_key", "reserved", "access", NULL};
@@ -280,10 +280,10 @@ PyDoc_STRVAR(winreg_DeleteKey__doc__,
     {"DeleteKey", (PyCFunction)winreg_DeleteKey, METH_VARARGS, winreg_DeleteKey__doc__},
 
 static PyObject *
-winreg_DeleteKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key);
+winreg_DeleteKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key);
 
 static PyObject *
-winreg_DeleteKey(PyModuleDef *module, PyObject *args)
+winreg_DeleteKey(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -327,11 +327,11 @@ PyDoc_STRVAR(winreg_DeleteKeyEx__doc__,
     {"DeleteKeyEx", (PyCFunction)winreg_DeleteKeyEx, METH_VARARGS|METH_KEYWORDS, winreg_DeleteKeyEx__doc__},
 
 static PyObject *
-winreg_DeleteKeyEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_DeleteKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                         REGSAM access, int reserved);
 
 static PyObject *
-winreg_DeleteKeyEx(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+winreg_DeleteKeyEx(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"key", "sub_key", "access", "reserved", NULL};
@@ -364,10 +364,10 @@ PyDoc_STRVAR(winreg_DeleteValue__doc__,
     {"DeleteValue", (PyCFunction)winreg_DeleteValue, METH_VARARGS, winreg_DeleteValue__doc__},
 
 static PyObject *
-winreg_DeleteValue_impl(PyModuleDef *module, HKEY key, Py_UNICODE *value);
+winreg_DeleteValue_impl(PyObject *module, HKEY key, Py_UNICODE *value);
 
 static PyObject *
-winreg_DeleteValue(PyModuleDef *module, PyObject *args)
+winreg_DeleteValue(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -401,10 +401,10 @@ PyDoc_STRVAR(winreg_EnumKey__doc__,
     {"EnumKey", (PyCFunction)winreg_EnumKey, METH_VARARGS, winreg_EnumKey__doc__},
 
 static PyObject *
-winreg_EnumKey_impl(PyModuleDef *module, HKEY key, int index);
+winreg_EnumKey_impl(PyObject *module, HKEY key, int index);
 
 static PyObject *
-winreg_EnumKey(PyModuleDef *module, PyObject *args)
+winreg_EnumKey(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -447,10 +447,10 @@ PyDoc_STRVAR(winreg_EnumValue__doc__,
     {"EnumValue", (PyCFunction)winreg_EnumValue, METH_VARARGS, winreg_EnumValue__doc__},
 
 static PyObject *
-winreg_EnumValue_impl(PyModuleDef *module, HKEY key, int index);
+winreg_EnumValue_impl(PyObject *module, HKEY key, int index);
 
 static PyObject *
-winreg_EnumValue(PyModuleDef *module, PyObject *args)
+winreg_EnumValue(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -475,10 +475,10 @@ PyDoc_STRVAR(winreg_ExpandEnvironmentStrings__doc__,
     {"ExpandEnvironmentStrings", (PyCFunction)winreg_ExpandEnvironmentStrings, METH_O, winreg_ExpandEnvironmentStrings__doc__},
 
 static PyObject *
-winreg_ExpandEnvironmentStrings_impl(PyModuleDef *module, Py_UNICODE *string);
+winreg_ExpandEnvironmentStrings_impl(PyObject *module, Py_UNICODE *string);
 
 static PyObject *
-winreg_ExpandEnvironmentStrings(PyModuleDef *module, PyObject *arg)
+winreg_ExpandEnvironmentStrings(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     Py_UNICODE *string;
@@ -514,10 +514,10 @@ PyDoc_STRVAR(winreg_FlushKey__doc__,
     {"FlushKey", (PyCFunction)winreg_FlushKey, METH_O, winreg_FlushKey__doc__},
 
 static PyObject *
-winreg_FlushKey_impl(PyModuleDef *module, HKEY key);
+winreg_FlushKey_impl(PyObject *module, HKEY key);
 
 static PyObject *
-winreg_FlushKey(PyModuleDef *module, PyObject *arg)
+winreg_FlushKey(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -562,11 +562,11 @@ PyDoc_STRVAR(winreg_LoadKey__doc__,
     {"LoadKey", (PyCFunction)winreg_LoadKey, METH_VARARGS, winreg_LoadKey__doc__},
 
 static PyObject *
-winreg_LoadKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_LoadKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                     Py_UNICODE *file_name);
 
 static PyObject *
-winreg_LoadKey(PyModuleDef *module, PyObject *args)
+winreg_LoadKey(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -605,11 +605,11 @@ PyDoc_STRVAR(winreg_OpenKey__doc__,
     {"OpenKey", (PyCFunction)winreg_OpenKey, METH_VARARGS|METH_KEYWORDS, winreg_OpenKey__doc__},
 
 static HKEY
-winreg_OpenKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_OpenKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                     int reserved, REGSAM access);
 
 static PyObject *
-winreg_OpenKey(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+winreg_OpenKey(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"key", "sub_key", "reserved", "access", NULL};
@@ -654,11 +654,11 @@ PyDoc_STRVAR(winreg_OpenKeyEx__doc__,
     {"OpenKeyEx", (PyCFunction)winreg_OpenKeyEx, METH_VARARGS|METH_KEYWORDS, winreg_OpenKeyEx__doc__},
 
 static HKEY
-winreg_OpenKeyEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_OpenKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                       int reserved, REGSAM access);
 
 static PyObject *
-winreg_OpenKeyEx(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+winreg_OpenKeyEx(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"key", "sub_key", "reserved", "access", NULL};
@@ -699,10 +699,10 @@ PyDoc_STRVAR(winreg_QueryInfoKey__doc__,
     {"QueryInfoKey", (PyCFunction)winreg_QueryInfoKey, METH_O, winreg_QueryInfoKey__doc__},
 
 static PyObject *
-winreg_QueryInfoKey_impl(PyModuleDef *module, HKEY key);
+winreg_QueryInfoKey_impl(PyObject *module, HKEY key);
 
 static PyObject *
-winreg_QueryInfoKey(PyModuleDef *module, PyObject *arg)
+winreg_QueryInfoKey(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -739,10 +739,10 @@ PyDoc_STRVAR(winreg_QueryValue__doc__,
     {"QueryValue", (PyCFunction)winreg_QueryValue, METH_VARARGS, winreg_QueryValue__doc__},
 
 static PyObject *
-winreg_QueryValue_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key);
+winreg_QueryValue_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key);
 
 static PyObject *
-winreg_QueryValue(PyModuleDef *module, PyObject *args)
+winreg_QueryValue(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -777,10 +777,10 @@ PyDoc_STRVAR(winreg_QueryValueEx__doc__,
     {"QueryValueEx", (PyCFunction)winreg_QueryValueEx, METH_VARARGS, winreg_QueryValueEx__doc__},
 
 static PyObject *
-winreg_QueryValueEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *name);
+winreg_QueryValueEx_impl(PyObject *module, HKEY key, Py_UNICODE *name);
 
 static PyObject *
-winreg_QueryValueEx(PyModuleDef *module, PyObject *args)
+winreg_QueryValueEx(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -820,10 +820,10 @@ PyDoc_STRVAR(winreg_SaveKey__doc__,
     {"SaveKey", (PyCFunction)winreg_SaveKey, METH_VARARGS, winreg_SaveKey__doc__},
 
 static PyObject *
-winreg_SaveKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *file_name);
+winreg_SaveKey_impl(PyObject *module, HKEY key, Py_UNICODE *file_name);
 
 static PyObject *
-winreg_SaveKey(PyModuleDef *module, PyObject *args)
+winreg_SaveKey(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -868,12 +868,12 @@ PyDoc_STRVAR(winreg_SetValue__doc__,
     {"SetValue", (PyCFunction)winreg_SetValue, METH_VARARGS, winreg_SetValue__doc__},
 
 static PyObject *
-winreg_SetValue_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_SetValue_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                      DWORD type, Py_UNICODE *value,
                      Py_ssize_clean_t value_length);
 
 static PyObject *
-winreg_SetValue(PyModuleDef *module, PyObject *args)
+winreg_SetValue(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -936,11 +936,11 @@ PyDoc_STRVAR(winreg_SetValueEx__doc__,
     {"SetValueEx", (PyCFunction)winreg_SetValueEx, METH_VARARGS, winreg_SetValueEx__doc__},
 
 static PyObject *
-winreg_SetValueEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *value_name,
+winreg_SetValueEx_impl(PyObject *module, HKEY key, Py_UNICODE *value_name,
                        PyObject *reserved, DWORD type, PyObject *value);
 
 static PyObject *
-winreg_SetValueEx(PyModuleDef *module, PyObject *args)
+winreg_SetValueEx(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -977,10 +977,10 @@ PyDoc_STRVAR(winreg_DisableReflectionKey__doc__,
     {"DisableReflectionKey", (PyCFunction)winreg_DisableReflectionKey, METH_O, winreg_DisableReflectionKey__doc__},
 
 static PyObject *
-winreg_DisableReflectionKey_impl(PyModuleDef *module, HKEY key);
+winreg_DisableReflectionKey_impl(PyObject *module, HKEY key);
 
 static PyObject *
-winreg_DisableReflectionKey(PyModuleDef *module, PyObject *arg)
+winreg_DisableReflectionKey(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -1010,10 +1010,10 @@ PyDoc_STRVAR(winreg_EnableReflectionKey__doc__,
     {"EnableReflectionKey", (PyCFunction)winreg_EnableReflectionKey, METH_O, winreg_EnableReflectionKey__doc__},
 
 static PyObject *
-winreg_EnableReflectionKey_impl(PyModuleDef *module, HKEY key);
+winreg_EnableReflectionKey_impl(PyObject *module, HKEY key);
 
 static PyObject *
-winreg_EnableReflectionKey(PyModuleDef *module, PyObject *arg)
+winreg_EnableReflectionKey(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -1041,10 +1041,10 @@ PyDoc_STRVAR(winreg_QueryReflectionKey__doc__,
     {"QueryReflectionKey", (PyCFunction)winreg_QueryReflectionKey, METH_O, winreg_QueryReflectionKey__doc__},
 
 static PyObject *
-winreg_QueryReflectionKey_impl(PyModuleDef *module, HKEY key);
+winreg_QueryReflectionKey_impl(PyObject *module, HKEY key);
 
 static PyObject *
-winreg_QueryReflectionKey(PyModuleDef *module, PyObject *arg)
+winreg_QueryReflectionKey(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     HKEY key;
@@ -1056,4 +1056,4 @@ winreg_QueryReflectionKey(PyModuleDef *module, PyObject *arg)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=5e346dccc296f9f1 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=7b8940a23f605ddc input=a9049054013a1b77]*/
index dca5a42..b00b442 100644 (file)
@@ -17,10 +17,10 @@ PyDoc_STRVAR(winsound_PlaySound__doc__,
     {"PlaySound", (PyCFunction)winsound_PlaySound, METH_VARARGS, winsound_PlaySound__doc__},
 
 static PyObject *
-winsound_PlaySound_impl(PyModuleDef *module, Py_UNICODE *sound, int flags);
+winsound_PlaySound_impl(PyObject *module, Py_UNICODE *sound, int flags);
 
 static PyObject *
-winsound_PlaySound(PyModuleDef *module, PyObject *args)
+winsound_PlaySound(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     Py_UNICODE *sound;
@@ -51,10 +51,10 @@ PyDoc_STRVAR(winsound_Beep__doc__,
     {"Beep", (PyCFunction)winsound_Beep, METH_VARARGS, winsound_Beep__doc__},
 
 static PyObject *
-winsound_Beep_impl(PyModuleDef *module, int frequency, int duration);
+winsound_Beep_impl(PyObject *module, int frequency, int duration);
 
 static PyObject *
-winsound_Beep(PyModuleDef *module, PyObject *args)
+winsound_Beep(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int frequency;
@@ -81,10 +81,10 @@ PyDoc_STRVAR(winsound_MessageBeep__doc__,
     {"MessageBeep", (PyCFunction)winsound_MessageBeep, METH_VARARGS, winsound_MessageBeep__doc__},
 
 static PyObject *
-winsound_MessageBeep_impl(PyModuleDef *module, int x);
+winsound_MessageBeep_impl(PyObject *module, int x);
 
 static PyObject *
-winsound_MessageBeep(PyModuleDef *module, PyObject *args)
+winsound_MessageBeep(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     int x = MB_OK;
@@ -97,4 +97,4 @@ winsound_MessageBeep(PyModuleDef *module, PyObject *args)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=c5b018ac9dc1f500 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=c0b290daf2330dc9 input=a9049054013a1b77]*/
diff --git a/PC/icons.mak b/PC/icons.mak
deleted file mode 100644 (file)
index 4a132c9..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-python_icon.exe:       py.res empty.obj
-       link /out:python_icon.exe /machine:x86 /subsystem:windows py.res empty.obj
-
-py.res:        py.ico pyc.ico pycon.ico icons.rc
-       rc /fo py.res icons.rc
-
-empty.obj:     empty.c
-       cl /c empty.c
-
diff --git a/PC/icons.rc b/PC/icons.rc
deleted file mode 100644 (file)
index d0b4410..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-101 ICON "py.ico"
-102 ICON "pyc.ico"
-103 ICON "pycon.ico"
-
index db5226e..40d4cb5 100644 (file)
@@ -1081,7 +1081,7 @@ static PYC_MAGIC magic_values[] = {
     { 3160, 3180, L"3.2" },
     { 3190, 3230, L"3.3" },
     { 3250, 3310, L"3.4" },
-    { 3320, 3350, L"3.5" },
+    { 3320, 3351, L"3.5" },
     { 3360, 3361, L"3.6" },
     { 0 }
 };
diff --git a/PC/make_versioninfo.c b/PC/make_versioninfo.c
deleted file mode 100644 (file)
index e969671..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-#include <stdio.h>
-#include "patchlevel.h"
-/*
- * This program prints out an include file containing fields required to build
- * the version info resource of pythonxx.dll because the resource compiler
- * cannot do the arithmetic.
- */
-/*
- * FIELD3 is the third field of the version number.
- * This is what we'd like FIELD3 to be:
- *
- * #define FIELD3 (PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL)
- *
- * but that neither gives an error nor comes anywhere close to working.
- *
- * For 2.4a0,
- * PY_MICRO_VERSION = 0
- * PY_RELEASE_LEVEL = 'alpha' = 0xa
- * PY_RELEASE_SERIAL = 0
- *
- * gives FIELD3 = 0*1000 + 10*10 + 0 = 100
- */
-int main(int argc, char **argv)
-{
-    printf("/* This file created by make_versioninfo.exe */\n");
-    printf("#define FIELD3 %d\n",
-        PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL);
-    printf("#define MS_DLL_ID \"%d.%d\"\n",
-           PY_MAJOR_VERSION, PY_MINOR_VERSION);
-    printf("#ifndef _DEBUG\n");
-    printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n",
-           PY_MAJOR_VERSION, PY_MINOR_VERSION);
-    printf("#else\n");
-    printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n",
-           PY_MAJOR_VERSION, PY_MINOR_VERSION);
-    printf("#endif\n");
-    return 0;
-}
index 52d4100..b0739d0 100644 (file)
@@ -78,8 +78,8 @@ to the operating system. On failure, this raises OSError.
 [clinic start generated code]*/
 
 static PyObject *
-msvcrt_heapmin_impl(PyModuleDef *module)
-/*[clinic end generated code: output=464f866feb57c436 input=82e1771d21bde2d8]*/
+msvcrt_heapmin_impl(PyObject *module)
+/*[clinic end generated code: output=1ba00f344782dc19 input=82e1771d21bde2d8]*/
 {
     if (_heapmin() != 0)
         return PyErr_SetFromErrno(PyExc_IOError);
@@ -105,8 +105,8 @@ individually.
 [clinic start generated code]*/
 
 static PyObject *
-msvcrt_locking_impl(PyModuleDef *module, int fd, int mode, long nbytes)
-/*[clinic end generated code: output=dff41e5e76d544de input=d9f13f0f6a713ba7]*/
+msvcrt_locking_impl(PyObject *module, int fd, int mode, long nbytes)
+/*[clinic end generated code: output=a4a90deca9785a03 input=d9f13f0f6a713ba7]*/
 {
     int err;
 
@@ -135,8 +135,8 @@ Return value is the previous mode.
 [clinic start generated code]*/
 
 static long
-msvcrt_setmode_impl(PyModuleDef *module, int fd, int flags)
-/*[clinic end generated code: output=8c84e5b37c586d0d input=76e7c01f6b137f75]*/
+msvcrt_setmode_impl(PyObject *module, int fd, int flags)
+/*[clinic end generated code: output=24a9be5ea07ccb9b input=76e7c01f6b137f75]*/
 {
     flags = _setmode(fd, flags);
     if (flags == -1)
@@ -160,9 +160,8 @@ to os.fdopen() to create a file object.
 [clinic start generated code]*/
 
 static long
-msvcrt_open_osfhandle_impl(PyModuleDef *module, Py_intptr_t handle,
-                           int flags)
-/*[clinic end generated code: output=86bce32582c49c06 input=4d8516ed32db8f65]*/
+msvcrt_open_osfhandle_impl(PyObject *module, Py_intptr_t handle, int flags)
+/*[clinic end generated code: output=bf65e422243a39f9 input=4d8516ed32db8f65]*/
 {
     int fd;
 
@@ -185,8 +184,8 @@ Raises IOError if fd is not recognized.
 [clinic start generated code]*/
 
 static Py_intptr_t
-msvcrt_get_osfhandle_impl(PyModuleDef *module, int fd)
-/*[clinic end generated code: output=376bff52586b55a6 input=c7d18d02c8017ec1]*/
+msvcrt_get_osfhandle_impl(PyObject *module, int fd)
+/*[clinic end generated code: output=eac47643338c0baa input=c7d18d02c8017ec1]*/
 {
     Py_intptr_t handle = -1;
 
@@ -212,8 +211,8 @@ Return true if a keypress is waiting to be read.
 [clinic start generated code]*/
 
 static long
-msvcrt_kbhit_impl(PyModuleDef *module)
-/*[clinic end generated code: output=2b7293fcbe5cb24e input=e70d678a5c2f6acc]*/
+msvcrt_kbhit_impl(PyObject *module)
+/*[clinic end generated code: output=940dfce6587c1890 input=e70d678a5c2f6acc]*/
 {
     return _kbhit();
 }
@@ -231,8 +230,8 @@ cannot be read with this function.
 [clinic start generated code]*/
 
 static int
-msvcrt_getch_impl(PyModuleDef *module)
-/*[clinic end generated code: output=199e3d89f49c166a input=37a40cf0ed0d1153]*/
+msvcrt_getch_impl(PyObject *module)
+/*[clinic end generated code: output=a4e51f0565064a7d input=37a40cf0ed0d1153]*/
 {
     int ch;
 
@@ -249,8 +248,8 @@ Wide char variant of getch(), returning a Unicode value.
 [clinic start generated code]*/
 
 static wchar_t
-msvcrt_getwch_impl(PyModuleDef *module)
-/*[clinic end generated code: output=9d3762861328b1fe input=27b3dec8ad823d7c]*/
+msvcrt_getwch_impl(PyObject *module)
+/*[clinic end generated code: output=be9937494e22f007 input=27b3dec8ad823d7c]*/
 {
     wchar_t ch;
 
@@ -267,8 +266,8 @@ Similar to getch(), but the keypress will be echoed if possible.
 [clinic start generated code]*/
 
 static int
-msvcrt_getche_impl(PyModuleDef *module)
-/*[clinic end generated code: output=8aa369be6550068e input=43311ade9ed4a9c0]*/
+msvcrt_getche_impl(PyObject *module)
+/*[clinic end generated code: output=d8f7db4fd2990401 input=43311ade9ed4a9c0]*/
 {
     int ch;
 
@@ -285,8 +284,8 @@ Wide char variant of getche(), returning a Unicode value.
 [clinic start generated code]*/
 
 static wchar_t
-msvcrt_getwche_impl(PyModuleDef *module)
-/*[clinic end generated code: output=3693cf78e3ea0cf6 input=49337d59d1a591f8]*/
+msvcrt_getwche_impl(PyObject *module)
+/*[clinic end generated code: output=d0dae5ba3829d596 input=49337d59d1a591f8]*/
 {
     wchar_t ch;
 
@@ -306,8 +305,8 @@ Print the byte string char to the console without buffering.
 [clinic start generated code]*/
 
 static PyObject *
-msvcrt_putch_impl(PyModuleDef *module, char char_value)
-/*[clinic end generated code: output=c05548b11554f36f input=ec078dd10cb054d6]*/
+msvcrt_putch_impl(PyObject *module, char char_value)
+/*[clinic end generated code: output=92ec9b81012d8f60 input=ec078dd10cb054d6]*/
 {
     _putch(char_value);
     Py_RETURN_NONE;
@@ -323,8 +322,8 @@ Wide char variant of putch(), accepting a Unicode value.
 [clinic start generated code]*/
 
 static PyObject *
-msvcrt_putwch_impl(PyModuleDef *module, int unicode_char)
-/*[clinic end generated code: output=c216a73694ca73dd input=996ccd0bbcbac4c3]*/
+msvcrt_putwch_impl(PyObject *module, int unicode_char)
+/*[clinic end generated code: output=a3bd1a8951d28eee input=996ccd0bbcbac4c3]*/
 {
     _putwch(unicode_char);
     Py_RETURN_NONE;
@@ -345,8 +344,8 @@ getch() or getche().
 [clinic start generated code]*/
 
 static PyObject *
-msvcrt_ungetch_impl(PyModuleDef *module, char char_value)
-/*[clinic end generated code: output=19a4cd3249709ec9 input=22f07ee9001bbf0f]*/
+msvcrt_ungetch_impl(PyObject *module, char char_value)
+/*[clinic end generated code: output=c6942a0efa119000 input=22f07ee9001bbf0f]*/
 {
     if (_ungetch(char_value) == EOF)
         return PyErr_SetFromErrno(PyExc_IOError);
@@ -363,8 +362,8 @@ Wide char variant of ungetch(), accepting a Unicode value.
 [clinic start generated code]*/
 
 static PyObject *
-msvcrt_ungetwch_impl(PyModuleDef *module, int unicode_char)
-/*[clinic end generated code: output=1ee7674710322bd1 input=83ec0492be04d564]*/
+msvcrt_ungetwch_impl(PyObject *module, int unicode_char)
+/*[clinic end generated code: output=e63af05438b8ba3d input=83ec0492be04d564]*/
 {
     if (_ungetwch(unicode_char) == WEOF)
         return PyErr_SetFromErrno(PyExc_IOError);
@@ -385,8 +384,8 @@ Only available on Debug builds.
 [clinic start generated code]*/
 
 static long
-msvcrt_CrtSetReportFile_impl(PyModuleDef *module, int type, int file)
-/*[clinic end generated code: output=8c3644fb2edfa808 input=bb8f721a604fcc45]*/
+msvcrt_CrtSetReportFile_impl(PyObject *module, int type, int file)
+/*[clinic end generated code: output=df291c7fe032eb68 input=bb8f721a604fcc45]*/
 {
     return (long)_CrtSetReportFile(type, (_HFILE)file);
 }
@@ -404,8 +403,8 @@ Only available on Debug builds.
 [clinic start generated code]*/
 
 static long
-msvcrt_CrtSetReportMode_impl(PyModuleDef *module, int type, int mode)
-/*[clinic end generated code: output=b407fbf8716a52b9 input=9319d29b4319426b]*/
+msvcrt_CrtSetReportMode_impl(PyObject *module, int type, int mode)
+/*[clinic end generated code: output=b2863761523de317 input=9319d29b4319426b]*/
 {
     int res;
 
@@ -427,8 +426,8 @@ Only available on Debug builds.
 [clinic start generated code]*/
 
 static long
-msvcrt_set_error_mode_impl(PyModuleDef *module, int mode)
-/*[clinic end generated code: output=62148adffa90867d input=046fca59c0f20872]*/
+msvcrt_set_error_mode_impl(PyObject *module, int mode)
+/*[clinic end generated code: output=ac4a09040d8ac4e3 input=046fca59c0f20872]*/
 {
     return _set_error_mode(mode);
 }
@@ -444,8 +443,8 @@ Wrapper around SetErrorMode.
 [clinic start generated code]*/
 
 static PyObject *
-msvcrt_SetErrorMode_impl(PyModuleDef *module, unsigned int mode)
-/*[clinic end generated code: output=544c60b085be79c6 input=d8b167258d32d907]*/
+msvcrt_SetErrorMode_impl(PyObject *module, unsigned int mode)
+/*[clinic end generated code: output=01d529293f00da8f input=d8b167258d32d907]*/
 {
     unsigned int res;
 
diff --git a/PC/pyshellext.cpp b/PC/pyshellext.cpp
new file mode 100644 (file)
index 0000000..04fe61e
--- /dev/null
@@ -0,0 +1,605 @@
+// Support back to Vista
+#define _WIN32_WINNT _WIN32_WINNT_VISTA
+#include <sdkddkver.h>
+
+// Use WRL to define a classic COM class
+#define __WRL_CLASSIC_COM__
+#include <wrl.h>
+
+#include <windows.h>
+#include <shlobj.h>
+#include <shlwapi.h>
+#include <olectl.h>
+#include <strsafe.h>
+
+#include "pyshellext_h.h"
+
+#define DDWM_UPDATEWINDOW (WM_USER+3)
+
+static HINSTANCE hModule;
+static CLIPFORMAT cfDropDescription;
+static CLIPFORMAT cfDragWindow;
+
+static const LPCWSTR CLASS_SUBKEY = L"Software\\Classes\\CLSID\\{BEA218D2-6950-497B-9434-61683EC065FE}";
+static const LPCWSTR DRAG_MESSAGE = L"Open with %1";
+
+using namespace Microsoft::WRL;
+
+HRESULT FilenameListCchLengthA(LPCSTR pszSource, size_t cchMax, size_t *pcchLength, size_t *pcchCount) {
+    HRESULT hr = S_OK;
+    size_t count = 0;
+    size_t length = 0;
+
+    while (pszSource && pszSource[0]) {
+        size_t oneLength;
+        hr = StringCchLengthA(pszSource, cchMax - length, &oneLength);
+        if (FAILED(hr)) {
+            return hr;
+        }
+        count += 1;
+        length += oneLength + (strchr(pszSource, ' ') ? 3 : 1);
+        pszSource = &pszSource[oneLength + 1];
+    }
+
+    *pcchCount = count;
+    *pcchLength = length;
+    return hr;
+}
+
+HRESULT FilenameListCchLengthW(LPCWSTR pszSource, size_t cchMax, size_t *pcchLength, size_t *pcchCount) {
+    HRESULT hr = S_OK;
+    size_t count = 0;
+    size_t length = 0;
+
+    while (pszSource && pszSource[0]) {
+        size_t oneLength;
+        hr = StringCchLengthW(pszSource, cchMax - length, &oneLength);
+        if (FAILED(hr)) {
+            return hr;
+        }
+        count += 1;
+        length += oneLength + (wcschr(pszSource, ' ') ? 3 : 1);
+        pszSource = &pszSource[oneLength + 1];
+    }
+
+    *pcchCount = count;
+    *pcchLength = length;
+    return hr;
+}
+
+HRESULT FilenameListCchCopyA(STRSAFE_LPSTR pszDest, size_t cchDest, LPCSTR pszSource, LPCSTR pszSeparator) {
+    HRESULT hr = S_OK;
+    size_t count = 0;
+    size_t length = 0;
+
+    while (pszSource[0]) {
+        STRSAFE_LPSTR newDest;
+
+        hr = StringCchCopyExA(pszDest, cchDest, pszSource, &newDest, &cchDest, 0);
+        if (FAILED(hr)) {
+            return hr;
+        }
+        pszSource += (newDest - pszDest) + 1;
+        pszDest = PathQuoteSpacesA(pszDest) ? newDest + 2 : newDest;
+
+        if (pszSource[0]) {
+            hr = StringCchCopyExA(pszDest, cchDest, pszSeparator, &newDest, &cchDest, 0);
+            if (FAILED(hr)) {
+                return hr;
+            }
+            pszDest = newDest;
+        }
+    }
+
+    return hr;
+}
+
+HRESULT FilenameListCchCopyW(STRSAFE_LPWSTR pszDest, size_t cchDest, LPCWSTR pszSource, LPCWSTR pszSeparator) {
+    HRESULT hr = S_OK;
+    size_t count = 0;
+    size_t length = 0;
+
+    while (pszSource[0]) {
+        STRSAFE_LPWSTR newDest;
+
+        hr = StringCchCopyExW(pszDest, cchDest, pszSource, &newDest, &cchDest, 0);
+        if (FAILED(hr)) {
+            return hr;
+        }
+        pszSource += (newDest - pszDest) + 1;
+        pszDest = PathQuoteSpacesW(pszDest) ? newDest + 2 : newDest;
+
+        if (pszSource[0]) {
+            hr = StringCchCopyExW(pszDest, cchDest, pszSeparator, &newDest, &cchDest, 0);
+            if (FAILED(hr)) {
+                return hr;
+            }
+            pszDest = newDest;
+        }
+    }
+
+    return hr;
+}
+
+
+class PyShellExt : public RuntimeClass<
+    RuntimeClassFlags<ClassicCom>,
+    IDropTarget,
+    IPersistFile
+>
+{
+    LPOLESTR target, target_dir;
+    DWORD target_mode;
+
+    IDataObject *data_obj;
+
+public:
+    PyShellExt() : target(NULL), target_dir(NULL), target_mode(0), data_obj(NULL) {
+        OutputDebugString(L"PyShellExt::PyShellExt");
+    }
+
+    ~PyShellExt() {
+        if (target) {
+            CoTaskMemFree(target);
+        }
+        if (target_dir) {
+            CoTaskMemFree(target_dir);
+        }
+        if (data_obj) {
+            data_obj->Release();
+        }
+    }
+
+private:
+    HRESULT UpdateDropDescription(IDataObject *pDataObj) {
+        STGMEDIUM medium;
+        FORMATETC fmt = {
+            cfDropDescription,
+            NULL,
+            DVASPECT_CONTENT,
+            -1,
+            TYMED_HGLOBAL
+        };
+
+        auto hr = pDataObj->GetData(&fmt, &medium);
+        if (FAILED(hr)) {
+            OutputDebugString(L"PyShellExt::UpdateDropDescription - failed to get DROPDESCRIPTION format");
+            return hr;
+        }
+        if (!medium.hGlobal) {
+            OutputDebugString(L"PyShellExt::UpdateDropDescription - DROPDESCRIPTION format had NULL hGlobal");
+            ReleaseStgMedium(&medium);
+            return E_FAIL;
+        }
+        auto dd = (DROPDESCRIPTION*)GlobalLock(medium.hGlobal);
+        StringCchCopy(dd->szMessage, sizeof(dd->szMessage) / sizeof(dd->szMessage[0]), DRAG_MESSAGE);
+        StringCchCopy(dd->szInsert, sizeof(dd->szInsert) / sizeof(dd->szInsert[0]), PathFindFileNameW(target));
+        dd->type = DROPIMAGE_MOVE;
+
+        GlobalUnlock(medium.hGlobal);
+        ReleaseStgMedium(&medium);
+
+        return S_OK;
+    }
+
+    HRESULT GetDragWindow(IDataObject *pDataObj, HWND *phWnd) {
+        HRESULT hr;
+        HWND *pMem;
+        STGMEDIUM medium;
+        FORMATETC fmt = {
+            cfDragWindow,
+            NULL,
+            DVASPECT_CONTENT,
+            -1,
+            TYMED_HGLOBAL
+        };
+
+        hr = pDataObj->GetData(&fmt, &medium);
+        if (FAILED(hr)) {
+            OutputDebugString(L"PyShellExt::GetDragWindow - failed to get DragWindow format");
+            return hr;
+        }
+        if (!medium.hGlobal) {
+            OutputDebugString(L"PyShellExt::GetDragWindow - DragWindow format had NULL hGlobal");
+            ReleaseStgMedium(&medium);
+            return E_FAIL;
+        }
+
+        pMem = (HWND*)GlobalLock(medium.hGlobal);
+        if (!pMem) {
+            OutputDebugString(L"PyShellExt::GetDragWindow - failed to lock DragWindow hGlobal");
+            ReleaseStgMedium(&medium);
+            return E_FAIL;
+        }
+
+        *phWnd = *pMem;
+
+        GlobalUnlock(medium.hGlobal);
+        ReleaseStgMedium(&medium);
+
+        return S_OK;
+    }
+
+    HRESULT GetArguments(IDataObject *pDataObj, LPCWSTR *pArguments) {
+        HRESULT hr;
+        DROPFILES *pdropfiles;
+
+        STGMEDIUM medium;
+        FORMATETC fmt = {
+            CF_HDROP,
+            NULL,
+            DVASPECT_CONTENT,
+            -1,
+            TYMED_HGLOBAL
+        };
+
+        hr = pDataObj->GetData(&fmt, &medium);
+        if (FAILED(hr)) {
+            OutputDebugString(L"PyShellExt::GetArguments - failed to get CF_HDROP format");
+            return hr;
+        }
+        if (!medium.hGlobal) {
+            OutputDebugString(L"PyShellExt::GetArguments - CF_HDROP format had NULL hGlobal");
+            ReleaseStgMedium(&medium);
+            return E_FAIL;
+        }
+
+        pdropfiles = (DROPFILES*)GlobalLock(medium.hGlobal);
+        if (!pdropfiles) {
+            OutputDebugString(L"PyShellExt::GetArguments - failed to lock CF_HDROP hGlobal");
+            ReleaseStgMedium(&medium);
+            return E_FAIL;
+        }
+
+        if (pdropfiles->fWide) {
+            LPCWSTR files = (LPCWSTR)((char*)pdropfiles + pdropfiles->pFiles);
+            size_t len, count;
+            hr = FilenameListCchLengthW(files, 32767, &len, &count);
+            if (SUCCEEDED(hr)) {
+                LPWSTR args = (LPWSTR)CoTaskMemAlloc(sizeof(WCHAR) * (len + 1));
+                if (args) {
+                    hr = FilenameListCchCopyW(args, 32767, files, L" ");
+                    if (SUCCEEDED(hr)) {
+                        *pArguments = args;
+                    } else {
+                        CoTaskMemFree(args);
+                    }
+                } else {
+                    hr = E_OUTOFMEMORY;
+                }
+            }
+        } else {
+            LPCSTR files = (LPCSTR)((char*)pdropfiles + pdropfiles->pFiles);
+            size_t len, count;
+            hr = FilenameListCchLengthA(files, 32767, &len, &count);
+            if (SUCCEEDED(hr)) {
+                LPSTR temp = (LPSTR)CoTaskMemAlloc(sizeof(CHAR) * (len + 1));
+                if (temp) {
+                    hr = FilenameListCchCopyA(temp, 32767, files, " ");
+                    if (SUCCEEDED(hr)) {
+                        int wlen = MultiByteToWideChar(CP_ACP, 0, temp, (int)len, NULL, 0);
+                        if (wlen) {
+                            LPWSTR args = (LPWSTR)CoTaskMemAlloc(sizeof(WCHAR) * (wlen + 1));
+                            if (MultiByteToWideChar(CP_ACP, 0, temp, (int)len, args, wlen + 1)) {
+                                *pArguments = args;
+                            } else {
+                                OutputDebugString(L"PyShellExt::GetArguments - failed to convert multi-byte to wide-char path");
+                                CoTaskMemFree(args);
+                                hr = E_FAIL;
+                            }
+                        } else {
+                            OutputDebugString(L"PyShellExt::GetArguments - failed to get length of wide-char path");
+                            hr = E_FAIL;
+                        }
+                    }
+                    CoTaskMemFree(temp);
+                } else {
+                    hr = E_OUTOFMEMORY;
+                }
+            }
+        }
+
+        GlobalUnlock(medium.hGlobal);
+        ReleaseStgMedium(&medium);
+
+        return hr;
+    }
+
+    HRESULT NotifyDragWindow(HWND hwnd) {
+        LRESULT res;
+
+        if (!hwnd) {
+            return S_FALSE;
+        }
+
+        res = SendMessage(hwnd, DDWM_UPDATEWINDOW, 0, NULL);
+
+        if (res) {
+            OutputDebugString(L"PyShellExt::NotifyDragWindow - failed to post DDWM_UPDATEWINDOW");
+            return E_FAIL;
+        }
+
+        return S_OK;
+    }
+
+public:
+    // IDropTarget implementation
+
+    STDMETHODIMP DragEnter(IDataObject *pDataObj, DWORD grfKeyState, POINTL pt, DWORD *pdwEffect) {
+        HWND hwnd;
+
+        OutputDebugString(L"PyShellExt::DragEnter");
+
+        pDataObj->AddRef();
+        data_obj = pDataObj;
+
+        *pdwEffect = DROPEFFECT_MOVE;
+
+        if (FAILED(UpdateDropDescription(data_obj))) {
+            OutputDebugString(L"PyShellExt::DragEnter - failed to update drop description");
+        }
+        if (FAILED(GetDragWindow(data_obj, &hwnd))) {
+            OutputDebugString(L"PyShellExt::DragEnter - failed to get drag window");
+        }
+        if (FAILED(NotifyDragWindow(hwnd))) {
+            OutputDebugString(L"PyShellExt::DragEnter - failed to notify drag window");
+        }
+
+        return S_OK;
+    }
+
+    STDMETHODIMP DragLeave() {
+        return S_OK;
+    }
+
+    STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, DWORD *pdwEffect) {
+        return S_OK;
+    }
+
+    STDMETHODIMP Drop(IDataObject *pDataObj, DWORD grfKeyState, POINTL pt, DWORD *pdwEffect) {
+        LPCWSTR args;
+
+        OutputDebugString(L"PyShellExt::Drop");
+        *pdwEffect = DROPEFFECT_NONE;
+
+        if (pDataObj != data_obj) {
+            OutputDebugString(L"PyShellExt::Drop - unexpected data object");
+            return E_FAIL;
+        }
+
+        data_obj->Release();
+        data_obj = NULL;
+
+        if (SUCCEEDED(GetArguments(pDataObj, &args))) {
+            OutputDebugString(args);
+            ShellExecute(NULL, NULL, target, args, target_dir, SW_NORMAL);
+
+            CoTaskMemFree((LPVOID)args);
+        } else {
+            OutputDebugString(L"PyShellExt::Drop - failed to get launch arguments");
+        }
+
+        return S_OK;
+    }
+
+    // IPersistFile implementation
+
+    STDMETHODIMP GetCurFile(LPOLESTR *ppszFileName) {
+        HRESULT hr;
+        size_t len;
+
+        if (!ppszFileName) {
+            return E_POINTER;
+        }
+
+        hr = StringCchLength(target, STRSAFE_MAX_CCH - 1, &len);
+        if (FAILED(hr)) {
+            return E_FAIL;
+        }
+
+        *ppszFileName = (LPOLESTR)CoTaskMemAlloc(sizeof(WCHAR) * (len + 1));
+        if (!*ppszFileName) {
+            return E_OUTOFMEMORY;
+        }
+
+        hr = StringCchCopy(*ppszFileName, len + 1, target);
+        if (FAILED(hr)) {
+            CoTaskMemFree(*ppszFileName);
+            *ppszFileName = NULL;
+            return E_FAIL;
+        }
+
+        return S_OK;
+    }
+
+    STDMETHODIMP IsDirty() {
+        return S_FALSE;
+    }
+
+    STDMETHODIMP Load(LPCOLESTR pszFileName, DWORD dwMode) {
+        HRESULT hr;
+        size_t len;
+
+        OutputDebugString(L"PyShellExt::Load");
+        OutputDebugString(pszFileName);
+
+        hr = StringCchLength(pszFileName, STRSAFE_MAX_CCH - 1, &len);
+        if (FAILED(hr)) {
+            OutputDebugString(L"PyShellExt::Load - failed to get string length");
+            return hr;
+        }
+
+        if (target) {
+            CoTaskMemFree(target);
+        }
+        if (target_dir) {
+            CoTaskMemFree(target_dir);
+        }
+
+        target = (LPOLESTR)CoTaskMemAlloc(sizeof(WCHAR) * (len + 1));
+        if (!target) {
+            OutputDebugString(L"PyShellExt::Load - E_OUTOFMEMORY");
+            return E_OUTOFMEMORY;
+        }
+        target_dir = (LPOLESTR)CoTaskMemAlloc(sizeof(WCHAR) * (len + 1));
+        if (!target_dir) {
+            OutputDebugString(L"PyShellExt::Load - E_OUTOFMEMORY");
+            return E_OUTOFMEMORY;
+        }
+
+        hr = StringCchCopy(target, len + 1, pszFileName);
+        if (FAILED(hr)) {
+            OutputDebugString(L"PyShellExt::Load - failed to copy string");
+            return hr;
+        }
+
+        hr = StringCchCopy(target_dir, len + 1, pszFileName);
+        if (FAILED(hr)) {
+            OutputDebugString(L"PyShellExt::Load - failed to copy string");
+            return hr;
+        }
+        if (!PathRemoveFileSpecW(target_dir)) {
+            OutputDebugStringW(L"PyShellExt::Load - failed to remove filespec from target");
+            return E_FAIL;
+        }
+
+        OutputDebugString(target);
+        target_mode = dwMode;
+        OutputDebugString(L"PyShellExt::Load - S_OK");
+        return S_OK;
+    }
+
+    STDMETHODIMP Save(LPCOLESTR pszFileName, BOOL fRemember) {
+        return E_NOTIMPL;
+    }
+
+    STDMETHODIMP SaveCompleted(LPCOLESTR pszFileName) {
+        return E_NOTIMPL;
+    }
+
+    STDMETHODIMP GetClassID(CLSID *pClassID) {
+        *pClassID = CLSID_PyShellExt;
+        return S_OK;
+    }
+};
+
+CoCreatableClass(PyShellExt);
+
+STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, _COM_Outptr_ void** ppv) {
+    return Module<InProc>::GetModule().GetClassObject(rclsid, riid, ppv);
+}
+
+STDAPI DllCanUnloadNow() {
+    return Module<InProc>::GetModule().Terminate() ? S_OK : S_FALSE;
+}
+
+STDAPI DllRegisterServer() {
+    LONG res;
+    SECURITY_ATTRIBUTES secattr = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE };
+    LPSECURITY_ATTRIBUTES psecattr = NULL;
+    HKEY key, ipsKey;
+    WCHAR modname[MAX_PATH];
+    DWORD modname_len;
+
+    OutputDebugString(L"PyShellExt::DllRegisterServer");
+    if (!hModule) {
+        OutputDebugString(L"PyShellExt::DllRegisterServer - module handle was not set");
+        return SELFREG_E_CLASS;
+    }
+    modname_len = GetModuleFileName(hModule, modname, MAX_PATH);
+    if (modname_len == 0 ||
+        (modname_len == MAX_PATH && GetLastError() == ERROR_INSUFFICIENT_BUFFER)) {
+        OutputDebugString(L"PyShellExt::DllRegisterServer - failed to get module file name");
+        return SELFREG_E_CLASS;
+    }
+
+    DWORD disp;
+    res = RegCreateKeyEx(HKEY_LOCAL_MACHINE, CLASS_SUBKEY, 0, NULL, 0,
+        KEY_ALL_ACCESS, psecattr, &key, &disp);
+    if (res == ERROR_ACCESS_DENIED) {
+        OutputDebugString(L"PyShellExt::DllRegisterServer - failed to write per-machine registration. Attempting per-user instead.");
+        res = RegCreateKeyEx(HKEY_CURRENT_USER, CLASS_SUBKEY, 0, NULL, 0,
+            KEY_ALL_ACCESS, psecattr, &key, &disp);
+    }
+    if (res != ERROR_SUCCESS) {
+        OutputDebugString(L"PyShellExt::DllRegisterServer - failed to create class key");
+        return SELFREG_E_CLASS;
+    }
+
+    res = RegCreateKeyEx(key, L"InProcServer32", 0, NULL, 0,
+        KEY_ALL_ACCESS, psecattr, &ipsKey, NULL);
+    if (res != ERROR_SUCCESS) {
+        RegCloseKey(key);
+        OutputDebugString(L"PyShellExt::DllRegisterServer - failed to create InProcServer32 key");
+        return SELFREG_E_CLASS;
+    }
+
+    res = RegSetValueEx(ipsKey, NULL, 0,
+        REG_SZ, (LPBYTE)modname, modname_len * sizeof(modname[0]));
+
+    if (res != ERROR_SUCCESS) {
+        RegCloseKey(ipsKey);
+        RegCloseKey(key);
+        OutputDebugString(L"PyShellExt::DllRegisterServer - failed to set server path");
+        return SELFREG_E_CLASS;
+    }
+
+    res = RegSetValueEx(ipsKey, L"ThreadingModel", 0,
+        REG_SZ, (LPBYTE)(L"Apartment"), sizeof(L"Apartment"));
+
+    RegCloseKey(ipsKey);
+    RegCloseKey(key);
+    if (res != ERROR_SUCCESS) {
+        OutputDebugString(L"PyShellExt::DllRegisterServer - failed to set threading model");
+        return SELFREG_E_CLASS;
+    }
+
+    SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
+
+    OutputDebugString(L"PyShellExt::DllRegisterServer - S_OK");
+    return S_OK;
+}
+
+STDAPI DllUnregisterServer() {
+    LONG res_lm, res_cu;
+
+    res_lm = RegDeleteTree(HKEY_LOCAL_MACHINE, CLASS_SUBKEY);
+    if (res_lm != ERROR_SUCCESS && res_lm != ERROR_FILE_NOT_FOUND) {
+        OutputDebugString(L"PyShellExt::DllUnregisterServer - failed to delete per-machine registration");
+        return SELFREG_E_CLASS;
+    }
+
+    res_cu = RegDeleteTree(HKEY_CURRENT_USER, CLASS_SUBKEY);
+    if (res_cu != ERROR_SUCCESS && res_cu != ERROR_FILE_NOT_FOUND) {
+        OutputDebugString(L"PyShellExt::DllUnregisterServer - failed to delete per-user registration");
+        return SELFREG_E_CLASS;
+    }
+
+    if (res_lm == ERROR_FILE_NOT_FOUND && res_cu == ERROR_FILE_NOT_FOUND) {
+        OutputDebugString(L"PyShellExt::DllUnregisterServer - extension was not registered");
+        return SELFREG_E_CLASS;
+    }
+
+    SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
+
+    OutputDebugString(L"PyShellExt::DllUnregisterServer - S_OK");
+    return S_OK;
+}
+
+STDAPI_(BOOL) DllMain(_In_opt_ HINSTANCE hinst, DWORD reason, _In_opt_ void*) {
+    if (reason == DLL_PROCESS_ATTACH) {
+        hModule = hinst;
+
+        cfDropDescription = RegisterClipboardFormat(CFSTR_DROPDESCRIPTION);
+        if (!cfDropDescription) {
+            OutputDebugString(L"PyShellExt::DllMain - failed to get CFSTR_DROPDESCRIPTION format");
+        }
+        cfDragWindow = RegisterClipboardFormat(L"DragWindow");
+        if (!cfDragWindow) {
+            OutputDebugString(L"PyShellExt::DllMain - failed to get DragWindow format");
+        }
+
+        DisableThreadLibraryCalls(hinst);
+    }
+    return TRUE;
+}
\ No newline at end of file
diff --git a/PC/pyshellext.def b/PC/pyshellext.def
new file mode 100644 (file)
index 0000000..5424bd1
--- /dev/null
@@ -0,0 +1,6 @@
+LIBRARY        "pyshellext"
+EXPORTS
+  DllRegisterServer PRIVATE
+  DllUnregisterServer PRIVATE
+  DllGetClassObject PRIVATE
+  DllCanUnloadNow PRIVATE
diff --git a/PC/pyshellext.idl b/PC/pyshellext.idl
new file mode 100644 (file)
index 0000000..c0a1838
--- /dev/null
@@ -0,0 +1,12 @@
+import "ocidl.idl";
+
+[uuid(44039A76-3BDD-41C1-A31B-71C00202CE81), version(1.0)]
+library PyShellExtLib
+{
+    [uuid(BEA218D2-6950-497B-9434-61683EC065FE), version(1.0)]
+    coclass PyShellExt
+    {
+        [default] interface IDropTarget;
+        interface IPersistFile;
+    }
+};
\ No newline at end of file
diff --git a/PC/pyshellext.rc b/PC/pyshellext.rc
new file mode 100644 (file)
index 0000000..e5924a4
--- /dev/null
@@ -0,0 +1,46 @@
+#include <windows.h>
+
+#include "python_ver_rc.h"
+
+// Include the manifest file that indicates we support all
+// current versions of Windows.
+#include <winuser.h>
+1 RT_MANIFEST "python.manifest"
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION PYVERSION64
+ PRODUCTVERSION PYVERSION64
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS VS_FF_DEBUG
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS VOS__WINDOWS32
+ FILETYPE VFT_APP
+ FILESUBTYPE 0x0L
+BEGIN
+    BLOCK "StringFileInfo"
+    BEGIN
+        BLOCK "000004b0"
+        BEGIN
+            VALUE "CompanyName", PYTHON_COMPANY "\0"
+            VALUE "FileDescription", "Python\0"
+            VALUE "FileVersion", PYTHON_VERSION
+            VALUE "InternalName", "Python Launcher Shell Extension\0"
+            VALUE "LegalCopyright", PYTHON_COPYRIGHT "\0"
+            VALUE "OriginalFilename", "pyshellext" PYTHON_DEBUG_EXT ".dll\0"
+            VALUE "ProductName", "Python\0"
+            VALUE "ProductVersion", PYTHON_VERSION
+        END
+    END
+    BLOCK "VarFileInfo"
+    BEGIN
+        VALUE "Translation", 0x0, 1200
+    END
+END
\ No newline at end of file
diff --git a/PC/pyshellext_d.def b/PC/pyshellext_d.def
new file mode 100644 (file)
index 0000000..7d2148b
--- /dev/null
@@ -0,0 +1,6 @@
+LIBRARY        "pyshellext_d"
+EXPORTS
+  DllRegisterServer PRIVATE
+  DllUnregisterServer PRIVATE
+  DllGetClassObject PRIVATE
+  DllCanUnloadNow PRIVATE
index 9b7b2f8..d6e4bba 100644 (file)
       <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
     </application> 
   </compatibility>
+  <dependency>
+    <dependentAssembly>
+      <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls"
+                        version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
+    </dependentAssembly>
+  </dependency>
 </assembly>
\ No newline at end of file
index 88c0742..d753049 100644 (file)
@@ -68,6 +68,7 @@ EXPORTS
   PyCodec_IncrementalEncoder=python35.PyCodec_IncrementalEncoder
   PyCodec_KnownEncoding=python35.PyCodec_KnownEncoding
   PyCodec_LookupError=python35.PyCodec_LookupError
+  PyCodec_NameReplaceErrors=python35.PyCodec_NameReplaceErrors
   PyCodec_Register=python35.PyCodec_Register
   PyCodec_RegisterError=python35.PyCodec_RegisterError
   PyCodec_ReplaceErrors=python35.PyCodec_ReplaceErrors
@@ -122,6 +123,7 @@ EXPORTS
   PyErr_Fetch=python35.PyErr_Fetch
   PyErr_Format=python35.PyErr_Format
   PyErr_FormatV=python35.PyErr_FormatV
+  PyErr_GetExcInfo=python35.PyErr_GetExcInfo
   PyErr_GivenExceptionMatches=python35.PyErr_GivenExceptionMatches
   PyErr_NewException=python35.PyErr_NewException
   PyErr_NewExceptionWithDoc=python35.PyErr_NewExceptionWithDoc
@@ -132,14 +134,24 @@ EXPORTS
   PyErr_PrintEx=python35.PyErr_PrintEx
   PyErr_ProgramText=python35.PyErr_ProgramText
   PyErr_Restore=python35.PyErr_Restore
+  PyErr_SetExcFromWindowsErr=python35.PyErr_SetExcFromWindowsErr
+  PyErr_SetExcFromWindowsErrWithFilename=python35.PyErr_SetExcFromWindowsErrWithFilename
+  PyErr_SetExcFromWindowsErrWithFilenameObject=python35.PyErr_SetExcFromWindowsErrWithFilenameObject
+  PyErr_SetExcFromWindowsErrWithFilenameObjects=python35.PyErr_SetExcFromWindowsErrWithFilenameObjects
+  PyErr_SetExcInfo=python35.PyErr_SetExcInfo
   PyErr_SetFromErrno=python35.PyErr_SetFromErrno
   PyErr_SetFromErrnoWithFilename=python35.PyErr_SetFromErrnoWithFilename
   PyErr_SetFromErrnoWithFilenameObject=python35.PyErr_SetFromErrnoWithFilenameObject
+  PyErr_SetFromErrnoWithFilenameObjects=python35.PyErr_SetFromErrnoWithFilenameObjects
+  PyErr_SetFromWindowsErr=python35.PyErr_SetFromWindowsErr
+  PyErr_SetFromWindowsErrWithFilename=python35.PyErr_SetFromWindowsErrWithFilename
+  PyErr_SetImportError=python35.PyErr_SetImportError
   PyErr_SetInterrupt=python35.PyErr_SetInterrupt
   PyErr_SetNone=python35.PyErr_SetNone
   PyErr_SetObject=python35.PyErr_SetObject
   PyErr_SetString=python35.PyErr_SetString
   PyErr_SyntaxLocation=python35.PyErr_SyntaxLocation
+  PyErr_SyntaxLocationEx=python35.PyErr_SyntaxLocationEx
   PyErr_WarnEx=python35.PyErr_WarnEx
   PyErr_WarnExplicit=python35.PyErr_WarnExplicit
   PyErr_WarnFormat=python35.PyErr_WarnFormat
@@ -171,12 +183,21 @@ EXPORTS
   PyExc_AssertionError=python35.PyExc_AssertionError DATA
   PyExc_AttributeError=python35.PyExc_AttributeError DATA
   PyExc_BaseException=python35.PyExc_BaseException DATA
+  PyExc_BlockingIOError=python35.PyExc_BlockingIOError DATA
+  PyExc_BrokenPipeError=python35.PyExc_BrokenPipeError DATA
   PyExc_BufferError=python35.PyExc_BufferError DATA
   PyExc_BytesWarning=python35.PyExc_BytesWarning DATA
+  PyExc_ChildProcessError=python35.PyExc_ChildProcessError DATA
+  PyExc_ConnectionAbortedError=python35.PyExc_ConnectionAbortedError DATA
+  PyExc_ConnectionError=python35.PyExc_ConnectionError DATA
+  PyExc_ConnectionRefusedError=python35.PyExc_ConnectionRefusedError DATA
+  PyExc_ConnectionResetError=python35.PyExc_ConnectionResetError DATA
   PyExc_DeprecationWarning=python35.PyExc_DeprecationWarning DATA
   PyExc_EOFError=python35.PyExc_EOFError DATA
   PyExc_EnvironmentError=python35.PyExc_EnvironmentError DATA
   PyExc_Exception=python35.PyExc_Exception DATA
+  PyExc_FileExistsError=python35.PyExc_FileExistsError DATA
+  PyExc_FileNotFoundError=python35.PyExc_FileNotFoundError DATA
   PyExc_FloatingPointError=python35.PyExc_FloatingPointError DATA
   PyExc_FutureWarning=python35.PyExc_FutureWarning DATA
   PyExc_GeneratorExit=python35.PyExc_GeneratorExit DATA
@@ -185,26 +206,34 @@ EXPORTS
   PyExc_ImportWarning=python35.PyExc_ImportWarning DATA
   PyExc_IndentationError=python35.PyExc_IndentationError DATA
   PyExc_IndexError=python35.PyExc_IndexError DATA
+  PyExc_InterruptedError=python35.PyExc_InterruptedError DATA
+  PyExc_IsADirectoryError=python35.PyExc_IsADirectoryError DATA
   PyExc_KeyError=python35.PyExc_KeyError DATA
   PyExc_KeyboardInterrupt=python35.PyExc_KeyboardInterrupt DATA
   PyExc_LookupError=python35.PyExc_LookupError DATA
   PyExc_MemoryError=python35.PyExc_MemoryError DATA
-  PyExc_MemoryErrorInst=python35.PyExc_MemoryErrorInst DATA
   PyExc_NameError=python35.PyExc_NameError DATA
+  PyExc_NotADirectoryError=python35.PyExc_NotADirectoryError DATA
   PyExc_NotImplementedError=python35.PyExc_NotImplementedError DATA
   PyExc_OSError=python35.PyExc_OSError DATA
   PyExc_OverflowError=python35.PyExc_OverflowError DATA
   PyExc_PendingDeprecationWarning=python35.PyExc_PendingDeprecationWarning DATA
+  PyExc_PermissionError=python35.PyExc_PermissionError DATA
+  PyExc_ProcessLookupError=python35.PyExc_ProcessLookupError DATA
+  PyExc_RecursionError=python35.PyExc_RecursionError DATA
   PyExc_RecursionErrorInst=python35.PyExc_RecursionErrorInst DATA
   PyExc_ReferenceError=python35.PyExc_ReferenceError DATA
+  PyExc_ResourceWarning=python35.PyExc_ResourceWarning DATA
   PyExc_RuntimeError=python35.PyExc_RuntimeError DATA
   PyExc_RuntimeWarning=python35.PyExc_RuntimeWarning DATA
+  PyExc_StopAsyncIteration=python35.PyExc_StopAsyncIteration DATA
   PyExc_StopIteration=python35.PyExc_StopIteration DATA
   PyExc_SyntaxError=python35.PyExc_SyntaxError DATA
   PyExc_SyntaxWarning=python35.PyExc_SyntaxWarning DATA
   PyExc_SystemError=python35.PyExc_SystemError DATA
   PyExc_SystemExit=python35.PyExc_SystemExit DATA
   PyExc_TabError=python35.PyExc_TabError DATA
+  PyExc_TimeoutError=python35.PyExc_TimeoutError DATA
   PyExc_TypeError=python35.PyExc_TypeError DATA
   PyExc_UnboundLocalError=python35.PyExc_UnboundLocalError DATA
   PyExc_UnicodeDecodeError=python35.PyExc_UnicodeDecodeError DATA
@@ -215,6 +244,7 @@ EXPORTS
   PyExc_UserWarning=python35.PyExc_UserWarning DATA
   PyExc_ValueError=python35.PyExc_ValueError DATA
   PyExc_Warning=python35.PyExc_Warning DATA
+  PyExc_WindowsError=python35.PyExc_WindowsError DATA
   PyExc_ZeroDivisionError=python35.PyExc_ZeroDivisionError DATA
   PyException_GetCause=python35.PyException_GetCause
   PyException_GetContext=python35.PyException_GetContext
@@ -242,10 +272,12 @@ EXPORTS
   PyGILState_Release=python35.PyGILState_Release
   PyGetSetDescr_Type=python35.PyGetSetDescr_Type DATA
   PyImport_AddModule=python35.PyImport_AddModule
+  PyImport_AddModuleObject=python35.PyImport_AddModuleObject
   PyImport_AppendInittab=python35.PyImport_AppendInittab
   PyImport_Cleanup=python35.PyImport_Cleanup
   PyImport_ExecCodeModule=python35.PyImport_ExecCodeModule
   PyImport_ExecCodeModuleEx=python35.PyImport_ExecCodeModuleEx
+  PyImport_ExecCodeModuleObject=python35.PyImport_ExecCodeModuleObject
   PyImport_ExecCodeModuleWithPathnames=python35.PyImport_ExecCodeModuleWithPathnames
   PyImport_GetImporter=python35.PyImport_GetImporter
   PyImport_GetMagicNumber=python35.PyImport_GetMagicNumber
@@ -253,8 +285,10 @@ EXPORTS
   PyImport_GetModuleDict=python35.PyImport_GetModuleDict
   PyImport_Import=python35.PyImport_Import
   PyImport_ImportFrozenModule=python35.PyImport_ImportFrozenModule
+  PyImport_ImportFrozenModuleObject=python35.PyImport_ImportFrozenModuleObject
   PyImport_ImportModule=python35.PyImport_ImportModule
   PyImport_ImportModuleLevel=python35.PyImport_ImportModuleLevel
+  PyImport_ImportModuleLevelObject=python35.PyImport_ImportModuleLevelObject
   PyImport_ImportModuleNoBlock=python35.PyImport_ImportModuleNoBlock
   PyImport_ReloadModule=python35.PyImport_ReloadModule
   PyInterpreterState_Clear=python35.PyInterpreterState_Clear
@@ -310,28 +344,36 @@ EXPORTS
   PyMapping_SetItemString=python35.PyMapping_SetItemString
   PyMapping_Size=python35.PyMapping_Size
   PyMapping_Values=python35.PyMapping_Values
+  PyMem_Calloc=python35.PyMem_Calloc
   PyMem_Free=python35.PyMem_Free
   PyMem_Malloc=python35.PyMem_Malloc
   PyMem_Realloc=python35.PyMem_Realloc
   PyMemberDescr_Type=python35.PyMemberDescr_Type DATA
+  PyMemoryView_FromMemory=python35.PyMemoryView_FromMemory
   PyMemoryView_FromObject=python35.PyMemoryView_FromObject
   PyMemoryView_GetContiguous=python35.PyMemoryView_GetContiguous
   PyMemoryView_Type=python35.PyMemoryView_Type DATA
   PyMethodDescr_Type=python35.PyMethodDescr_Type DATA
+  PyModuleDef_Init=python35.PyModuleDef_Init
+  PyModuleDef_Type=python35.PyModuleDef_Type DATA
+  PyModule_AddFunctions=python35.PyModule_AddFunctions
   PyModule_AddIntConstant=python35.PyModule_AddIntConstant
   PyModule_AddObject=python35.PyModule_AddObject
   PyModule_AddStringConstant=python35.PyModule_AddStringConstant
   PyModule_Create2=python35.PyModule_Create2
+  PyModule_ExecDef=python35.PyModule_ExecDef
+  PyModule_FromDefAndSpec2=python35.PyModule_FromDefAndSpec2
   PyModule_GetDef=python35.PyModule_GetDef
   PyModule_GetDict=python35.PyModule_GetDict
   PyModule_GetFilename=python35.PyModule_GetFilename
   PyModule_GetFilenameObject=python35.PyModule_GetFilenameObject
   PyModule_GetName=python35.PyModule_GetName
+  PyModule_GetNameObject=python35.PyModule_GetNameObject
   PyModule_GetState=python35.PyModule_GetState
   PyModule_New=python35.PyModule_New
+  PyModule_NewObject=python35.PyModule_NewObject
+  PyModule_SetDocString=python35.PyModule_SetDocString
   PyModule_Type=python35.PyModule_Type DATA
-  PyModuleDef_Init=python35.PyModuleDef_Init
-  PyModuleDef_Type=python35.PyModuleDef_Type DATA
   PyNullImporter_Type=python35.PyNullImporter_Type DATA
   PyNumber_Absolute=python35.PyNumber_Absolute
   PyNumber_Add=python35.PyNumber_Add
@@ -345,6 +387,7 @@ EXPORTS
   PyNumber_InPlaceAnd=python35.PyNumber_InPlaceAnd
   PyNumber_InPlaceFloorDivide=python35.PyNumber_InPlaceFloorDivide
   PyNumber_InPlaceLshift=python35.PyNumber_InPlaceLshift
+  PyNumber_InPlaceMatrixMultiply=python35.PyNumber_InPlaceMatrixMultiply
   PyNumber_InPlaceMultiply=python35.PyNumber_InPlaceMultiply
   PyNumber_InPlaceOr=python35.PyNumber_InPlaceOr
   PyNumber_InPlacePower=python35.PyNumber_InPlacePower
@@ -357,6 +400,7 @@ EXPORTS
   PyNumber_Invert=python35.PyNumber_Invert
   PyNumber_Long=python35.PyNumber_Long
   PyNumber_Lshift=python35.PyNumber_Lshift
+  PyNumber_MatrixMultiply=python35.PyNumber_MatrixMultiply
   PyNumber_Multiply=python35.PyNumber_Multiply
   PyNumber_Negative=python35.PyNumber_Negative
   PyNumber_Or=python35.PyNumber_Or
@@ -368,7 +412,16 @@ EXPORTS
   PyNumber_ToBase=python35.PyNumber_ToBase
   PyNumber_TrueDivide=python35.PyNumber_TrueDivide
   PyNumber_Xor=python35.PyNumber_Xor
+  PyODictItems_Type=python35.PyODictItems_Type DATA
+  PyODictIter_Type=python35.PyODictIter_Type DATA
+  PyODictKeys_Type=python35.PyODictKeys_Type DATA
+  PyODictValues_Type=python35.PyODictValues_Type DATA
+  PyODict_DelItem=python35.PyODict_DelItem
+  PyODict_New=python35.PyODict_New
+  PyODict_SetItem=python35.PyODict_SetItem
+  PyODict_Type=python35.PyODict_Type DATA
   PyOS_AfterFork=python35.PyOS_AfterFork
+  PyOS_CheckStack=python35.PyOS_CheckStack
   PyOS_InitInterrupts=python35.PyOS_InitInterrupts
   PyOS_InputHook=python35.PyOS_InputHook DATA
   PyOS_InterruptOccurred=python35.PyOS_InterruptOccurred
@@ -395,6 +448,7 @@ EXPORTS
   PyObject_CallMethod=python35.PyObject_CallMethod
   PyObject_CallMethodObjArgs=python35.PyObject_CallMethodObjArgs
   PyObject_CallObject=python35.PyObject_CallObject
+  PyObject_Calloc=python35.PyObject_Calloc
   PyObject_CheckReadBuffer=python35.PyObject_CheckReadBuffer
   PyObject_ClearWeakRefs=python35.PyObject_ClearWeakRefs
   PyObject_DelItem=python35.PyObject_DelItem
@@ -407,6 +461,7 @@ EXPORTS
   PyObject_GC_UnTrack=python35.PyObject_GC_UnTrack
   PyObject_GenericGetAttr=python35.PyObject_GenericGetAttr
   PyObject_GenericSetAttr=python35.PyObject_GenericSetAttr
+  PyObject_GenericSetDict=python35.PyObject_GenericSetDict
   PyObject_GetAttr=python35.PyObject_GetAttr
   PyObject_GetAttrString=python35.PyObject_GetAttrString
   PyObject_GetItem=python35.PyObject_GetItem
@@ -433,17 +488,10 @@ EXPORTS
   PyObject_SetItem=python35.PyObject_SetItem
   PyObject_Size=python35.PyObject_Size
   PyObject_Str=python35.PyObject_Str
-  PyObject_Type=python35.PyObject_Type DATA
-  PyODict_DelItem=python35.PyODict_DelItem
-  PyODict_New=python35.PyODict_New
-  PyODict_SetItem=python35.PyODict_SetItem
-  PyODict_Type=python35.PyODict_Type DATA
-  PyODictItems_Type=python35.PyODictItems_Type DATA
-  PyODictIter_Type=python35.PyODictIter_Type DATA
-  PyODictKeys_Type=python35.PyODictKeys_Type DATA
-  PyODictValues_Type=python35.PyODictValues_Type DATA
+  PyObject_Type=python35.PyObject_Type
   PyParser_SimpleParseFileFlags=python35.PyParser_SimpleParseFileFlags
   PyParser_SimpleParseStringFlags=python35.PyParser_SimpleParseStringFlags
+  PyParser_SimpleParseStringFlagsFilename=python35.PyParser_SimpleParseStringFlagsFilename
   PyProperty_Type=python35.PyProperty_Type DATA
   PyRangeIter_Type=python35.PyRangeIter_Type DATA
   PyRange_Type=python35.PyRange_Type DATA
@@ -484,8 +532,8 @@ EXPORTS
   PySlice_New=python35.PySlice_New
   PySlice_Type=python35.PySlice_Type DATA
   PySortWrapper_Type=python35.PySortWrapper_Type DATA
-  PyState_FindModule=python35.PyState_FindModule
   PyState_AddModule=python35.PyState_AddModule
+  PyState_FindModule=python35.PyState_FindModule
   PyState_RemoveModule=python35.PyState_RemoveModule
   PyStructSequence_GetItem=python35.PyStructSequence_GetItem
   PyStructSequence_New=python35.PyStructSequence_New
@@ -494,9 +542,11 @@ EXPORTS
   PySuper_Type=python35.PySuper_Type DATA
   PySys_AddWarnOption=python35.PySys_AddWarnOption
   PySys_AddWarnOptionUnicode=python35.PySys_AddWarnOptionUnicode
+  PySys_AddXOption=python35.PySys_AddXOption
   PySys_FormatStderr=python35.PySys_FormatStderr
   PySys_FormatStdout=python35.PySys_FormatStdout
   PySys_GetObject=python35.PySys_GetObject
+  PySys_GetXOptions=python35.PySys_GetXOptions
   PySys_HasWarnOptions=python35.PySys_HasWarnOptions
   PySys_ResetWarnOptions=python35.PySys_ResetWarnOptions
   PySys_SetArgv=python35.PySys_SetArgv
@@ -571,34 +621,51 @@ EXPORTS
   PyUnicode_AsEncodedString=python35.PyUnicode_AsEncodedString
   PyUnicode_AsEncodedUnicode=python35.PyUnicode_AsEncodedUnicode
   PyUnicode_AsLatin1String=python35.PyUnicode_AsLatin1String
+  PyUnicode_AsMBCSString=python35.PyUnicode_AsMBCSString
   PyUnicode_AsRawUnicodeEscapeString=python35.PyUnicode_AsRawUnicodeEscapeString
+  PyUnicode_AsUCS4=python35.PyUnicode_AsUCS4
+  PyUnicode_AsUCS4Copy=python35.PyUnicode_AsUCS4Copy
   PyUnicode_AsUTF16String=python35.PyUnicode_AsUTF16String
   PyUnicode_AsUTF32String=python35.PyUnicode_AsUTF32String
   PyUnicode_AsUTF8String=python35.PyUnicode_AsUTF8String
   PyUnicode_AsUnicodeEscapeString=python35.PyUnicode_AsUnicodeEscapeString
   PyUnicode_AsWideChar=python35.PyUnicode_AsWideChar
-  PyUnicode_ClearFreelist=python35.PyUnicode_ClearFreelist
+  PyUnicode_AsWideCharString=python35.PyUnicode_AsWideCharString
+  PyUnicode_BuildEncodingMap=python35.PyUnicode_BuildEncodingMap
+  PyUnicode_ClearFreeList=python35.PyUnicode_ClearFreeList
   PyUnicode_Compare=python35.PyUnicode_Compare
+  PyUnicode_CompareWithASCIIString=python35.PyUnicode_CompareWithASCIIString
   PyUnicode_Concat=python35.PyUnicode_Concat
   PyUnicode_Contains=python35.PyUnicode_Contains
   PyUnicode_Count=python35.PyUnicode_Count
   PyUnicode_Decode=python35.PyUnicode_Decode
   PyUnicode_DecodeASCII=python35.PyUnicode_DecodeASCII
   PyUnicode_DecodeCharmap=python35.PyUnicode_DecodeCharmap
+  PyUnicode_DecodeCodePageStateful=python35.PyUnicode_DecodeCodePageStateful
   PyUnicode_DecodeFSDefault=python35.PyUnicode_DecodeFSDefault
   PyUnicode_DecodeFSDefaultAndSize=python35.PyUnicode_DecodeFSDefaultAndSize
   PyUnicode_DecodeLatin1=python35.PyUnicode_DecodeLatin1
+  PyUnicode_DecodeLocale=python35.PyUnicode_DecodeLocale
+  PyUnicode_DecodeLocaleAndSize=python35.PyUnicode_DecodeLocaleAndSize
+  PyUnicode_DecodeMBCS=python35.PyUnicode_DecodeMBCS
+  PyUnicode_DecodeMBCSStateful=python35.PyUnicode_DecodeMBCSStateful
   PyUnicode_DecodeRawUnicodeEscape=python35.PyUnicode_DecodeRawUnicodeEscape
   PyUnicode_DecodeUTF16=python35.PyUnicode_DecodeUTF16
   PyUnicode_DecodeUTF16Stateful=python35.PyUnicode_DecodeUTF16Stateful
   PyUnicode_DecodeUTF32=python35.PyUnicode_DecodeUTF32
   PyUnicode_DecodeUTF32Stateful=python35.PyUnicode_DecodeUTF32Stateful
+  PyUnicode_DecodeUTF7=python35.PyUnicode_DecodeUTF7
+  PyUnicode_DecodeUTF7Stateful=python35.PyUnicode_DecodeUTF7Stateful
   PyUnicode_DecodeUTF8=python35.PyUnicode_DecodeUTF8
   PyUnicode_DecodeUTF8Stateful=python35.PyUnicode_DecodeUTF8Stateful
   PyUnicode_DecodeUnicodeEscape=python35.PyUnicode_DecodeUnicodeEscape
+  PyUnicode_EncodeCodePage=python35.PyUnicode_EncodeCodePage
+  PyUnicode_EncodeFSDefault=python35.PyUnicode_EncodeFSDefault
+  PyUnicode_EncodeLocale=python35.PyUnicode_EncodeLocale
   PyUnicode_FSConverter=python35.PyUnicode_FSConverter
   PyUnicode_FSDecoder=python35.PyUnicode_FSDecoder
   PyUnicode_Find=python35.PyUnicode_Find
+  PyUnicode_FindChar=python35.PyUnicode_FindChar
   PyUnicode_Format=python35.PyUnicode_Format
   PyUnicode_FromEncodedObject=python35.PyUnicode_FromEncodedObject
   PyUnicode_FromFormat=python35.PyUnicode_FromFormat
@@ -609,30 +676,28 @@ EXPORTS
   PyUnicode_FromStringAndSize=python35.PyUnicode_FromStringAndSize
   PyUnicode_FromWideChar=python35.PyUnicode_FromWideChar
   PyUnicode_GetDefaultEncoding=python35.PyUnicode_GetDefaultEncoding
+  PyUnicode_GetLength=python35.PyUnicode_GetLength
   PyUnicode_GetSize=python35.PyUnicode_GetSize
+  PyUnicode_InternFromString=python35.PyUnicode_InternFromString
+  PyUnicode_InternImmortal=python35.PyUnicode_InternImmortal
+  PyUnicode_InternInPlace=python35.PyUnicode_InternInPlace
   PyUnicode_IsIdentifier=python35.PyUnicode_IsIdentifier
   PyUnicode_Join=python35.PyUnicode_Join
   PyUnicode_Partition=python35.PyUnicode_Partition
   PyUnicode_RPartition=python35.PyUnicode_RPartition
   PyUnicode_RSplit=python35.PyUnicode_RSplit
+  PyUnicode_ReadChar=python35.PyUnicode_ReadChar
   PyUnicode_Replace=python35.PyUnicode_Replace
   PyUnicode_Resize=python35.PyUnicode_Resize
   PyUnicode_RichCompare=python35.PyUnicode_RichCompare
-  PyUnicode_SetDefaultEncoding=python35.PyUnicode_SetDefaultEncoding
   PyUnicode_Split=python35.PyUnicode_Split
   PyUnicode_Splitlines=python35.PyUnicode_Splitlines
+  PyUnicode_Substring=python35.PyUnicode_Substring
   PyUnicode_Tailmatch=python35.PyUnicode_Tailmatch
   PyUnicode_Translate=python35.PyUnicode_Translate
-  PyUnicode_BuildEncodingMap=python35.PyUnicode_BuildEncodingMap
-  PyUnicode_CompareWithASCIIString=python35.PyUnicode_CompareWithASCIIString
-  PyUnicode_DecodeUTF7=python35.PyUnicode_DecodeUTF7
-  PyUnicode_DecodeUTF7Stateful=python35.PyUnicode_DecodeUTF7Stateful
-  PyUnicode_EncodeFSDefault=python35.PyUnicode_EncodeFSDefault
-  PyUnicode_InternFromString=python35.PyUnicode_InternFromString
-  PyUnicode_InternImmortal=python35.PyUnicode_InternImmortal
-  PyUnicode_InternInPlace=python35.PyUnicode_InternInPlace
   PyUnicode_Type=python35.PyUnicode_Type DATA
-  PyWeakref_GetObject=python35.PyWeakref_GetObject DATA
+  PyUnicode_WriteChar=python35.PyUnicode_WriteChar
+  PyWeakref_GetObject=python35.PyWeakref_GetObject
   PyWeakref_NewProxy=python35.PyWeakref_NewProxy
   PyWeakref_NewRef=python35.PyWeakref_NewRef
   PyWrapperDescr_Type=python35.PyWrapperDescr_Type DATA
@@ -643,6 +708,8 @@ EXPORTS
   Py_BuildValue=python35.Py_BuildValue
   Py_CompileString=python35.Py_CompileString
   Py_DecRef=python35.Py_DecRef
+  Py_DecodeLocale=python35.Py_DecodeLocale
+  Py_EncodeLocale=python35.Py_EncodeLocale
   Py_EndInterpreter=python35.Py_EndInterpreter
   Py_Exit=python35.Py_Exit
   Py_FatalError=python35.Py_FatalError
@@ -670,11 +737,17 @@ EXPORTS
   Py_NewInterpreter=python35.Py_NewInterpreter
   Py_ReprEnter=python35.Py_ReprEnter
   Py_ReprLeave=python35.Py_ReprLeave
+  Py_SetPath=python35.Py_SetPath
   Py_SetProgramName=python35.Py_SetProgramName
   Py_SetPythonHome=python35.Py_SetPythonHome
   Py_SetRecursionLimit=python35.Py_SetRecursionLimit
   Py_SymtableString=python35.Py_SymtableString
   Py_VaBuildValue=python35.Py_VaBuildValue
+  _PyArg_ParseTupleAndKeywords_SizeT=python35._PyArg_ParseTupleAndKeywords_SizeT
+  _PyArg_ParseTuple_SizeT=python35._PyArg_ParseTuple_SizeT
+  _PyArg_Parse_SizeT=python35._PyArg_Parse_SizeT
+  _PyArg_VaParseTupleAndKeywords_SizeT=python35._PyArg_VaParseTupleAndKeywords_SizeT
+  _PyArg_VaParse_SizeT=python35._PyArg_VaParse_SizeT
   _PyErr_BadInternalCall=python35._PyErr_BadInternalCall
   _PyObject_CallFunction_SizeT=python35._PyObject_CallFunction_SizeT
   _PyObject_CallMethod_SizeT=python35._PyObject_CallMethod_SizeT
@@ -691,6 +764,8 @@ EXPORTS
   _PyTrash_delete_nesting=python35._PyTrash_delete_nesting DATA
   _PyTrash_deposit_object=python35._PyTrash_deposit_object
   _PyTrash_destroy_chain=python35._PyTrash_destroy_chain
+  _PyTrash_thread_deposit_object=python35._PyTrash_thread_deposit_object
+  _PyTrash_thread_destroy_chain=python35._PyTrash_thread_destroy_chain
   _PyWeakref_CallableProxyType=python35._PyWeakref_CallableProxyType DATA
   _PyWeakref_ProxyType=python35._PyWeakref_ProxyType DATA
   _PyWeakref_RefType=python35._PyWeakref_RefType DATA
@@ -705,9 +780,3 @@ EXPORTS
   _Py_SwappedOp=python35._Py_SwappedOp DATA
   _Py_TrueStruct=python35._Py_TrueStruct DATA
   _Py_VaBuildValue_SizeT=python35._Py_VaBuildValue_SizeT
-  _PyArg_Parse_SizeT=python35._PyArg_Parse_SizeT
-  _PyArg_ParseTuple_SizeT=python35._PyArg_ParseTuple_SizeT
-  _PyArg_ParseTupleAndKeywords_SizeT=python35._PyArg_ParseTupleAndKeywords_SizeT
-  _PyArg_VaParse_SizeT=python35._PyArg_VaParse_SizeT
-  _PyArg_VaParseTupleAndKeywords_SizeT=python35._PyArg_VaParseTupleAndKeywords_SizeT
-  _Py_BuildValue_SizeT=python35._Py_BuildValue_SizeT
index 6145d59..0ba54ab 100644 (file)
@@ -82,7 +82,8 @@ print('{} is version {}.{}.{}.{}'.format(name.value, *ver))
 
 if ver < (10, 0, 10586):
     print('WARN: ucrtbased contains known issues. '
-          'Please update Visual Studio or the Windows SDK.')
+          'Please update the Windows 10 SDK.')
     print('See:')
-    print('  http://bugs.python.org/issue26624')
+    print('  http://bugs.python.org/issue27705')
+    print('  https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk')
     sys.exit(1)
index d1c3f39..f08d9a4 100644 (file)
@@ -774,8 +774,8 @@ closed when the hkey object is destroyed by Python.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_CloseKey(PyModuleDef *module, PyObject *hkey)
-/*[clinic end generated code: output=d96f73439403a064 input=5b1aac65ba5127ad]*/
+winreg_CloseKey(PyObject *module, PyObject *hkey)
+/*[clinic end generated code: output=a4fa537019a80d15 input=5b1aac65ba5127ad]*/
 {
     if (!PyHKEY_Close(hkey))
         return NULL;
@@ -799,9 +799,9 @@ If the function fails, an OSError exception is raised.
 [clinic start generated code]*/
 
 static HKEY
-winreg_ConnectRegistry_impl(PyModuleDef *module, Py_UNICODE *computer_name,
+winreg_ConnectRegistry_impl(PyObject *module, Py_UNICODE *computer_name,
                             HKEY key)
-/*[clinic end generated code: output=5c52f6f7ba6e7b46 input=5f98a891a347e68e]*/
+/*[clinic end generated code: output=5ab79d02aa3167b4 input=5f98a891a347e68e]*/
 {
     HKEY retKey;
     long rc;
@@ -836,8 +836,8 @@ If the function fails, an OSError exception is raised.
 [clinic start generated code]*/
 
 static HKEY
-winreg_CreateKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key)
-/*[clinic end generated code: output=cd6843f30a73fc0e input=3cdd1622488acea2]*/
+winreg_CreateKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key)
+/*[clinic end generated code: output=9c81d4095527c927 input=3cdd1622488acea2]*/
 {
     HKEY retKey;
     long rc;
@@ -875,9 +875,9 @@ If the function fails, an OSError exception is raised.
 [clinic start generated code]*/
 
 static HKEY
-winreg_CreateKeyEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_CreateKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                         int reserved, REGSAM access)
-/*[clinic end generated code: output=db835d5be84e72b2 input=42c2b03f98406b66]*/
+/*[clinic end generated code: output=b9fce6dc5c4e39b1 input=42c2b03f98406b66]*/
 {
     HKEY retKey;
     long rc;
@@ -910,8 +910,8 @@ is removed.  If the function fails, an OSError exception is raised.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_DeleteKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key)
-/*[clinic end generated code: output=875c8917dacbc99d input=b31d225b935e4211]*/
+winreg_DeleteKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key)
+/*[clinic end generated code: output=7734b1e431991ae4 input=b31d225b935e4211]*/
 {
     long rc;
     rc = RegDeleteKeyW(key, sub_key );
@@ -945,9 +945,9 @@ On unsupported Windows versions, NotImplementedError is raised.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_DeleteKeyEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_DeleteKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                         REGSAM access, int reserved)
-/*[clinic end generated code: output=0362a0ac6502379f input=711d9d89e7ecbed7]*/
+/*[clinic end generated code: output=01378d86ad3eb936 input=711d9d89e7ecbed7]*/
 {
     HMODULE hMod;
     typedef LONG (WINAPI *RDKEFunc)(HKEY, const wchar_t*, REGSAM, int);
@@ -987,8 +987,8 @@ Removes a named value from a registry key.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_DeleteValue_impl(PyModuleDef *module, HKEY key, Py_UNICODE *value)
-/*[clinic end generated code: output=308550b8cdcfd8e1 input=a78d3407a4197b21]*/
+winreg_DeleteValue_impl(PyObject *module, HKEY key, Py_UNICODE *value)
+/*[clinic end generated code: output=67e7e9a514f84951 input=a78d3407a4197b21]*/
 {
     long rc;
     Py_BEGIN_ALLOW_THREADS
@@ -1017,8 +1017,8 @@ raised, indicating no more values are available.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_EnumKey_impl(PyModuleDef *module, HKEY key, int index)
-/*[clinic end generated code: output=58074ffabbc67896 input=fad9a7c00ab0e04b]*/
+winreg_EnumKey_impl(PyObject *module, HKEY key, int index)
+/*[clinic end generated code: output=25a6ec52cd147bc4 input=fad9a7c00ab0e04b]*/
 {
     long rc;
     PyObject *retStr;
@@ -1068,8 +1068,8 @@ The result is a tuple of 3 items:
 [clinic start generated code]*/
 
 static PyObject *
-winreg_EnumValue_impl(PyModuleDef *module, HKEY key, int index)
-/*[clinic end generated code: output=4570367ebaf0e979 input=4414f47a6fb238b5]*/
+winreg_EnumValue_impl(PyObject *module, HKEY key, int index)
+/*[clinic end generated code: output=d363b5a06f8789ac input=4414f47a6fb238b5]*/
 {
     long rc;
     wchar_t *retValueBuf;
@@ -1155,8 +1155,8 @@ Expand environment vars.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_ExpandEnvironmentStrings_impl(PyModuleDef *module, Py_UNICODE *string)
-/*[clinic end generated code: output=4cb6914065a8663c input=b2a9714d2b751aa6]*/
+winreg_ExpandEnvironmentStrings_impl(PyObject *module, Py_UNICODE *string)
+/*[clinic end generated code: output=cba46ac293a8af1a input=b2a9714d2b751aa6]*/
 {
     wchar_t *retValue = NULL;
     DWORD retValueSize;
@@ -1205,8 +1205,8 @@ a FlushKey() call is required, it probably isn't.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_FlushKey_impl(PyModuleDef *module, HKEY key)
-/*[clinic end generated code: output=b9a7a6e405466420 input=f57457c12297d82f]*/
+winreg_FlushKey_impl(PyObject *module, HKEY key)
+/*[clinic end generated code: output=e6fc230d4c5dc049 input=f57457c12297d82f]*/
 {
     long rc;
     Py_BEGIN_ALLOW_THREADS
@@ -1248,9 +1248,9 @@ tree.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_LoadKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_LoadKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                     Py_UNICODE *file_name)
-/*[clinic end generated code: output=b8b700e39c695b90 input=e3b5b45ade311582]*/
+/*[clinic end generated code: output=87344005c5905cde input=e3b5b45ade311582]*/
 {
     long rc;
 
@@ -1282,9 +1282,9 @@ If the function fails, an OSError exception is raised.
 [clinic start generated code]*/
 
 static HKEY
-winreg_OpenKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_OpenKey_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                     int reserved, REGSAM access)
-/*[clinic end generated code: output=79818ea356490a55 input=098505ac36a9ae28]*/
+/*[clinic end generated code: output=a905f1b947f3ce85 input=098505ac36a9ae28]*/
 {
     HKEY retKey;
     long rc;
@@ -1309,9 +1309,9 @@ If the function fails, an OSError exception is raised.
 [clinic start generated code]*/
 
 static HKEY
-winreg_OpenKeyEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_OpenKeyEx_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                       int reserved, REGSAM access)
-/*[clinic end generated code: output=2dd9f29e84ea2dbc input=c6c4972af8622959]*/
+/*[clinic end generated code: output=226042593b37e940 input=c6c4972af8622959]*/
 {
     return winreg_OpenKey_impl(module, key, sub_key, reserved, access);
 }
@@ -1333,8 +1333,8 @@ as 100's of nanoseconds since Jan 1, 1600.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_QueryInfoKey_impl(PyModuleDef *module, HKEY key)
-/*[clinic end generated code: output=ae885222fe966a34 input=c3593802390cde1f]*/
+winreg_QueryInfoKey_impl(PyObject *module, HKEY key)
+/*[clinic end generated code: output=dc657b8356a4f438 input=c3593802390cde1f]*/
 {
   long rc;
   DWORD nSubKeys, nValues;
@@ -1379,8 +1379,8 @@ completeness.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_QueryValue_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key)
-/*[clinic end generated code: output=f91cb6f623c3b65a input=41cafbbf423b21d6]*/
+winreg_QueryValue_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key)
+/*[clinic end generated code: output=2bb8d1e02c10d0b6 input=41cafbbf423b21d6]*/
 {
     long rc;
     PyObject *retStr;
@@ -1446,8 +1446,8 @@ The return value is a tuple of the value and the type_id.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_QueryValueEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *name)
-/*[clinic end generated code: output=a4b07f7807194f23 input=cf366cada4836891]*/
+winreg_QueryValueEx_impl(PyObject *module, HKEY key, Py_UNICODE *name)
+/*[clinic end generated code: output=5b4fa3e33d6d3e8f input=cf366cada4836891]*/
 {
     long rc;
     BYTE *retBuf, *tmp;
@@ -1519,8 +1519,8 @@ to the API.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_SaveKey_impl(PyModuleDef *module, HKEY key, Py_UNICODE *file_name)
-/*[clinic end generated code: output=33109b96bfabef8f input=da735241f91ac7a2]*/
+winreg_SaveKey_impl(PyObject *module, HKEY key, Py_UNICODE *file_name)
+/*[clinic end generated code: output=1dda1502bd4c30d8 input=da735241f91ac7a2]*/
 {
     LPSECURITY_ATTRIBUTES pSA = NULL;
 
@@ -1565,10 +1565,10 @@ KEY_SET_VALUE access.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_SetValue_impl(PyModuleDef *module, HKEY key, Py_UNICODE *sub_key,
+winreg_SetValue_impl(PyObject *module, HKEY key, Py_UNICODE *sub_key,
                      DWORD type, Py_UNICODE *value,
                      Py_ssize_clean_t value_length)
-/*[clinic end generated code: output=3c9c7c2769e8f953 input=2cd2adab79339c53]*/
+/*[clinic end generated code: output=1e31931174820631 input=2cd2adab79339c53]*/
 {
     long rc;
 
@@ -1629,9 +1629,9 @@ the configuration registry to help the registry perform efficiently.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_SetValueEx_impl(PyModuleDef *module, HKEY key, Py_UNICODE *value_name,
+winreg_SetValueEx_impl(PyObject *module, HKEY key, Py_UNICODE *value_name,
                        PyObject *reserved, DWORD type, PyObject *value)
-/*[clinic end generated code: output=ea092a935c361582 input=f1b16cbcc3ed4101]*/
+/*[clinic end generated code: output=c88c8426b6c00ec7 input=f1b16cbcc3ed4101]*/
 {
     BYTE *data;
     DWORD len;
@@ -1672,8 +1672,8 @@ of any subkeys.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_DisableReflectionKey_impl(PyModuleDef *module, HKEY key)
-/*[clinic end generated code: output=50fe6e2604324cdd input=a6c9e5ca5410193c]*/
+winreg_DisableReflectionKey_impl(PyObject *module, HKEY key)
+/*[clinic end generated code: output=830cce504cc764b4 input=a6c9e5ca5410193c]*/
 {
     HMODULE hMod;
     typedef LONG (WINAPI *RDRKFunc)(HKEY);
@@ -1715,8 +1715,8 @@ subkeys.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_EnableReflectionKey_impl(PyModuleDef *module, HKEY key)
-/*[clinic end generated code: output=e3f23edb414f24a4 input=7748abbacd1e166a]*/
+winreg_EnableReflectionKey_impl(PyObject *module, HKEY key)
+/*[clinic end generated code: output=86fa1385fdd9ce57 input=7748abbacd1e166a]*/
 {
     HMODULE hMod;
     typedef LONG (WINAPI *RERKFunc)(HKEY);
@@ -1756,8 +1756,8 @@ Will generally raise NotImplemented if executed on a 32bit OS.
 [clinic start generated code]*/
 
 static PyObject *
-winreg_QueryReflectionKey_impl(PyModuleDef *module, HKEY key)
-/*[clinic end generated code: output=2a49c564ca162e50 input=9f325eacb5a65d88]*/
+winreg_QueryReflectionKey_impl(PyObject *module, HKEY key)
+/*[clinic end generated code: output=4e774af288c3ebb9 input=9f325eacb5a65d88]*/
 {
     HMODULE hMod;
     typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *);
index 8e77d13..6b79d23 100644 (file)
@@ -74,8 +74,8 @@ A wrapper around the Windows PlaySound API.
 [clinic start generated code]*/
 
 static PyObject *
-winsound_PlaySound_impl(PyModuleDef *module, Py_UNICODE *sound, int flags)
-/*[clinic end generated code: output=614273784bf59e5c input=3411b1b7c1f36d93]*/
+winsound_PlaySound_impl(PyObject *module, Py_UNICODE *sound, int flags)
+/*[clinic end generated code: output=ec24b3a2b4368378 input=3411b1b7c1f36d93]*/
 {
     int ok;
 
@@ -111,8 +111,8 @@ A wrapper around the Windows Beep API.
 [clinic start generated code]*/
 
 static PyObject *
-winsound_Beep_impl(PyModuleDef *module, int frequency, int duration)
-/*[clinic end generated code: output=c75f282035a872bd input=628a99d2ddf73798]*/
+winsound_Beep_impl(PyObject *module, int frequency, int duration)
+/*[clinic end generated code: output=f32382e52ee9b2fb input=628a99d2ddf73798]*/
 {
     BOOL ok;
 
@@ -145,8 +145,8 @@ x defaults to MB_OK.
 [clinic start generated code]*/
 
 static PyObject *
-winsound_MessageBeep_impl(PyModuleDef *module, int x)
-/*[clinic end generated code: output=92aa6a822bdc66ad input=a776c8a85c9853f6]*/
+winsound_MessageBeep_impl(PyObject *module, int x)
+/*[clinic end generated code: output=1ad89e4d8d30a957 input=a776c8a85c9853f6]*/
 {
     MessageBeep(x);
     Py_RETURN_NONE;
index 88b1f06..9e63a84 100644 (file)
@@ -105,6 +105,10 @@ if "%platf%"=="x64" (
     )\r
 )\r
 \r
+if not exist "%HG%" where hg > "%TEMP%\hg.loc" 2> nul && set /P HG= < "%TEMP%\hg.loc" & del "%TEMP%\hg.loc"\r
+if exist "%HG%" set HGProperty=/p:HG="%HG%"\r
+if not exist "%HG%" echo Cannot find Mercurial on PATH & set HGProperty=\r
+\r
 rem Setup the environment\r
 call "%dir%env.bat" %vs_platf% >nul\r
 \r
@@ -141,7 +145,7 @@ msbuild "%dir%pcbuild.proj" /t:%target% %parallel% %verbose%^
  /p:Configuration=%conf% /p:Platform=%platf%^\r
  /p:IncludeExternals=%IncludeExternals%^\r
  /p:IncludeSSL=%IncludeSSL% /p:IncludeTkinter=%IncludeTkinter%^\r
- /p:UseTestMarker=%UseTestMarker%^\r
+ /p:UseTestMarker=%UseTestMarker% %HGProperty%^\r
  %1 %2 %3 %4 %5 %6 %7 %8 %9\r
 \r
 @echo off\r
index 9b2a084..1c3cdee 100644 (file)
@@ -54,7 +54,7 @@ echo.Fetching external libraries...
 set libraries=\r
 set libraries=%libraries%                                    bzip2-1.0.6\r
 if NOT "%IncludeSSL%"=="false" set libraries=%libraries%     nasm-2.11.06\r
-if NOT "%IncludeSSL%"=="false" set libraries=%libraries%     openssl-1.0.2h\r
+if NOT "%IncludeSSL%"=="false" set libraries=%libraries%     openssl-1.0.2j\r
 set libraries=%libraries%                                    sqlite-3.8.11.0\r
 if NOT "%IncludeTkinter%"=="false" set libraries=%libraries% tcl-core-8.6.4.2\r
 if NOT "%IncludeTkinter%"=="false" set libraries=%libraries% tk-8.6.4.2\r
index 36621c9..c320434 100644 (file)
       <CleanAllTarget>CleanAll</CleanAllTarget>
       <BuildInParallel>true</BuildInParallel>
     </Projects>
+    <Projects2>
+      <Platform>$(Platform)</Platform>
+      <Configuration>$(Configuration)</Configuration>
+      <Properties></Properties>
+      <BuildTarget>Build</BuildTarget>
+      <CleanTarget>Clean</CleanTarget>
+      <CleanAllTarget>CleanAll</CleanAllTarget>
+      <BuildInParallel>true</BuildInParallel>
+    </Projects2>
   </ItemDefinitionGroup>
   <ItemGroup>
     <!-- pythonXY.dll -->
     <Projects Include="pythoncore.vcxproj">
       <BuildInParallel>false</BuildInParallel>
     </Projects>
-    <!-- python[w].exe -->
-    <Projects Include="python.vcxproj;pythonw.vcxproj" />
     <!-- python3.dll -->
     <Projects Include="python3dll.vcxproj" />
     <!-- py[w].exe -->
     <Projects Include="pylauncher.vcxproj;pywlauncher.vcxproj" />
+    <!-- pyshellext.dll -->
+    <Projects Include="pyshellext.vcxproj" />
     <!-- _freeze_importlib -->
     <Projects Include="_freeze_importlib.vcxproj" />
     <!-- Extension modules -->
       <!-- Disable parallel build for test modules -->
       <BuildInParallel>false</BuildInParallel>
     </Projects>
+    
+    <!-- python[w].exe -->
+    <Projects2 Include="python.vcxproj;pythonw.vcxproj">
+      <BuildInParallel>false</BuildInParallel>
+    </Projects2>
   </ItemGroup>
 
   <Target Name="Build">
     <MSBuild Projects="@(Projects)"
              Properties="Configuration=%(Configuration);Platform=%(Platform);%(Properties)"
              BuildInParallel="%(BuildInParallel)"
+             StopOnFirstFailure="true"
+             Targets="%(BuildTarget)" />
+    <MSBuild Projects="@(Projects2)"
+             Properties="Configuration=%(Configuration);Platform=%(Platform);%(Properties)"
+             BuildInParallel="%(BuildInParallel)"
+             StopOnFirstFailure="true"
              Targets="%(BuildTarget)" />
   </Target>
 
   <Target Name="Clean">
+    <MSBuild Projects="@(Projects2)"
+             Properties="Configuration=%(Configuration);Platform=%(Platform);%(Properties)"
+             BuildInParallel="%(BuildInParallel)"
+             StopOnFirstFailure="false"
+             Condition="%(CleanTarget) != ''"
+             Targets="%(CleanTarget)" />
     <MSBuild Projects="@(Projects)"
              Properties="Configuration=%(Configuration);Platform=%(Platform);%(Properties)"
              BuildInParallel="%(BuildInParallel)"
   </Target>
 
   <Target Name="CleanAll">
+    <MSBuild Projects="@(Projects2)"
+             Properties="Configuration=%(Configuration);Platform=%(Platform);%(Properties)"
+             BuildInParallel="%(BuildInParallel)"
+             StopOnFirstFailure="false"
+             Condition="%(CleanAllTarget) != ''"
+             Targets="%(CleanAllTarget)" />
     <MSBuild Projects="@(Projects)"
              Properties="Configuration=%(Configuration);Platform=%(Platform);%(Properties)"
              BuildInParallel="%(BuildInParallel)"
index 766a870..42a4d2b 100644 (file)
@@ -1,6 +1,6 @@
 Microsoft Visual Studio Solution File, Format Version 12.00\r
 # Visual Studio 14\r
-VisualStudioVersion = 14.0.22823.1\r
+VisualStudioVersion = 14.0.25123.0\r
 MinimumVisualStudioVersion = 10.0.40219.1\r
 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{553EC33E-9816-4996-A660-5D6186A0B0B3}"\r
        ProjectSection(SolutionItems) = preProject\r
@@ -63,8 +63,14 @@ EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_testbuffer", "_testbuffer.vcxproj", "{A2697BD3-28C1-4AEC-9106-8B748639FD16}"\r
 EndProject\r
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pylauncher", "pylauncher.vcxproj", "{7B2727B5-5A3F-40EE-A866-43A13CD31446}"\r
+       ProjectSection(ProjectDependencies) = postProject\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782} = {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}\r
+       EndProjectSection\r
 EndProject\r
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pywlauncher", "pywlauncher.vcxproj", "{1D4B18D3-7C12-4ECB-9179-8531FF876CE6}"\r
+       ProjectSection(ProjectDependencies) = postProject\r
+               {7B2727B5-5A3F-40EE-A866-43A13CD31446} = {7B2727B5-5A3F-40EE-A866-43A13CD31446}\r
+       EndProjectSection\r
 EndProject\r
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_freeze_importlib", "_freeze_importlib.vcxproj", "{19C0C13F-47CA-4432-AFF3-799A296A4DDC}"\r
 EndProject\r
@@ -84,6 +90,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libeay", "libeay.vcxproj",
 EndProject\r
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ssleay", "ssleay.vcxproj", "{10615B24-73BF-4EFA-93AA-236916321317}"\r
 EndProject\r
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pyshellext", "pyshellext.vcxproj", "{0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}"\r
+EndProject\r
 Global\r
        GlobalSection(SolutionConfigurationPlatforms) = preSolution\r
                Debug|Win32 = Debug|Win32\r
@@ -684,6 +692,22 @@ Global
                {10615B24-73BF-4EFA-93AA-236916321317}.Release|Win32.Build.0 = Release|Win32\r
                {10615B24-73BF-4EFA-93AA-236916321317}.Release|x64.ActiveCfg = Release|x64\r
                {10615B24-73BF-4EFA-93AA-236916321317}.Release|x64.Build.0 = Release|x64\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.Debug|Win32.ActiveCfg = Debug|Win32\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.Debug|Win32.Build.0 = Debug|Win32\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.Debug|x64.ActiveCfg = Debug|x64\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.Debug|x64.Build.0 = Debug|x64\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.PGInstrument|Win32.Build.0 = PGInstrument|Win32\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.PGInstrument|x64.ActiveCfg = PGInstrument|x64\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.PGInstrument|x64.Build.0 = PGInstrument|x64\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.PGUpdate|Win32.Build.0 = PGUpdate|Win32\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.PGUpdate|x64.ActiveCfg = PGUpdate|x64\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.PGUpdate|x64.Build.0 = PGUpdate|x64\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.Release|Win32.ActiveCfg = Release|Win32\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.Release|Win32.Build.0 = Release|Win32\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.Release|x64.ActiveCfg = Release|x64\r
+               {0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}.Release|x64.Build.0 = Release|x64\r
        EndGlobalSection\r
        GlobalSection(SolutionProperties) = preSolution\r
                HideSolutionNode = FALSE\r
index f6170f5..d746976 100644 (file)
@@ -18,6 +18,8 @@
 # it should configure OpenSSL such that it is ready to be built by
 # ssl.vcxproj on 32 or 64 bit platforms.
 
+from __future__ import print_function
+
 import os
 import re
 import sys
@@ -89,7 +91,10 @@ def create_asms(makefile, tmp_d):
 
 def copy_includes(makefile, suffix):
     dir = 'include'+suffix+'\\openssl'
-    os.makedirs(dir, exist_ok=True)
+    try:
+        os.makedirs(dir)
+    except OSError:
+        pass
     copy_if_different = r'$(PERL) $(SRC_D)\util\copy-if-different.pl'
     with open(makefile) as fin:
         for line in fin:
index c56292a..d1ac998 100644 (file)
@@ -4,10 +4,8 @@
     <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
     <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
     <OutDir>$(BuildPath)</OutDir>
-    <OutDir Condition="'$(Py_OutDir)' != ''">$(Py_OutDir)</OutDir>
     <OutDir Condition="!HasTrailingSlash($(OutDir))">$(OutDir)\</OutDir>
-    <Py_IntDir Condition="'$(Py_IntDir)' == ''">$(SolutionDir)obj\</Py_IntDir>
-    <IntDir Condition="!HasTrailingSlash($(IntDir))">$(IntDir)\</IntDir>
+    <Py_IntDir Condition="'$(Py_IntDir)' == ''">$(MSBuildThisFileDirectory)obj\</Py_IntDir>
     <IntDir>$(Py_IntDir)\$(ArchName)_$(Configuration)\$(ProjectName)\</IntDir>
     <IntDir Condition="$(Configuration) == 'PGInstrument' or $(Configuration) == 'PGUpdate'">$(Py_IntDir)\$(ArchName)_PGO\$(ProjectName)\</IntDir>
     <TargetName Condition="'$(TargetName)' == ''">$(ProjectName)</TargetName>
@@ -29,7 +27,7 @@
   </PropertyGroup>
   <ItemDefinitionGroup>
     <ClCompile>
-      <AdditionalIncludeDirectories>$(PySourcePath)Include;$(PySourcePath)PC;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+      <AdditionalIncludeDirectories>$(PySourcePath)Include;$(PySourcePath)PC;$(IntDir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
       <PreprocessorDefinitions>WIN32;$(_PlatformPreprocessorDefinition)$(_DebugPreprocessorDefinition)$(_PydPreprocessorDefinition)%(PreprocessorDefinitions)</PreprocessorDefinitions>
       
       <Optimization>MaxSpeed</Optimization>
@@ -85,9 +83,9 @@
       <SuppressStartupBanner>true</SuppressStartupBanner>
       <TargetEnvironment>Win32</TargetEnvironment>
       <TargetEnvironment Condition="'$(Platform)' == 'x64'">X64</TargetEnvironment>
-      <TypeLibraryName>$(OutDir)wininst.tlb</TypeLibraryName>
-      <HeaderFileName>
-      </HeaderFileName>
+      <OutputDirectory>$(IntDir)</OutputDirectory>
+      <InterfaceIdentifierFileName>$(MSBuildProjectName)_i.c</InterfaceIdentifierFileName>
+      <ProxyFileName>$(MSBuildProjectName)_p.c</ProxyFileName>
     </Midl>
   </ItemDefinitionGroup>
 
diff --git a/PCbuild/pyshellext.vcxproj b/PCbuild/pyshellext.vcxproj
new file mode 100644 (file)
index 0000000..0293935
--- /dev/null
@@ -0,0 +1,87 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Debug|x64">
+      <Configuration>Debug</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="PGInstrument|Win32">
+      <Configuration>PGInstrument</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="PGInstrument|x64">
+      <Configuration>PGInstrument</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="PGUpdate|Win32">
+      <Configuration>PGUpdate</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="PGUpdate|x64">
+      <Configuration>PGUpdate</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|x64">
+      <Configuration>Release</Configuration>
+      <Platform>x64</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{0F6EE4A4-C75F-4578-B4B3-2D64F4B9B782}</ProjectGuid>
+    <RootNamespace>pyshellext</RootNamespace>
+    <TargetName>pyshellext</TargetName>
+    <SupportPGO>false</SupportPGO>
+  </PropertyGroup>
+  <Import Project="python.props" />
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Label="Configuration">
+    <ConfigurationType>DynamicLibrary</ConfigurationType>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <PropertyGroup>
+    <MakeVersionInfoBeforeTarget>ClCompile</MakeVersionInfoBeforeTarget>
+  </PropertyGroup>
+  <ImportGroup Label="PropertySheets">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+    <Import Project="pyproject.props" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <ItemDefinitionGroup>
+    <ClCompile>
+      <PreprocessorDefinitions>_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <AdditionalDependencies>version.lib;shlwapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <SubSystem>Console</SubSystem>
+      <ModuleDefinitionFile>..\PC\pyshellext$(PyDebugExt).def</ModuleDefinitionFile>
+    </Link>
+    <Midl>
+      <CompileInterface>true</CompileInterface>
+    </Midl>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="..\PC\pyshellext.cpp" />
+    <Midl Include="..\PC\pyshellext.idl" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="..\PC\pyshellext.def" />
+    <None Include="..\PC\pyshellext_d.def" />
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="..\PC\pyshellext.rc" />
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>
\ No newline at end of file
diff --git a/PCbuild/pyshellext.vcxproj.filters b/PCbuild/pyshellext.vcxproj.filters
new file mode 100644 (file)
index 0000000..648e499
--- /dev/null
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup>
+    <Filter Include="Source Files">
+      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+    </Filter>
+    <Filter Include="Header Files">
+      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+    </Filter>
+    <Filter Include="Resource Files">
+      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+    </Filter>
+  </ItemGroup>
+  <ItemGroup>
+    <ClCompile Include="..\PC\pyshellext.cpp">
+      <Filter>Source Files</Filter>
+    </ClCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <Midl Include="..\PC\pyshellext.idl">
+      <Filter>Source Files</Filter>
+    </Midl>
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="..\PC\pyshellext.rc">
+      <Filter>Resource Files</Filter>
+    </ResourceCompile>
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="..\PC\pyshellext.def">
+      <Filter>Source Files</Filter>
+    </None>
+    <None Include="..\PC\pyshellext_d.def">
+      <Filter>Source Files</Filter>
+    </None>
+  </ItemGroup>
+</Project>
\ No newline at end of file
index 843771d..1553731 100644 (file)
     <PySourcePath Condition="!HasTrailingSlash($(PySourcePath))">$(PySourcePath)\</PySourcePath>
     
     <!-- Directory where build outputs are put -->
-    <BuildPath Condition="'$(PyBuildPath)' == ''">$(PySourcePath)PCBuild\$(ArchName)\</BuildPath>
-    <BuildPath Condition="'$(PyBuildPath)' != ''">$(PyBuildPath)</BuildPath>
+    <BuildPath32 Condition="'$(Py_OutDir)' == ''">$(PySourcePath)PCBuild\win32\</BuildPath32>
+    <BuildPath32 Condition="'$(Py_OutDir)' != ''">$(Py_OutDir)\win32\</BuildPath32>
+    <BuildPath64 Condition="'$(Py_OutDir)' == ''">$(PySourcePath)PCBuild\amd64\</BuildPath64>
+    <BuildPath64 Condition="'$(Py_OutDir)' != ''">$(Py_OutDir)\amd64\</BuildPath64>
+    <BuildPath Condition="'$(ArchName)' == 'win32'">$(BuildPath32)</BuildPath>
+    <BuildPath Condition="'$(ArchName)' == 'amd64'">$(BuildPath64)</BuildPath>
+    <BuildPath Condition="'$(BuildPath)' == ''">$(PySourcePath)PCBuild\$(ArchName)\</BuildPath>
     <BuildPath Condition="!HasTrailingSlash($(BuildPath))">$(BuildPath)\</BuildPath>
     
     <!-- Directories of external projects. tcltk is handled in tcltk.props -->
@@ -41,7 +46,7 @@
     <sqlite3Dir>$(ExternalsDir)sqlite-3.8.11.0\</sqlite3Dir>
     <bz2Dir>$(ExternalsDir)bzip2-1.0.6\</bz2Dir>
     <lzmaDir>$(ExternalsDir)xz-5.0.5\</lzmaDir>
-    <opensslDir>$(ExternalsDir)openssl-1.0.2h\</opensslDir>
+    <opensslDir>$(ExternalsDir)openssl-1.0.2j\</opensslDir>
     <opensslIncludeDir>$(opensslDir)include32</opensslIncludeDir>
     <opensslIncludeDir Condition="'$(ArchName)' == 'amd64'">$(opensslDir)include64</opensslIncludeDir>
     <nasmDir>$(ExternalsDir)\nasm-2.11.06\</nasmDir>
index 60116df..807213f 100644 (file)
@@ -88,7 +88,9 @@
       <UcrtName>ucrtbase</UcrtName>
       <UcrtName Condition="'$(Configuration)' == 'Debug'">ucrtbased</UcrtName>
     </PropertyGroup>
-    <Exec Command='"$(OutDir)python$(PyDebugExt).exe" "$(PySourcePath)PC\validate_ucrtbase.py" $(UcrtName)' ContinueOnError="true" />
+    <Exec Command='setlocal
+set PYTHONPATH=$(PySourcePath)Lib
+"$(OutDir)python$(PyDebugExt).exe" "$(PySourcePath)PC\validate_ucrtbase.py" $(UcrtName)' ContinueOnError="true" />
   </Target>
   <Target Name="GeneratePythonBat" AfterTargets="AfterBuild">
     <PropertyGroup>
 @rem This is only meant as a convenience for developing CPython
 @rem and using it outside of that context is ill-advised.
 @echo Running $(Configuration)^|$(Platform) interpreter...
+@setlocal
+@set PYTHONHOME=$(PySourcePath)
 @"$(OutDir)python$(PyDebugExt).exe" %*
 </_Content>
       <_ExistingContent Condition="Exists('$(PySourcePath)python.bat')">$([System.IO.File]::ReadAllText('$(PySourcePath)python.bat'))</_ExistingContent>
index cbb618f..c66c8ef 100644 (file)
@@ -58,6 +58,7 @@
     <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
     <_Machine>X86</_Machine>
     <_Machine Condition="$(Platform) == 'x64'">X64</_Machine>
+    <ExtensionsToDeleteOnClean>$(ExtensionsToDeleteOnClean);$(IntDir)python3_d.def;$(IntDir)python3stub.def</ExtensionsToDeleteOnClean>
   </PropertyGroup>
   <ItemDefinitionGroup>
     <ClCompile>
     <MakeDir Directories="$(IntDir)" />
     <WriteLinesToFile File="$(IntDir)python3stub.def" Lines="@(_Lines)" Overwrite="true" />
   </Target>
-  <Target Name="_CleanStubDef" BeforeTargets="CoreClean">
-    <ItemGroup>
-      <Clean Include="$(IntDir)python3stub.def" />
-    </ItemGroup>
-  </Target>
 </Project>
\ No newline at end of file
index 3a1b5ba..970344f 100644 (file)
@@ -69,7 +69,7 @@
       <PreprocessorDefinitions>_USRDLL;Py_BUILD_CORE;Py_ENABLE_SHARED;MS_DLL_ID="$(SysWinVer)";%(PreprocessorDefinitions)</PreprocessorDefinitions>
     </ClCompile>
     <Link>
-      <AdditionalDependencies>ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+      <AdditionalDependencies>version.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
       <BaseAddress>0x1e000000</BaseAddress>
     </Link>
   </ItemDefinitionGroup>
   <ImportGroup Label="ExtensionTargets">
   </ImportGroup>
   <Target Name="_GetBuildInfo" BeforeTargets="PrepareForBuild">
-    <Exec Command="hg id -b &gt; &quot;$(IntDir)hgbranch.txt&quot;" ContinueOnError="true" />
-    <Exec Command="hg id -i &gt; &quot;$(IntDir)hgversion.txt&quot;" ContinueOnError="true" />
-    <Exec Command="hg id -t &gt; &quot;$(IntDir)hgtag.txt&quot;" ContinueOnError="true" />
+    <PropertyGroup>
+      <HG Condition="$(HG) == ''">hg</HG>
+      <_HG>$(HG)</_HG>
+      <_HG Condition="$(HG.Contains(` `))">"$(HG)"</_HG>
+    </PropertyGroup>
+    <Message Text="Getting build info from $(_HG)" Importance="high" />
+    <MakeDir Directories="$(IntDir)" Condition="!Exists($(IntDir))" />
+    <Exec Command="$(_HG) id -b &gt; &quot;$(IntDir)hgbranch.txt&quot;" ContinueOnError="true" />
+    <Exec Command="$(_HG) id -i &gt; &quot;$(IntDir)hgversion.txt&quot;" ContinueOnError="true" />
+    <Exec Command="$(_HG) id -t &gt; &quot;$(IntDir)hgtag.txt&quot;" ContinueOnError="true" />
     <PropertyGroup>
       <HgBranch Condition="Exists('$(IntDir)hgbranch.txt')">$([System.IO.File]::ReadAllText('$(IntDir)hgbranch.txt').Trim())</HgBranch>
       <HgVersion Condition="Exists('$(IntDir)hgversion.txt')">$([System.IO.File]::ReadAllText('$(IntDir)hgversion.txt').Trim())</HgVersion>
index d45eb27..2462012 100644 (file)
@@ -169,7 +169,7 @@ _lzma
     Homepage:\r
         http://tukaani.org/xz/\r
 _ssl\r
-    Python wrapper for version 1.0.2h of the OpenSSL secure sockets\r
+    Python wrapper for version 1.0.2j of the OpenSSL secure sockets\r
     library, which is built by ssl.vcxproj\r
     Homepage:\r
         http://www.openssl.org/\r
index 464c83c..3dfd155 100644 (file)
@@ -88,4 +88,6 @@ nmake -f makefile.vc MACHINE=$(TclMachine) OPTS=$(TclOpts) $(TclDirs) $(DebugFla
     <Delete Files="$(TargetPath);$(BuildPath)$(tclDLLName)" />
     <RemoveDir Directories="$(IntDir)" />
   </Target>
+  
+  <Target Name="ResolveAssemblyReferences" />
 </Project>
\ No newline at end of file
index f857f9e..d1bc0ab 100644 (file)
@@ -89,4 +89,6 @@ nmake /nologo -f makefile.vc MACHINE=$(TclMachine) $(DebugFlags) $(TclShortVersi
     <RemoveDir Directories="$(OutDir)" />
     <RemoveDir Directories="$(IntDir)" />
   </Target>
+  
+  <Target Name="ResolveAssemblyReferences" />
 </Project>
\ No newline at end of file
index 20749f7..a26318b 100644 (file)
@@ -92,4 +92,6 @@ nmake /nologo -f makefile.vc RC=rc MACHINE=$(TclMachine) OPTS=$(TkOpts) $(TkDirs
     <Delete Files="$(TargetPath);$(BuildPath)$(tkDLLName)" />
     <RemoveDir Directories="$(IntDir)" />
   </Target>
+  
+  <Target Name="ResolveAssemblyReferences" />
 </Project>
\ No newline at end of file
index f38c253..ac9d2b6 100755 (executable)
@@ -526,6 +526,13 @@ class Obj2ModVisitor(PickleVisitor):
             self.emit("res = obj2ast_%s(PyList_GET_ITEM(tmp, i), &value, arena);" %
                       field.type, depth+2, reflow=False)
             self.emit("if (res != 0) goto failed;", depth+2)
+            self.emit("if (len != PyList_GET_SIZE(tmp)) {", depth+2)
+            self.emit("PyErr_SetString(PyExc_RuntimeError, \"%s field \\\"%s\\\" "
+                      "changed size during iteration\");" %
+                      (name, field.name),
+                      depth+3, reflow=False)
+            self.emit("goto failed;", depth+3)
+            self.emit("}", depth+2)
             self.emit("asdl_seq_SET(%s, i, value);" % field.name, depth+2)
             self.emit("}", depth+1)
         else:
index 184ffe7..612cb23 100644 (file)
@@ -497,16 +497,12 @@ error:
 static int
 fp_setreadl(struct tok_state *tok, const char* enc)
 {
-    PyObject *readline = NULL, *stream = NULL, *io = NULL;
+    PyObject *readline, *io, *stream;
     _Py_IDENTIFIER(open);
     _Py_IDENTIFIER(readline);
     int fd;
     long pos;
 
-    io = PyImport_ImportModuleNoBlock("io");
-    if (io == NULL)
-        goto cleanup;
-
     fd = fileno(tok->fp);
     /* Due to buffering the file offset for fd can be different from the file
      * position of tok->fp.  If tok->fp was opened in text mode on Windows,
@@ -517,27 +513,33 @@ fp_setreadl(struct tok_state *tok, const char* enc)
     if (pos == -1 ||
         lseek(fd, (off_t)(pos > 0 ? pos - 1 : pos), SEEK_SET) == (off_t)-1) {
         PyErr_SetFromErrnoWithFilename(PyExc_OSError, NULL);
-        goto cleanup;
+        return 0;
     }
 
+    io = PyImport_ImportModuleNoBlock("io");
+    if (io == NULL)
+        return 0;
+
     stream = _PyObject_CallMethodId(io, &PyId_open, "isisOOO",
                     fd, "r", -1, enc, Py_None, Py_None, Py_False);
+    Py_DECREF(io);
     if (stream == NULL)
-        goto cleanup;
+        return 0;
 
     readline = _PyObject_GetAttrId(stream, &PyId_readline);
+    Py_DECREF(stream);
+    if (readline == NULL)
+        return 0;
     Py_XSETREF(tok->decoding_readline, readline);
+
     if (pos > 0) {
-        if (PyObject_CallObject(readline, NULL) == NULL) {
-            readline = NULL;
-            goto cleanup;
-        }
+        PyObject *bufobj = PyObject_CallObject(readline, NULL);
+        if (bufobj == NULL)
+            return 0;
+        Py_DECREF(bufobj);
     }
 
-  cleanup:
-    Py_XDECREF(stream);
-    Py_XDECREF(io);
-    return readline != NULL;
+    return 1;
 }
 
 /* Fetch the next byte from TOK. */
@@ -1023,7 +1025,7 @@ tok_nextc(struct tok_state *tok)
                 else {
                     tok->done = E_OK;
                     tok->inp = strchr(tok->buf, '\0');
-                    done = tok->inp[-1] == '\n';
+                    done = tok->inp == tok->buf || tok->inp[-1] == '\n';
                 }
             }
             else {
index aecb123..0793984 100644 (file)
@@ -77,6 +77,7 @@ main(int argc, char *argv[])
     Py_NoUserSiteDirectory++;
     Py_NoSiteFlag++;
     Py_IgnoreEnvironmentFlag++;
+    Py_FrozenFlag++;
 
     Py_SetProgramName(L"./_freeze_importlib");
     /* Don't install importlib, since it could execute outdated bytecode. */
index edfcbad..ad53ba3 100644 (file)
@@ -3797,6 +3797,10 @@ obj2ast_mod(PyObject* obj, mod_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Module field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -3832,6 +3836,10 @@ obj2ast_mod(PyObject* obj, mod_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Interactive field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -3889,6 +3897,10 @@ obj2ast_mod(PyObject* obj, mod_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Suite field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -3992,6 +4004,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "FunctionDef field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4016,6 +4032,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "FunctionDef field \"decorator_list\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(decorator_list, i, value);
             }
             Py_CLEAR(tmp);
@@ -4088,6 +4108,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "AsyncFunctionDef field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4112,6 +4136,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "AsyncFunctionDef field \"decorator_list\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(decorator_list, i, value);
             }
             Py_CLEAR(tmp);
@@ -4173,6 +4201,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"bases\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(bases, i, value);
             }
             Py_CLEAR(tmp);
@@ -4197,6 +4229,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 keyword_ty value;
                 res = obj2ast_keyword(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"keywords\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(keywords, i, value);
             }
             Py_CLEAR(tmp);
@@ -4221,6 +4257,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4245,6 +4285,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "ClassDef field \"decorator_list\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(decorator_list, i, value);
             }
             Py_CLEAR(tmp);
@@ -4302,6 +4346,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Delete field \"targets\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(targets, i, value);
             }
             Py_CLEAR(tmp);
@@ -4338,6 +4386,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Assign field \"targets\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(targets, i, value);
             }
             Py_CLEAR(tmp);
@@ -4455,6 +4507,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "For field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4479,6 +4535,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "For field \"orelse\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(orelse, i, value);
             }
             Py_CLEAR(tmp);
@@ -4539,6 +4599,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "AsyncFor field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4563,6 +4627,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "AsyncFor field \"orelse\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(orelse, i, value);
             }
             Py_CLEAR(tmp);
@@ -4611,6 +4679,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "While field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4635,6 +4707,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "While field \"orelse\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(orelse, i, value);
             }
             Py_CLEAR(tmp);
@@ -4683,6 +4759,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "If field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4707,6 +4787,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "If field \"orelse\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(orelse, i, value);
             }
             Py_CLEAR(tmp);
@@ -4743,6 +4827,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 withitem_ty value;
                 res = obj2ast_withitem(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "With field \"items\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(items, i, value);
             }
             Py_CLEAR(tmp);
@@ -4767,6 +4855,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "With field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4803,6 +4895,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 withitem_ty value;
                 res = obj2ast_withitem(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "AsyncWith field \"items\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(items, i, value);
             }
             Py_CLEAR(tmp);
@@ -4827,6 +4923,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "AsyncWith field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4897,6 +4997,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Try field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -4921,6 +5025,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 excepthandler_ty value;
                 res = obj2ast_excepthandler(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Try field \"handlers\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(handlers, i, value);
             }
             Py_CLEAR(tmp);
@@ -4945,6 +5053,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Try field \"orelse\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(orelse, i, value);
             }
             Py_CLEAR(tmp);
@@ -4969,6 +5081,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Try field \"finalbody\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(finalbody, i, value);
             }
             Py_CLEAR(tmp);
@@ -5038,6 +5154,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 alias_ty value;
                 res = obj2ast_alias(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Import field \"names\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(names, i, value);
             }
             Py_CLEAR(tmp);
@@ -5085,6 +5205,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 alias_ty value;
                 res = obj2ast_alias(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "ImportFrom field \"names\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(names, i, value);
             }
             Py_CLEAR(tmp);
@@ -5130,6 +5254,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 identifier value;
                 res = obj2ast_identifier(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Global field \"names\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(names, i, value);
             }
             Py_CLEAR(tmp);
@@ -5165,6 +5293,10 @@ obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
                 identifier value;
                 res = obj2ast_identifier(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Nonlocal field \"names\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(names, i, value);
             }
             Py_CLEAR(tmp);
@@ -5306,6 +5438,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "BoolOp field \"values\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(values, i, value);
             }
             Py_CLEAR(tmp);
@@ -5502,6 +5638,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Dict field \"keys\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(keys, i, value);
             }
             Py_CLEAR(tmp);
@@ -5526,6 +5666,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Dict field \"values\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(values, i, value);
             }
             Py_CLEAR(tmp);
@@ -5561,6 +5705,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Set field \"elts\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(elts, i, value);
             }
             Py_CLEAR(tmp);
@@ -5608,6 +5756,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 comprehension_ty value;
                 res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "ListComp field \"generators\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(generators, i, value);
             }
             Py_CLEAR(tmp);
@@ -5655,6 +5807,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 comprehension_ty value;
                 res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "SetComp field \"generators\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(generators, i, value);
             }
             Py_CLEAR(tmp);
@@ -5714,6 +5870,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 comprehension_ty value;
                 res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "DictComp field \"generators\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(generators, i, value);
             }
             Py_CLEAR(tmp);
@@ -5761,6 +5921,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 comprehension_ty value;
                 res = obj2ast_comprehension(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "GeneratorExp field \"generators\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(generators, i, value);
             }
             Py_CLEAR(tmp);
@@ -5874,6 +6038,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 cmpop_ty value;
                 res = obj2ast_cmpop(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Compare field \"ops\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(ops, i, value);
             }
             Py_CLEAR(tmp);
@@ -5898,6 +6066,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Compare field \"comparators\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(comparators, i, value);
             }
             Py_CLEAR(tmp);
@@ -5946,6 +6118,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Call field \"args\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(args, i, value);
             }
             Py_CLEAR(tmp);
@@ -5970,6 +6146,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 keyword_ty value;
                 res = obj2ast_keyword(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Call field \"keywords\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(keywords, i, value);
             }
             Py_CLEAR(tmp);
@@ -6264,6 +6444,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "List field \"elts\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(elts, i, value);
             }
             Py_CLEAR(tmp);
@@ -6311,6 +6495,10 @@ obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
                 expr_ty value;
                 res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "Tuple field \"elts\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(elts, i, value);
             }
             Py_CLEAR(tmp);
@@ -6476,6 +6664,10 @@ obj2ast_slice(PyObject* obj, slice_ty* out, PyArena* arena)
                 slice_ty value;
                 res = obj2ast_slice(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "ExtSlice field \"dims\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(dims, i, value);
             }
             Py_CLEAR(tmp);
@@ -6835,6 +7027,10 @@ obj2ast_comprehension(PyObject* obj, comprehension_ty* out, PyArena* arena)
             expr_ty value;
             res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
             if (res != 0) goto failed;
+            if (len != PyList_GET_SIZE(tmp)) {
+                PyErr_SetString(PyExc_RuntimeError, "comprehension field \"ifs\" changed size during iteration");
+                goto failed;
+            }
             asdl_seq_SET(ifs, i, value);
         }
         Py_CLEAR(tmp);
@@ -6930,6 +7126,10 @@ obj2ast_excepthandler(PyObject* obj, excepthandler_ty* out, PyArena* arena)
                 stmt_ty value;
                 res = obj2ast_stmt(PyList_GET_ITEM(tmp, i), &value, arena);
                 if (res != 0) goto failed;
+                if (len != PyList_GET_SIZE(tmp)) {
+                    PyErr_SetString(PyExc_RuntimeError, "ExceptHandler field \"body\" changed size during iteration");
+                    goto failed;
+                }
                 asdl_seq_SET(body, i, value);
             }
             Py_CLEAR(tmp);
@@ -6976,6 +7176,10 @@ obj2ast_arguments(PyObject* obj, arguments_ty* out, PyArena* arena)
             arg_ty value;
             res = obj2ast_arg(PyList_GET_ITEM(tmp, i), &value, arena);
             if (res != 0) goto failed;
+            if (len != PyList_GET_SIZE(tmp)) {
+                PyErr_SetString(PyExc_RuntimeError, "arguments field \"args\" changed size during iteration");
+                goto failed;
+            }
             asdl_seq_SET(args, i, value);
         }
         Py_CLEAR(tmp);
@@ -7010,6 +7214,10 @@ obj2ast_arguments(PyObject* obj, arguments_ty* out, PyArena* arena)
             arg_ty value;
             res = obj2ast_arg(PyList_GET_ITEM(tmp, i), &value, arena);
             if (res != 0) goto failed;
+            if (len != PyList_GET_SIZE(tmp)) {
+                PyErr_SetString(PyExc_RuntimeError, "arguments field \"kwonlyargs\" changed size during iteration");
+                goto failed;
+            }
             asdl_seq_SET(kwonlyargs, i, value);
         }
         Py_CLEAR(tmp);
@@ -7034,6 +7242,10 @@ obj2ast_arguments(PyObject* obj, arguments_ty* out, PyArena* arena)
             expr_ty value;
             res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
             if (res != 0) goto failed;
+            if (len != PyList_GET_SIZE(tmp)) {
+                PyErr_SetString(PyExc_RuntimeError, "arguments field \"kw_defaults\" changed size during iteration");
+                goto failed;
+            }
             asdl_seq_SET(kw_defaults, i, value);
         }
         Py_CLEAR(tmp);
@@ -7068,6 +7280,10 @@ obj2ast_arguments(PyObject* obj, arguments_ty* out, PyArena* arena)
             expr_ty value;
             res = obj2ast_expr(PyList_GET_ITEM(tmp, i), &value, arena);
             if (res != 0) goto failed;
+            if (len != PyList_GET_SIZE(tmp)) {
+                PyErr_SetString(PyExc_RuntimeError, "arguments field \"defaults\" changed size during iteration");
+                goto failed;
+            }
             asdl_seq_SET(defaults, i, value);
         }
         Py_CLEAR(tmp);
index 978bad1..3928153 100644 (file)
@@ -431,7 +431,7 @@ warn_explicit(PyObject *category, PyObject *message,
     if (action == NULL)
         goto cleanup;
 
-    if (PyUnicode_CompareWithASCIIString(action, "error") == 0) {
+    if (_PyUnicode_EqualToASCIIString(action, "error")) {
         PyErr_SetObject(category, message);
         goto cleanup;
     }
@@ -439,13 +439,13 @@ warn_explicit(PyObject *category, PyObject *message,
     /* Store in the registry that we've been here, *except* when the action
        is "always". */
     rc = 0;
-    if (PyUnicode_CompareWithASCIIString(action, "always") != 0) {
+    if (!_PyUnicode_EqualToASCIIString(action, "always")) {
         if (registry != NULL && registry != Py_None &&
                 PyDict_SetItem(registry, key, Py_True) < 0)
             goto cleanup;
-        else if (PyUnicode_CompareWithASCIIString(action, "ignore") == 0)
+        else if (_PyUnicode_EqualToASCIIString(action, "ignore"))
             goto return_none;
-        else if (PyUnicode_CompareWithASCIIString(action, "once") == 0) {
+        else if (_PyUnicode_EqualToASCIIString(action, "once")) {
             if (registry == NULL || registry == Py_None) {
                 registry = get_once_registry();
                 if (registry == NULL)
@@ -454,12 +454,12 @@ warn_explicit(PyObject *category, PyObject *message,
             /* _once_registry[(text, category)] = 1 */
             rc = update_registry(registry, text, category, 0);
         }
-        else if (PyUnicode_CompareWithASCIIString(action, "module") == 0) {
+        else if (_PyUnicode_EqualToASCIIString(action, "module")) {
             /* registry[(text, category, 0)] = 1 */
             if (registry != NULL && registry != Py_None)
                 rc = update_registry(registry, text, category, 0);
         }
-        else if (PyUnicode_CompareWithASCIIString(action, "default") != 0) {
+        else if (!_PyUnicode_EqualToASCIIString(action, "default")) {
             PyErr_Format(PyExc_RuntimeError,
                         "Unrecognized action (%R) in warnings.filters:\n %R",
                         action, item);
@@ -665,7 +665,7 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
     }
     else {
         *filename = NULL;
-        if (*module != Py_None && PyUnicode_CompareWithASCIIString(*module, "__main__") == 0) {
+        if (*module != Py_None && _PyUnicode_EqualToASCIIString(*module, "__main__")) {
             PyObject *argv = _PySys_GetObjectId(&PyId_argv);
             /* PyList_Check() is needed because sys.argv is set to None during
                Python finalization */
index 7743c31..d36a9b7 100644 (file)
@@ -876,14 +876,14 @@ forbidden_name(struct compiling *c, identifier name, const node *n,
                int full_checks)
 {
     assert(PyUnicode_Check(name));
-    if (PyUnicode_CompareWithASCIIString(name, "__debug__") == 0) {
+    if (_PyUnicode_EqualToASCIIString(name, "__debug__")) {
         ast_error(c, n, "assignment to keyword");
         return 1;
     }
     if (full_checks) {
         const char **p;
         for (p = FORBIDDEN; *p; p++) {
-            if (PyUnicode_CompareWithASCIIString(name, *p) == 0) {
+            if (_PyUnicode_EqualToASCIIString(name, *p)) {
                 ast_error(c, n, "assignment to keyword");
                 return 1;
             }
@@ -2024,16 +2024,18 @@ ast_for_atom(struct compiling *c, const node *n)
                 errtype = "value error";
             if (errtype) {
                 char buf[128];
+                const char *s = NULL;
                 PyObject *type, *value, *tback, *errstr;
                 PyErr_Fetch(&type, &value, &tback);
                 errstr = PyObject_Str(value);
-                if (errstr) {
-                    char *s = _PyUnicode_AsString(errstr);
+                if (errstr)
+                    s = PyUnicode_AsUTF8(errstr);
+                if (s) {
                     PyOS_snprintf(buf, sizeof(buf), "(%s) %s", errtype, s);
-                    Py_DECREF(errstr);
                 } else {
                     PyOS_snprintf(buf, sizeof(buf), "(%s) unknown error", errtype);
                 }
+                Py_XDECREF(errstr);
                 ast_error(c, n, buf);
                 Py_DECREF(type);
                 Py_XDECREF(value);
@@ -2810,7 +2812,7 @@ ast_for_expr_stmt(struct compiling *c, const node *n)
        testlist_star_expr: (test|star_expr) (',' test|star_expr)* [',']
        augassign: '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^='
                 | '<<=' | '>>=' | '**=' | '//='
-       test: ... here starts the operator precendence dance
+       test: ... here starts the operator precedence dance
      */
 
     if (NCH(n) == 1) {
index f3d0c9a..9f5db2a 100644 (file)
@@ -242,8 +242,8 @@ Return the absolute value of the argument.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_abs(PyModuleDef *module, PyObject *x)
-/*[clinic end generated code: output=6833047c493ecea2 input=bed4ca14e29c20d1]*/
+builtin_abs(PyObject *module, PyObject *x)
+/*[clinic end generated code: output=b1b433b9e51356f5 input=bed4ca14e29c20d1]*/
 {
     return PyNumber_Absolute(x);
 }
@@ -260,8 +260,8 @@ If the iterable is empty, return True.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_all(PyModuleDef *module, PyObject *iterable)
-/*[clinic end generated code: output=089e6d1b7bde27b1 input=1a7c5d1bc3438a21]*/
+builtin_all(PyObject *module, PyObject *iterable)
+/*[clinic end generated code: output=ca2a7127276f79b3 input=1a7c5d1bc3438a21]*/
 {
     PyObject *it, *item;
     PyObject *(*iternext)(PyObject *);
@@ -309,8 +309,8 @@ If the iterable is empty, return False.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_any(PyModuleDef *module, PyObject *iterable)
-/*[clinic end generated code: output=1be994b2c2307492 input=41d7451c23384f24]*/
+builtin_any(PyObject *module, PyObject *iterable)
+/*[clinic end generated code: output=fa65684748caa60e input=41d7451c23384f24]*/
 {
     PyObject *it, *item;
     PyObject *(*iternext)(PyObject *);
@@ -361,8 +361,8 @@ to that returned by repr() in Python 2.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_ascii(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=d4e862c48af2a933 input=4c62732e1b3a3cc9]*/
+builtin_ascii(PyObject *module, PyObject *obj)
+/*[clinic end generated code: output=6d37b3f0984c7eb9 input=4c62732e1b3a3cc9]*/
 {
     return PyObject_ASCII(obj);
 }
@@ -381,8 +381,8 @@ Return the binary representation of an integer.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_bin(PyModuleDef *module, PyObject *number)
-/*[clinic end generated code: output=25ee26c6cf3bbb54 input=53f8a0264bacaf90]*/
+builtin_bin(PyObject *module, PyObject *number)
+/*[clinic end generated code: output=b6fc4ad5e649f4f7 input=53f8a0264bacaf90]*/
 {
     return PyNumber_ToBase(number, 2);
 }
@@ -401,8 +401,8 @@ __call__() method.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_callable(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=f4df2ce92364b656 input=1423bab99cc41f58]*/
+builtin_callable(PyObject *module, PyObject *obj)
+/*[clinic end generated code: output=2b095d59d934cb7e input=1423bab99cc41f58]*/
 {
     return PyBool_FromLong((long)PyCallable_Check(obj));
 }
@@ -574,9 +574,8 @@ format_spec defaults to the empty string
 [clinic start generated code]*/
 
 static PyObject *
-builtin_format_impl(PyModuleDef *module, PyObject *value,
-                    PyObject *format_spec)
-/*[clinic end generated code: output=4341fd78a5f01764 input=6325e751a1b29b86]*/
+builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec)
+/*[clinic end generated code: output=2f40bdfa4954b077 input=6325e751a1b29b86]*/
 {
     return PyObject_Format(value, format_spec);
 }
@@ -591,8 +590,8 @@ Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_chr_impl(PyModuleDef *module, int i)
-/*[clinic end generated code: output=67fe4d87e690f373 input=3f604ef45a70750d]*/
+builtin_chr_impl(PyObject *module, int i)
+/*[clinic end generated code: output=c733afcd200afcb7 input=3f604ef45a70750d]*/
 {
     return PyUnicode_FromOrdinal(i);
 }
@@ -672,10 +671,10 @@ in addition to any features explicitly specified.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_compile_impl(PyModuleDef *module, PyObject *source,
-                     PyObject *filename, const char *mode, int flags,
-                     int dont_inherit, int optimize)
-/*[clinic end generated code: output=31881762c1bb90c4 input=9d53e8cfb3c86414]*/
+builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
+                     const char *mode, int flags, int dont_inherit,
+                     int optimize)
+/*[clinic end generated code: output=1fa176e33452bb63 input=9d53e8cfb3c86414]*/
 {
     PyObject *source_copy;
     const char *str;
@@ -800,8 +799,8 @@ Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y)
-/*[clinic end generated code: output=9ad0076120ebf9ac input=175ad9c84ff41a85]*/
+builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y)
+/*[clinic end generated code: output=b06d8a5f6e0c745e input=175ad9c84ff41a85]*/
 {
     return PyNumber_Divmod(x, y);
 }
@@ -825,9 +824,9 @@ If only globals is given, locals defaults to it.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals,
+builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
                   PyObject *locals)
-/*[clinic end generated code: output=7284501fb7b4d666 input=11ee718a8640e527]*/
+/*[clinic end generated code: output=0a0824aa70093116 input=11ee718a8640e527]*/
 {
     PyObject *result, *source_copy;
     const char *str;
@@ -908,9 +907,9 @@ If only globals is given, locals defaults to it.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals,
+builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
                   PyObject *locals)
-/*[clinic end generated code: output=83d574ef9d5d0b46 input=01ca3e1c01692829]*/
+/*[clinic end generated code: output=3c90efc6ab68ef5d input=01ca3e1c01692829]*/
 {
     PyObject *v;
 
@@ -1024,8 +1023,8 @@ global scope and vice-versa.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_globals_impl(PyModuleDef *module)
-/*[clinic end generated code: output=4958645e96dd8138 input=9327576f92bb48ba]*/
+builtin_globals_impl(PyObject *module)
+/*[clinic end generated code: output=e5dd1527067b94d2 input=9327576f92bb48ba]*/
 {
     PyObject *d;
 
@@ -1048,8 +1047,8 @@ This is done by calling getattr(obj, name) and catching AttributeError.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
-/*[clinic end generated code: output=81154fdd63634696 input=0faec9787d979542]*/
+builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name)
+/*[clinic end generated code: output=a7aff2090a4151e5 input=0faec9787d979542]*/
 {
     PyObject *v;
 
@@ -1324,9 +1323,9 @@ setattr(x, 'y', v) is equivalent to ``x.y = v''
 [clinic start generated code]*/
 
 static PyObject *
-builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name,
+builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
                      PyObject *value)
-/*[clinic end generated code: output=d881c655c0f7e34f input=bd2b7ca6875a1899]*/
+/*[clinic end generated code: output=dc2ce1d1add9acb4 input=bd2b7ca6875a1899]*/
 {
     if (PyObject_SetAttr(obj, name, value) != 0)
         return NULL;
@@ -1348,8 +1347,8 @@ delattr(x, 'y') is equivalent to ``del x.y''
 [clinic start generated code]*/
 
 static PyObject *
-builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name)
-/*[clinic end generated code: output=ef653e698a0b4187 input=db16685d6b4b9410]*/
+builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name)
+/*[clinic end generated code: output=85134bc58dff79fa input=db16685d6b4b9410]*/
 {
     if (PyObject_SetAttr(obj, name, (PyObject *)NULL) != 0)
         return NULL;
@@ -1371,8 +1370,8 @@ reverse is not necessarily true.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_hash(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=1f32ff154c1f751a input=58c48be822bf9c54]*/
+builtin_hash(PyObject *module, PyObject *obj)
+/*[clinic end generated code: output=237668e9d7688db7 input=58c48be822bf9c54]*/
 {
     Py_hash_t x;
 
@@ -1396,8 +1395,8 @@ Return the hexadecimal representation of an integer.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_hex(PyModuleDef *module, PyObject *number)
-/*[clinic end generated code: output=618489ce3cbc5858 input=e645aff5fc7d540e]*/
+builtin_hex(PyObject *module, PyObject *number)
+/*[clinic end generated code: output=e46b612169099408 input=e645aff5fc7d540e]*/
 {
     return PyNumber_ToBase(number, 16);
 }
@@ -1440,8 +1439,8 @@ Return the number of items in a container.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_len(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=8e5837b6f81d915b input=bc55598da9e9c9b5]*/
+builtin_len(PyObject *module, PyObject *obj)
+/*[clinic end generated code: output=fa7a270d314dfb6c input=bc55598da9e9c9b5]*/
 {
     Py_ssize_t res;
 
@@ -1463,8 +1462,8 @@ covered by any backwards compatibility guarantees.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_locals_impl(PyModuleDef *module)
-/*[clinic end generated code: output=8b5a41f12e19d13a input=7874018d478d5c4b]*/
+builtin_locals_impl(PyObject *module)
+/*[clinic end generated code: output=b46c94015ce11448 input=7874018d478d5c4b]*/
 {
     PyObject *d;
 
@@ -1622,8 +1621,8 @@ Return the octal representation of an integer.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_oct(PyModuleDef *module, PyObject *number)
-/*[clinic end generated code: output=18f701bc6d8f804a input=ad6b274af4016c72]*/
+builtin_oct(PyObject *module, PyObject *number)
+/*[clinic end generated code: output=40a34656b6875352 input=ad6b274af4016c72]*/
 {
     return PyNumber_ToBase(number, 8);
 }
@@ -1639,8 +1638,8 @@ Return the Unicode code point for a one-character string.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_ord(PyModuleDef *module, PyObject *c)
-/*[clinic end generated code: output=04fd27272d9462f6 input=3064e5d6203ad012]*/
+builtin_ord(PyObject *module, PyObject *c)
+/*[clinic end generated code: output=4fa5e87a323bae71 input=3064e5d6203ad012]*/
 {
     long ord;
     Py_ssize_t size;
@@ -1699,8 +1698,8 @@ invoked using the three argument form.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z)
-/*[clinic end generated code: output=1fba268adba9b45f input=653d57d38d41fc07]*/
+builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z)
+/*[clinic end generated code: output=50a14d5d130d404b input=653d57d38d41fc07]*/
 {
     return PyNumber_Power(x, y, z);
 }
@@ -1818,8 +1817,8 @@ On *nix systems, readline is used if available.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_input_impl(PyModuleDef *module, PyObject *prompt)
-/*[clinic end generated code: output=b77731f59e1515c4 input=5e8bb70c2908fe3c]*/
+builtin_input_impl(PyObject *module, PyObject *prompt)
+/*[clinic end generated code: output=83db5a191e7a0d60 input=5e8bb70c2908fe3c]*/
 {
     PyObject *fin = _PySys_GetObjectId(&PyId_stdin);
     PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
@@ -2005,8 +2004,8 @@ For many object types, including most builtins, eval(repr(obj)) == obj.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_repr(PyModuleDef *module, PyObject *obj)
-/*[clinic end generated code: output=dc41784fa4341834 input=1c9e6d66d3e3be04]*/
+builtin_repr(PyObject *module, PyObject *obj)
+/*[clinic end generated code: output=7ed3778c44fd0194 input=1c9e6d66d3e3be04]*/
 {
     return PyObject_Repr(obj);
 }
@@ -2040,7 +2039,7 @@ builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
         return NULL;
     }
 
-    if (ndigits == NULL)
+    if (ndigits == NULL || ndigits == Py_None)
         result = PyObject_CallFunctionObjArgs(round, NULL);
     else
         result = PyObject_CallFunctionObjArgs(round, ndigits, NULL);
@@ -2069,7 +2068,7 @@ sorted as builtin_sorted
 
 Return a new list containing all items from the iterable in ascending order.
 
-A custom key function can be supplied to customise the sort order, and the
+A custom key function can be supplied to customize the sort order, and the
 reverse flag can be set to request the result in descending order.
 [end disabled clinic input]*/
 
@@ -2079,7 +2078,7 @@ PyDoc_STRVAR(builtin_sorted__doc__,
 "\n"
 "Return a new list containing all items from the iterable in ascending order.\n"
 "\n"
-"A custom key function can be supplied to customise the sort order, and the\n"
+"A custom key function can be supplied to customize the sort order, and the\n"
 "reverse flag can be set to request the result in descending order.");
 
 #define BUILTIN_SORTED_METHODDEF    \
@@ -2175,8 +2174,8 @@ reject non-numeric types.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start)
-/*[clinic end generated code: output=33655b248b21d581 input=3b5b7a9d7611c73a]*/
+builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
+/*[clinic end generated code: output=df758cec7d1d302f input=3b5b7a9d7611c73a]*/
 {
     PyObject *result = start;
     PyObject *temp, *item, *iter;
@@ -2352,9 +2351,9 @@ or ...`` etc.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_isinstance_impl(PyModuleDef *module, PyObject *obj,
+builtin_isinstance_impl(PyObject *module, PyObject *obj,
                         PyObject *class_or_tuple)
-/*[clinic end generated code: output=f960b7c12dbbeda0 input=ffa743db1daf7549]*/
+/*[clinic end generated code: output=6faf01472c13b003 input=ffa743db1daf7549]*/
 {
     int retval;
 
@@ -2380,9 +2379,9 @@ or ...`` etc.
 [clinic start generated code]*/
 
 static PyObject *
-builtin_issubclass_impl(PyModuleDef *module, PyObject *cls,
+builtin_issubclass_impl(PyObject *module, PyObject *cls,
                         PyObject *class_or_tuple)
-/*[clinic end generated code: output=8b012a151940bbf2 input=af5f35e9ceaddaf6]*/
+/*[clinic end generated code: output=358412410cd7a250 input=af5f35e9ceaddaf6]*/
 {
     int retval;
 
index 3d69038..7b40518 100644 (file)
@@ -1563,7 +1563,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
             if (PyUnicode_CheckExact(left) &&
                      PyUnicode_CheckExact(right)) {
                 sum = unicode_concatenate(left, right, f, next_instr);
-                /* unicode_concatenate consumed the ref to v */
+                /* unicode_concatenate consumed the ref to left */
             }
             else {
                 sum = PyNumber_Add(left, right);
@@ -1762,7 +1762,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
             PyObject *sum;
             if (PyUnicode_CheckExact(left) && PyUnicode_CheckExact(right)) {
                 sum = unicode_concatenate(left, right, f, next_instr);
-                /* unicode_concatenate consumed the ref to v */
+                /* unicode_concatenate consumed the ref to left */
             }
             else {
                 sum = PyNumber_InPlaceAdd(left, right);
@@ -1853,7 +1853,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
             PyObject *v = THIRD();
             int err;
             STACKADJ(-3);
-            /* v[w] = u */
+            /* container[sub] = v */
             err = PyObject_SetItem(container, sub, v);
             Py_DECREF(v);
             Py_DECREF(container);
@@ -1868,7 +1868,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
             PyObject *container = SECOND();
             int err;
             STACKADJ(-2);
-            /* del v[w] */
+            /* del container[sub] */
             err = PyObject_DelItem(container, sub);
             Py_DECREF(container);
             Py_DECREF(sub);
@@ -2107,7 +2107,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
                 SET_TOP(val);
                 DISPATCH();
             }
-            /* x remains on stack, retval is value to be yielded */
+            /* receiver remains on stack, retval is value to be yielded */
             f->f_stacktop = stack_pointer;
             why = WHY_YIELD;
             /* and repeat... */
@@ -2196,7 +2196,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
             else {
                 PyObject *build_class_str = _PyUnicode_FromId(&PyId___build_class__);
                 if (build_class_str == NULL)
-                    break;
+                    goto error;
                 bc = PyObject_GetItem(f->f_builtins, build_class_str);
                 if (bc == NULL) {
                     if (PyErr_ExceptionMatches(PyExc_KeyError))
@@ -2580,14 +2580,16 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
         TARGET(BUILD_SET) {
             PyObject *set = PySet_New(NULL);
             int err = 0;
+            int i;
             if (set == NULL)
                 goto error;
-            while (--oparg >= 0) {
-                PyObject *item = POP();
+            for (i = oparg; i > 0; i--) {
+                PyObject *item = PEEK(i);
                 if (err == 0)
                     err = PySet_Add(set, item);
                 Py_DECREF(item);
             }
+            STACKADJ(-oparg);
             if (err != 0) {
                 Py_DECREF(set);
                 goto error;
@@ -2644,14 +2646,12 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
         _build_map_unpack: {
             int with_call = opcode == BUILD_MAP_UNPACK_WITH_CALL;
             int num_maps;
-            int function_location;
             int i;
             PyObject *sum = PyDict_New();
             if (sum == NULL)
                 goto error;
             if (with_call) {
                 num_maps = oparg & 0xff;
-                function_location = (oparg>>8) & 0xff;
             }
             else {
                 num_maps = oparg;
@@ -2663,7 +2663,9 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
                     PyObject *intersection = _PyDictView_Intersect(sum, arg);
 
                     if (intersection == NULL) {
-                        if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
+                        if (PyErr_ExceptionMatches(PyExc_AttributeError) ||
+                            !PyMapping_Check(arg)) {
+                            int function_location = (oparg>>8) & 0xff;
                             PyObject *func = (
                                     PEEK(function_location + num_maps));
                             PyErr_Format(PyExc_TypeError,
@@ -2680,6 +2682,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
                     if (PySet_GET_SIZE(intersection)) {
                         Py_ssize_t idx = 0;
                         PyObject *key;
+                        int function_location = (oparg>>8) & 0xff;
                         PyObject *func = PEEK(function_location + num_maps);
                         Py_hash_t hash;
                         _PySet_NextEntry(intersection, &idx, &key, &hash);
@@ -2705,9 +2708,21 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
 
                 if (PyDict_Update(sum, arg) < 0) {
                     if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
-                        PyErr_Format(PyExc_TypeError,
-                                "'%.200s' object is not a mapping",
-                                arg->ob_type->tp_name);
+                        if (with_call) {
+                            int function_location = (oparg>>8) & 0xff;
+                            PyObject *func = PEEK(function_location + num_maps);
+                            PyErr_Format(PyExc_TypeError,
+                                    "%.200s%.200s argument after ** "
+                                    "must be a mapping, not %.200s",
+                                    PyEval_GetFuncName(func),
+                                    PyEval_GetFuncDesc(func),
+                                    arg->ob_type->tp_name);
+                        }
+                        else {
+                            PyErr_Format(PyExc_TypeError,
+                                    "'%.200s' object is not a mapping",
+                                    arg->ob_type->tp_name);
+                        }
                     }
                     Py_DECREF(sum);
                     goto error;
@@ -2728,7 +2743,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
             STACKADJ(-2);
             map = stack_pointer[-oparg];  /* dict */
             assert(PyDict_CheckExact(map));
-            err = PyDict_SetItem(map, key, value);  /* v[w] = u */
+            err = PyDict_SetItem(map, key, value);  /* map[key] = value */
             Py_DECREF(value);
             Py_DECREF(key);
             if (err != 0)
@@ -4123,7 +4138,7 @@ do_raise(PyObject *exc, PyObject *cause)
         type = tstate->exc_type;
         value = tstate->exc_value;
         tb = tstate->exc_traceback;
-        if (type == Py_None) {
+        if (type == Py_None || type == NULL) {
             PyErr_SetString(PyExc_RuntimeError,
                             "No active exception to reraise");
             return 0;
index 90995e5..4e2b1f1 100644 (file)
@@ -83,11 +83,10 @@ PyDoc_STRVAR(builtin_format__doc__,
     {"format", (PyCFunction)builtin_format, METH_VARARGS, builtin_format__doc__},
 
 static PyObject *
-builtin_format_impl(PyModuleDef *module, PyObject *value,
-                    PyObject *format_spec);
+builtin_format_impl(PyObject *module, PyObject *value, PyObject *format_spec);
 
 static PyObject *
-builtin_format(PyModuleDef *module, PyObject *args)
+builtin_format(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *value;
@@ -112,10 +111,10 @@ PyDoc_STRVAR(builtin_chr__doc__,
     {"chr", (PyCFunction)builtin_chr, METH_O, builtin_chr__doc__},
 
 static PyObject *
-builtin_chr_impl(PyModuleDef *module, int i);
+builtin_chr_impl(PyObject *module, int i);
 
 static PyObject *
-builtin_chr(PyModuleDef *module, PyObject *arg)
+builtin_chr(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     int i;
@@ -150,12 +149,12 @@ PyDoc_STRVAR(builtin_compile__doc__,
     {"compile", (PyCFunction)builtin_compile, METH_VARARGS|METH_KEYWORDS, builtin_compile__doc__},
 
 static PyObject *
-builtin_compile_impl(PyModuleDef *module, PyObject *source,
-                     PyObject *filename, const char *mode, int flags,
-                     int dont_inherit, int optimize);
+builtin_compile_impl(PyObject *module, PyObject *source, PyObject *filename,
+                     const char *mode, int flags, int dont_inherit,
+                     int optimize);
 
 static PyObject *
-builtin_compile(PyModuleDef *module, PyObject *args, PyObject *kwargs)
+builtin_compile(PyObject *module, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
     static char *_keywords[] = {"source", "filename", "mode", "flags", "dont_inherit", "optimize", NULL};
@@ -185,10 +184,10 @@ PyDoc_STRVAR(builtin_divmod__doc__,
     {"divmod", (PyCFunction)builtin_divmod, METH_VARARGS, builtin_divmod__doc__},
 
 static PyObject *
-builtin_divmod_impl(PyModuleDef *module, PyObject *x, PyObject *y);
+builtin_divmod_impl(PyObject *module, PyObject *x, PyObject *y);
 
 static PyObject *
-builtin_divmod(PyModuleDef *module, PyObject *args)
+builtin_divmod(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *x;
@@ -220,11 +219,11 @@ PyDoc_STRVAR(builtin_eval__doc__,
     {"eval", (PyCFunction)builtin_eval, METH_VARARGS, builtin_eval__doc__},
 
 static PyObject *
-builtin_eval_impl(PyModuleDef *module, PyObject *source, PyObject *globals,
+builtin_eval_impl(PyObject *module, PyObject *source, PyObject *globals,
                   PyObject *locals);
 
 static PyObject *
-builtin_eval(PyModuleDef *module, PyObject *args)
+builtin_eval(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *source;
@@ -257,11 +256,11 @@ PyDoc_STRVAR(builtin_exec__doc__,
     {"exec", (PyCFunction)builtin_exec, METH_VARARGS, builtin_exec__doc__},
 
 static PyObject *
-builtin_exec_impl(PyModuleDef *module, PyObject *source, PyObject *globals,
+builtin_exec_impl(PyObject *module, PyObject *source, PyObject *globals,
                   PyObject *locals);
 
 static PyObject *
-builtin_exec(PyModuleDef *module, PyObject *args)
+builtin_exec(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *source;
@@ -291,10 +290,10 @@ PyDoc_STRVAR(builtin_globals__doc__,
     {"globals", (PyCFunction)builtin_globals, METH_NOARGS, builtin_globals__doc__},
 
 static PyObject *
-builtin_globals_impl(PyModuleDef *module);
+builtin_globals_impl(PyObject *module);
 
 static PyObject *
-builtin_globals(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+builtin_globals(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return builtin_globals_impl(module);
 }
@@ -311,10 +310,10 @@ PyDoc_STRVAR(builtin_hasattr__doc__,
     {"hasattr", (PyCFunction)builtin_hasattr, METH_VARARGS, builtin_hasattr__doc__},
 
 static PyObject *
-builtin_hasattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name);
+builtin_hasattr_impl(PyObject *module, PyObject *obj, PyObject *name);
 
 static PyObject *
-builtin_hasattr(PyModuleDef *module, PyObject *args)
+builtin_hasattr(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *obj;
@@ -354,11 +353,11 @@ PyDoc_STRVAR(builtin_setattr__doc__,
     {"setattr", (PyCFunction)builtin_setattr, METH_VARARGS, builtin_setattr__doc__},
 
 static PyObject *
-builtin_setattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name,
+builtin_setattr_impl(PyObject *module, PyObject *obj, PyObject *name,
                      PyObject *value);
 
 static PyObject *
-builtin_setattr(PyModuleDef *module, PyObject *args)
+builtin_setattr(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *obj;
@@ -387,10 +386,10 @@ PyDoc_STRVAR(builtin_delattr__doc__,
     {"delattr", (PyCFunction)builtin_delattr, METH_VARARGS, builtin_delattr__doc__},
 
 static PyObject *
-builtin_delattr_impl(PyModuleDef *module, PyObject *obj, PyObject *name);
+builtin_delattr_impl(PyObject *module, PyObject *obj, PyObject *name);
 
 static PyObject *
-builtin_delattr(PyModuleDef *module, PyObject *args)
+builtin_delattr(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *obj;
@@ -453,10 +452,10 @@ PyDoc_STRVAR(builtin_locals__doc__,
     {"locals", (PyCFunction)builtin_locals, METH_NOARGS, builtin_locals__doc__},
 
 static PyObject *
-builtin_locals_impl(PyModuleDef *module);
+builtin_locals_impl(PyObject *module);
 
 static PyObject *
-builtin_locals(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+builtin_locals(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return builtin_locals_impl(module);
 }
@@ -495,10 +494,10 @@ PyDoc_STRVAR(builtin_pow__doc__,
     {"pow", (PyCFunction)builtin_pow, METH_VARARGS, builtin_pow__doc__},
 
 static PyObject *
-builtin_pow_impl(PyModuleDef *module, PyObject *x, PyObject *y, PyObject *z);
+builtin_pow_impl(PyObject *module, PyObject *x, PyObject *y, PyObject *z);
 
 static PyObject *
-builtin_pow(PyModuleDef *module, PyObject *args)
+builtin_pow(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *x;
@@ -531,10 +530,10 @@ PyDoc_STRVAR(builtin_input__doc__,
     {"input", (PyCFunction)builtin_input, METH_VARARGS, builtin_input__doc__},
 
 static PyObject *
-builtin_input_impl(PyModuleDef *module, PyObject *prompt);
+builtin_input_impl(PyObject *module, PyObject *prompt);
 
 static PyObject *
-builtin_input(PyModuleDef *module, PyObject *args)
+builtin_input(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *prompt = NULL;
@@ -574,10 +573,10 @@ PyDoc_STRVAR(builtin_sum__doc__,
     {"sum", (PyCFunction)builtin_sum, METH_VARARGS, builtin_sum__doc__},
 
 static PyObject *
-builtin_sum_impl(PyModuleDef *module, PyObject *iterable, PyObject *start);
+builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start);
 
 static PyObject *
-builtin_sum(PyModuleDef *module, PyObject *args)
+builtin_sum(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *iterable;
@@ -607,11 +606,11 @@ PyDoc_STRVAR(builtin_isinstance__doc__,
     {"isinstance", (PyCFunction)builtin_isinstance, METH_VARARGS, builtin_isinstance__doc__},
 
 static PyObject *
-builtin_isinstance_impl(PyModuleDef *module, PyObject *obj,
+builtin_isinstance_impl(PyObject *module, PyObject *obj,
                         PyObject *class_or_tuple);
 
 static PyObject *
-builtin_isinstance(PyModuleDef *module, PyObject *args)
+builtin_isinstance(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *obj;
@@ -641,11 +640,11 @@ PyDoc_STRVAR(builtin_issubclass__doc__,
     {"issubclass", (PyCFunction)builtin_issubclass, METH_VARARGS, builtin_issubclass__doc__},
 
 static PyObject *
-builtin_issubclass_impl(PyModuleDef *module, PyObject *cls,
+builtin_issubclass_impl(PyObject *module, PyObject *cls,
                         PyObject *class_or_tuple);
 
 static PyObject *
-builtin_issubclass(PyModuleDef *module, PyObject *args)
+builtin_issubclass(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *cls;
@@ -660,4 +659,4 @@ builtin_issubclass(PyModuleDef *module, PyObject *args)
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=4bef16b6aa432879 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=9031270b64c794b8 input=a9049054013a1b77]*/
index 2477665..05d79ac 100644 (file)
@@ -14,10 +14,10 @@ PyDoc_STRVAR(_imp_lock_held__doc__,
     {"lock_held", (PyCFunction)_imp_lock_held, METH_NOARGS, _imp_lock_held__doc__},
 
 static PyObject *
-_imp_lock_held_impl(PyModuleDef *module);
+_imp_lock_held_impl(PyObject *module);
 
 static PyObject *
-_imp_lock_held(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_imp_lock_held(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return _imp_lock_held_impl(module);
 }
@@ -35,10 +35,10 @@ PyDoc_STRVAR(_imp_acquire_lock__doc__,
     {"acquire_lock", (PyCFunction)_imp_acquire_lock, METH_NOARGS, _imp_acquire_lock__doc__},
 
 static PyObject *
-_imp_acquire_lock_impl(PyModuleDef *module);
+_imp_acquire_lock_impl(PyObject *module);
 
 static PyObject *
-_imp_acquire_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_imp_acquire_lock(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return _imp_acquire_lock_impl(module);
 }
@@ -55,10 +55,10 @@ PyDoc_STRVAR(_imp_release_lock__doc__,
     {"release_lock", (PyCFunction)_imp_release_lock, METH_NOARGS, _imp_release_lock__doc__},
 
 static PyObject *
-_imp_release_lock_impl(PyModuleDef *module);
+_imp_release_lock_impl(PyObject *module);
 
 static PyObject *
-_imp_release_lock(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_imp_release_lock(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return _imp_release_lock_impl(module);
 }
@@ -78,11 +78,11 @@ PyDoc_STRVAR(_imp__fix_co_filename__doc__,
     {"_fix_co_filename", (PyCFunction)_imp__fix_co_filename, METH_VARARGS, _imp__fix_co_filename__doc__},
 
 static PyObject *
-_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code,
+_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
                            PyObject *path);
 
 static PyObject *
-_imp__fix_co_filename(PyModuleDef *module, PyObject *args)
+_imp__fix_co_filename(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyCodeObject *code;
@@ -116,10 +116,10 @@ PyDoc_STRVAR(_imp_extension_suffixes__doc__,
     {"extension_suffixes", (PyCFunction)_imp_extension_suffixes, METH_NOARGS, _imp_extension_suffixes__doc__},
 
 static PyObject *
-_imp_extension_suffixes_impl(PyModuleDef *module);
+_imp_extension_suffixes_impl(PyObject *module);
 
 static PyObject *
-_imp_extension_suffixes(PyModuleDef *module, PyObject *Py_UNUSED(ignored))
+_imp_extension_suffixes(PyObject *module, PyObject *Py_UNUSED(ignored))
 {
     return _imp_extension_suffixes_impl(module);
 }
@@ -134,10 +134,10 @@ PyDoc_STRVAR(_imp_init_frozen__doc__,
     {"init_frozen", (PyCFunction)_imp_init_frozen, METH_O, _imp_init_frozen__doc__},
 
 static PyObject *
-_imp_init_frozen_impl(PyModuleDef *module, PyObject *name);
+_imp_init_frozen_impl(PyObject *module, PyObject *name);
 
 static PyObject *
-_imp_init_frozen(PyModuleDef *module, PyObject *arg)
+_imp_init_frozen(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *name;
@@ -160,10 +160,10 @@ PyDoc_STRVAR(_imp_get_frozen_object__doc__,
     {"get_frozen_object", (PyCFunction)_imp_get_frozen_object, METH_O, _imp_get_frozen_object__doc__},
 
 static PyObject *
-_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name);
+_imp_get_frozen_object_impl(PyObject *module, PyObject *name);
 
 static PyObject *
-_imp_get_frozen_object(PyModuleDef *module, PyObject *arg)
+_imp_get_frozen_object(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *name;
@@ -186,10 +186,10 @@ PyDoc_STRVAR(_imp_is_frozen_package__doc__,
     {"is_frozen_package", (PyCFunction)_imp_is_frozen_package, METH_O, _imp_is_frozen_package__doc__},
 
 static PyObject *
-_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name);
+_imp_is_frozen_package_impl(PyObject *module, PyObject *name);
 
 static PyObject *
-_imp_is_frozen_package(PyModuleDef *module, PyObject *arg)
+_imp_is_frozen_package(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *name;
@@ -212,10 +212,10 @@ PyDoc_STRVAR(_imp_is_builtin__doc__,
     {"is_builtin", (PyCFunction)_imp_is_builtin, METH_O, _imp_is_builtin__doc__},
 
 static PyObject *
-_imp_is_builtin_impl(PyModuleDef *module, PyObject *name);
+_imp_is_builtin_impl(PyObject *module, PyObject *name);
 
 static PyObject *
-_imp_is_builtin(PyModuleDef *module, PyObject *arg)
+_imp_is_builtin(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *name;
@@ -238,10 +238,10 @@ PyDoc_STRVAR(_imp_is_frozen__doc__,
     {"is_frozen", (PyCFunction)_imp_is_frozen, METH_O, _imp_is_frozen__doc__},
 
 static PyObject *
-_imp_is_frozen_impl(PyModuleDef *module, PyObject *name);
+_imp_is_frozen_impl(PyObject *module, PyObject *name);
 
 static PyObject *
-_imp_is_frozen(PyModuleDef *module, PyObject *arg)
+_imp_is_frozen(PyObject *module, PyObject *arg)
 {
     PyObject *return_value = NULL;
     PyObject *name;
@@ -266,10 +266,10 @@ PyDoc_STRVAR(_imp_create_dynamic__doc__,
     {"create_dynamic", (PyCFunction)_imp_create_dynamic, METH_VARARGS, _imp_create_dynamic__doc__},
 
 static PyObject *
-_imp_create_dynamic_impl(PyModuleDef *module, PyObject *spec, PyObject *file);
+_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file);
 
 static PyObject *
-_imp_create_dynamic(PyModuleDef *module, PyObject *args)
+_imp_create_dynamic(PyObject *module, PyObject *args)
 {
     PyObject *return_value = NULL;
     PyObject *spec;
@@ -299,10 +299,10 @@ PyDoc_STRVAR(_imp_exec_dynamic__doc__,
     {"exec_dynamic", (PyCFunction)_imp_exec_dynamic, METH_O, _imp_exec_dynamic__doc__},
 
 static int
-_imp_exec_dynamic_impl(PyModuleDef *module, PyObject *mod);
+_imp_exec_dynamic_impl(PyObject *module, PyObject *mod);
 
 static PyObject *
-_imp_exec_dynamic(PyModuleDef *module, PyObject *mod)
+_imp_exec_dynamic(PyObject *module, PyObject *mod)
 {
     PyObject *return_value = NULL;
     int _return_value;
@@ -328,10 +328,10 @@ PyDoc_STRVAR(_imp_exec_builtin__doc__,
     {"exec_builtin", (PyCFunction)_imp_exec_builtin, METH_O, _imp_exec_builtin__doc__},
 
 static int
-_imp_exec_builtin_impl(PyModuleDef *module, PyObject *mod);
+_imp_exec_builtin_impl(PyObject *module, PyObject *mod);
 
 static PyObject *
-_imp_exec_builtin(PyModuleDef *module, PyObject *mod)
+_imp_exec_builtin(PyObject *module, PyObject *mod)
 {
     PyObject *return_value = NULL;
     int _return_value;
@@ -352,4 +352,4 @@ exit:
 #ifndef _IMP_EXEC_DYNAMIC_METHODDEF
     #define _IMP_EXEC_DYNAMIC_METHODDEF
 #endif /* !defined(_IMP_EXEC_DYNAMIC_METHODDEF) */
-/*[clinic end generated code: output=32324a5e46cdfc4b input=a9049054013a1b77]*/
+/*[clinic end generated code: output=90ad6e5833e6170d input=a9049054013a1b77]*/
index 1e720ea..adc33ac 100644 (file)
@@ -1390,7 +1390,7 @@ get_ref_type(struct compiler *c, PyObject *name)
 {
     int scope;
     if (c->u->u_scope_type == COMPILER_SCOPE_CLASS &&
-        !PyUnicode_CompareWithASCIIString(name, "__class__"))
+        _PyUnicode_EqualToASCIIString(name, "__class__"))
         return CELL;
     scope = PyST_GetScope(c->u->u_ste, name);
     if (scope == 0) {
@@ -1494,6 +1494,9 @@ static int
 compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
                               asdl_seq *kw_defaults)
 {
+    /* Return the number of defaults + 1.
+       Returns 0 on error.
+     */
     int i, default_count = 0;
     for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) {
         arg_ty arg = asdl_seq_GET(kwonlyargs, i);
@@ -1501,16 +1504,16 @@ compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs,
         if (default_) {
             PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg);
             if (!mangled)
-                return -1;
+                return 0;
             ADDOP_O(c, LOAD_CONST, mangled, consts);
             Py_DECREF(mangled);
             if (!compiler_visit_expr(c, default_)) {
-                return -1;
+                return 0;
             }
             default_count++;
         }
     }
-    return default_count;
+    return default_count + 1;
 }
 
 static int
@@ -1554,17 +1557,17 @@ compiler_visit_annotations(struct compiler *c, arguments_ty args,
                            expr_ty returns)
 {
     /* Push arg annotations and a list of the argument names. Return the #
-       of items pushed. The expressions are evaluated out-of-order wrt the
+       of items pushed + 1. The expressions are evaluated out-of-order wrt the
        source code.
 
-       More than 2^16-1 annotations is a SyntaxError. Returns -1 on error.
+       More than 2^16-1 annotations is a SyntaxError. Returns 0 on error.
        */
     static identifier return_str;
     PyObject *names;
     Py_ssize_t len;
     names = PyList_New(0);
     if (!names)
-        return -1;
+        return 0;
 
     if (!compiler_visit_argannotations(c, args->args, names))
         goto error;
@@ -1614,11 +1617,11 @@ compiler_visit_annotations(struct compiler *c, arguments_ty args,
     Py_DECREF(names);
 
     /* We just checked that len <= 65535, see above */
-    return Py_SAFE_DOWNCAST(len, Py_ssize_t, int);
+    return Py_SAFE_DOWNCAST(len + 1, Py_ssize_t, int);
 
 error:
     Py_DECREF(names);
-    return -1;
+    return 0;
 }
 
 static int
@@ -1667,13 +1670,14 @@ compiler_function(struct compiler *c, stmt_ty s, int is_async)
     if (args->kwonlyargs) {
         int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
                                                 args->kw_defaults);
-        if (res < 0)
+        if (res == 0)
             return 0;
-        kw_default_count = res;
+        kw_default_count = res - 1;
     }
     num_annotations = compiler_visit_annotations(c, args, returns);
-    if (num_annotations < 0)
+    if (num_annotations == 0)
         return 0;
+    num_annotations--;
     assert((num_annotations & 0xFFFF) == num_annotations);
 
     if (!compiler_enter_scope(c, name,
@@ -1889,8 +1893,8 @@ compiler_lambda(struct compiler *c, expr_ty e)
     if (args->kwonlyargs) {
         int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs,
                                                 args->kw_defaults);
-        if (res < 0) return 0;
-        kw_default_count = res;
+        if (res == 0) return 0;
+        kw_default_count = res - 1;
     }
     if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA,
                               (void *)e, e->lineno))
@@ -2403,7 +2407,7 @@ compiler_import_as(struct compiler *c, identifier name, identifier asname)
     Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
                                         PyUnicode_GET_LENGTH(name), 1);
     if (dot == -2)
-        return -1;
+        return 0;
     if (dot != -1) {
         /* Consume the base module name to get the first attribute */
         Py_ssize_t pos = dot + 1;
@@ -2412,12 +2416,12 @@ compiler_import_as(struct compiler *c, identifier name, identifier asname)
             dot = PyUnicode_FindChar(name, '.', pos,
                                      PyUnicode_GET_LENGTH(name), 1);
             if (dot == -2)
-                return -1;
+                return 0;
             attr = PyUnicode_Substring(name, pos,
                                        (dot != -1) ? dot :
                                        PyUnicode_GET_LENGTH(name));
             if (!attr)
-                return -1;
+                return 0;
             ADDOP_O(c, LOAD_ATTR, attr, names);
             Py_DECREF(attr);
             pos = dot + 1;
@@ -2509,7 +2513,7 @@ compiler_from_import(struct compiler *c, stmt_ty s)
     }
 
     if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
-        !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) {
+        _PyUnicode_EqualToASCIIString(s->v.ImportFrom.module, "__future__")) {
         Py_DECREF(level);
         Py_DECREF(names);
         return compiler_error(c, "from __future__ imports must occur "
@@ -2833,9 +2837,9 @@ compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
     if (!mangled)
         return 0;
 
-    assert(PyUnicode_CompareWithASCIIString(name, "None") &&
-           PyUnicode_CompareWithASCIIString(name, "True") &&
-           PyUnicode_CompareWithASCIIString(name, "False"));
+    assert(!_PyUnicode_EqualToASCIIString(name, "None") &&
+           !_PyUnicode_EqualToASCIIString(name, "True") &&
+           !_PyUnicode_EqualToASCIIString(name, "False"));
 
     op = 0;
     optype = OP_NAME;
@@ -3262,7 +3266,7 @@ compiler_call_helper(struct compiler *c,
         code |= 2;
         if (nsubkwargs > 1) {
             /* Pack it all up */
-            int function_pos = n + (code & 1) + nkw + 1;
+            int function_pos = n + (code & 1) + 2 * nkw + 1;
             ADDOP_I(c, BUILD_MAP_UNPACK_WITH_CALL, nsubkwargs | (function_pos << 8));
         }
     }
@@ -3976,7 +3980,7 @@ compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
 {
     struct fblockinfo *f;
     if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
-        PyErr_SetString(PyExc_SystemError,
+        PyErr_SetString(PyExc_SyntaxError,
                         "too many statically nested blocks");
         return 0;
     }
index bb5b1b6..ced910f 100644 (file)
@@ -238,7 +238,7 @@ _PyCOND_WAIT_MS(PyCOND_T *cv, PyMUTEX_T *cs, DWORD ms)
     cv->waiting++;
     PyMUTEX_UNLOCK(cs);
     /* "lost wakeup bug" would occur if the caller were interrupted here,
-     * but we are safe because we are using a semaphore wich has an internal
+     * but we are safe because we are using a semaphore which has an internal
      * count.
      */
     wait = WaitForSingleObjectEx(cv->sem, ms, FALSE);
index e151cab..b820722 100644 (file)
@@ -388,8 +388,11 @@ _PyErr_ChainExceptions(PyObject *exc, PyObject *val, PyObject *tb)
         PyObject *exc2, *val2, *tb2;
         PyErr_Fetch(&exc2, &val2, &tb2);
         PyErr_NormalizeException(&exc, &val, &tb);
+        if (tb != NULL) {
+            PyException_SetTraceback(val, tb);
+            Py_DECREF(tb);
+        }
         Py_DECREF(exc);
-        Py_XDECREF(tb);
         PyErr_NormalizeException(&exc2, &val2, &tb2);
         PyException_SetContext(val2, val);
         PyErr_Restore(exc2, val2, tb2);
@@ -931,7 +934,7 @@ PyErr_WriteUnraisable(PyObject *obj)
             goto done;
     }
     else {
-        if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0) {
+        if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins)) {
             if (PyFile_WriteObject(moduleName, f, Py_PRINT_RAW) < 0)
                 goto done;
             if (PyFile_WriteString(".", f) < 0)
@@ -1006,16 +1009,15 @@ PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
             PyErr_Clear();
         Py_DECREF(tmp);
     }
+    tmp = NULL;
     if (col_offset >= 0) {
         tmp = PyLong_FromLong(col_offset);
         if (tmp == NULL)
             PyErr_Clear();
-        else {
-            if (_PyObject_SetAttrId(v, &PyId_offset, tmp))
-                PyErr_Clear();
-            Py_DECREF(tmp);
-        }
     }
+    if (_PyObject_SetAttrId(v, &PyId_offset, tmp ? tmp : Py_None))
+        PyErr_Clear();
+    Py_XDECREF(tmp);
     if (filename != NULL) {
         if (_PyObject_SetAttrId(v, &PyId_filename, filename))
             PyErr_Clear();
@@ -1027,9 +1029,6 @@ PyErr_SyntaxLocationObject(PyObject *filename, int lineno, int col_offset)
             Py_DECREF(tmp);
         }
     }
-    if (_PyObject_SetAttrId(v, &PyId_offset, Py_None)) {
-        PyErr_Clear();
-    }
     if (exc != PyExc_SyntaxError) {
         if (!_PyObject_HasAttrId(v, &PyId_msg)) {
             tmp = PyObject_Str(v);
@@ -1095,11 +1094,8 @@ err_programtext(FILE *fp, int lineno)
     }
     fclose(fp);
     if (i == lineno) {
-        char *p = linebuf;
         PyObject *res;
-        while (*p == ' ' || *p == '\t' || *p == '\014')
-            p++;
-        res = PyUnicode_FromString(p);
+        res = PyUnicode_FromString(linebuf);
         if (res == NULL)
             PyErr_Clear();
         return res;
index 8e9c502..617d58b 100644 (file)
@@ -118,7 +118,7 @@ typedef struct {
 } InternalFormatSpec;
 
 #if 0
-/* Occassionally useful for debugging. Should normally be commented out. */
+/* Occasionally useful for debugging. Should normally be commented out. */
 static void
 DEBUG_PRINT_FORMAT_SPEC(InternalFormatSpec *format)
 {
@@ -347,9 +347,11 @@ fill_padding(_PyUnicodeWriter *writer,
 /************************************************************************/
 
 /* Locale type codes. */
-#define LT_CURRENT_LOCALE 0
-#define LT_DEFAULT_LOCALE 1
-#define LT_NO_LOCALE 2
+enum LocaleType {
+    LT_CURRENT_LOCALE,
+    LT_DEFAULT_LOCALE,
+    LT_NO_LOCALE
+};
 
 /* Locale info needed for formatting integers and the part of floats
    before and including the decimal. Note that locales only support
@@ -663,7 +665,7 @@ static char no_grouping[1] = {CHAR_MAX};
    LT_CURRENT_LOCALE, a hard-coded locale if LT_DEFAULT_LOCALE, or
    none if LT_NO_LOCALE. */
 static int
-get_locale_info(int type, LocaleInfo *locale_info)
+get_locale_info(enum LocaleType type, LocaleInfo *locale_info)
 {
     switch (type) {
     case LT_CURRENT_LOCALE: {
@@ -676,21 +678,16 @@ get_locale_info(int type, LocaleInfo *locale_info)
         locale_info->thousands_sep = PyUnicode_DecodeLocale(
                                          locale_data->thousands_sep,
                                          NULL);
-        if (locale_info->thousands_sep == NULL) {
-            Py_DECREF(locale_info->decimal_point);
+        if (locale_info->thousands_sep == NULL)
             return -1;
-        }
         locale_info->grouping = locale_data->grouping;
         break;
     }
     case LT_DEFAULT_LOCALE:
         locale_info->decimal_point = PyUnicode_FromOrdinal('.');
         locale_info->thousands_sep = PyUnicode_FromOrdinal(',');
-        if (!locale_info->decimal_point || !locale_info->thousands_sep) {
-            Py_XDECREF(locale_info->decimal_point);
-            Py_XDECREF(locale_info->thousands_sep);
+        if (!locale_info->decimal_point || !locale_info->thousands_sep)
             return -1;
-        }
         locale_info->grouping = "\3"; /* Group every 3 characters.  The
                                          (implicit) trailing 0 means repeat
                                          infinitely. */
@@ -698,15 +695,10 @@ get_locale_info(int type, LocaleInfo *locale_info)
     case LT_NO_LOCALE:
         locale_info->decimal_point = PyUnicode_FromOrdinal('.');
         locale_info->thousands_sep = PyUnicode_New(0, 0);
-        if (!locale_info->decimal_point || !locale_info->thousands_sep) {
-            Py_XDECREF(locale_info->decimal_point);
-            Py_XDECREF(locale_info->thousands_sep);
+        if (!locale_info->decimal_point || !locale_info->thousands_sep)
             return -1;
-        }
         locale_info->grouping = no_grouping;
         break;
-    default:
-        assert(0);
     }
     return 0;
 }
index 163f87f..4de801b 100644 (file)
@@ -99,7 +99,7 @@ future_parse(PyFutureFeatures *ff, mod_ty mod, PyObject *filename)
         if (s->kind == ImportFrom_kind) {
             identifier modname = s->v.ImportFrom.module;
             if (modname &&
-                !PyUnicode_CompareWithASCIIString(modname, "__future__")) {
+                _PyUnicode_EqualToASCIIString(modname, "__future__")) {
                 if (done) {
                     PyErr_SetString(PyExc_SyntaxError,
                                     ERR_LATE_FUTURE);
index 8aab067..b10e776 100644 (file)
@@ -1618,7 +1618,7 @@ vgetargskeywords(PyObject *args, PyObject *keywords, const char *format,
                 return cleanreturn(0, &freelist);
             }
             for (i = 0; i < len; i++) {
-                if (!PyUnicode_CompareWithASCIIString(key, kwlist[i])) {
+                if (_PyUnicode_EqualToASCIIString(key, kwlist[i])) {
                     match = 1;
                     break;
                 }
index c3f1e89..cac647c 100644 (file)
@@ -4,7 +4,7 @@
 
 static const char cprt[] =
 "\
-Copyright (c) 2001-2016 Python Software Foundation.\n\
+Copyright (c) 2001-2017 Python Software Foundation.\n\
 All Rights Reserved.\n\
 \n\
 Copyright (c) 2000 BeOpen.com.\n\
index 0b843da..3579273 100644 (file)
@@ -242,8 +242,8 @@ On platforms without threads, return False.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_lock_held_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d7a8cc3a5169081a input=9b088f9b217d9bdf]*/
+_imp_lock_held_impl(PyObject *module)
+/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
 {
 #ifdef WITH_THREAD
     return PyBool_FromLong(import_lock_thread != -1);
@@ -262,8 +262,8 @@ modules. On platforms without threads, this function does nothing.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_acquire_lock_impl(PyModuleDef *module)
-/*[clinic end generated code: output=cc143b1d16422cae input=4a2d4381866d5fdc]*/
+_imp_acquire_lock_impl(PyObject *module)
+/*[clinic end generated code: output=1aff58cb0ee1b026 input=4a2d4381866d5fdc]*/
 {
 #ifdef WITH_THREAD
     _PyImport_AcquireLock();
@@ -281,8 +281,8 @@ On platforms without threads, this function does nothing.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_release_lock_impl(PyModuleDef *module)
-/*[clinic end generated code: output=74d28e38ebe2b224 input=934fb11516dd778b]*/
+_imp_release_lock_impl(PyObject *module)
+/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
 {
 #ifdef WITH_THREAD
     if (_PyImport_ReleaseLock() < 0) {
@@ -926,9 +926,9 @@ Changes code.co_filename to specify the passed-in file path.
 [clinic start generated code]*/
 
 static PyObject *
-_imp__fix_co_filename_impl(PyModuleDef *module, PyCodeObject *code,
+_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
                            PyObject *path)
-/*[clinic end generated code: output=f4db56aac0a1327f input=895ba50e78b82f05]*/
+/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
 
 {
     update_compiled_module(code, path);
@@ -946,10 +946,9 @@ static const struct _frozen * find_frozen(PyObject *);
 static int
 is_builtin(PyObject *name)
 {
-    int i, cmp;
+    int i;
     for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
-        cmp = PyUnicode_CompareWithASCIIString(name, PyImport_Inittab[i].name);
-        if (cmp == 0) {
+        if (_PyUnicode_EqualToASCIIString(name, PyImport_Inittab[i].name)) {
             if (PyImport_Inittab[i].initfunc == NULL)
                 return -1;
             else
@@ -960,12 +959,13 @@ is_builtin(PyObject *name)
 }
 
 
-/* Return an importer object for a sys.path/pkg.__path__ item 'p',
+/* Return a finder object for a sys.path/pkg.__path__ item 'p',
    possibly by fetching it from the path_importer_cache dict. If it
    wasn't yet cached, traverse path_hooks until a hook is found
    that can handle the path item. Return None if no hook could;
-   this tells our caller it should fall back to the builtin
-   import mechanism. Cache the result in path_importer_cache.
+   this tells our caller that the path based finder could not find
+   a finder for this path item. Cache the result in
+   path_importer_cache.
    Returns a borrowed reference. */
 
 static PyObject *
@@ -1040,8 +1040,8 @@ Create an extension module.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_create_builtin(PyModuleDef *module, PyObject *spec)
-/*[clinic end generated code: output=5038f467617226bd input=37f966f890384e47]*/
+_imp_create_builtin(PyObject *module, PyObject *spec)
+/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
 {
     struct _inittab *p;
     PyObject *name;
@@ -1056,7 +1056,7 @@ _imp_create_builtin(PyModuleDef *module, PyObject *spec)
     mod = _PyImport_FindExtensionObject(name, name);
     if (mod || PyErr_Occurred()) {
         Py_DECREF(name);
-        Py_INCREF(mod);
+        Py_XINCREF(mod);
         return mod;
     }
 
@@ -1068,7 +1068,7 @@ _imp_create_builtin(PyModuleDef *module, PyObject *spec)
 
     for (p = PyImport_Inittab; p->name != NULL; p++) {
         PyModuleDef *def;
-        if (PyUnicode_CompareWithASCIIString(name, p->name) == 0) {
+        if (_PyUnicode_EqualToASCIIString(name, p->name)) {
             if (p->initfunc == NULL) {
                 /* Cannot re-init internal module ("sys" or "builtins") */
                 mod = PyImport_AddModule(namestr);
@@ -1114,7 +1114,7 @@ find_frozen(PyObject *name)
     for (p = PyImport_FrozenModules; ; p++) {
         if (p->name == NULL)
             return NULL;
-        if (PyUnicode_CompareWithASCIIString(name, p->name) == 0)
+        if (_PyUnicode_EqualToASCIIString(name, p->name))
             break;
     }
     return p;
@@ -1315,12 +1315,8 @@ remove_importlib_frames(void)
         int now_in_importlib;
 
         assert(PyTraceBack_Check(tb));
-        now_in_importlib = (PyUnicode_CompareWithASCIIString(
-                                code->co_filename,
-                                importlib_filename) == 0) ||
-                           (PyUnicode_CompareWithASCIIString(
-                                code->co_filename,
-                                external_filename) == 0);
+        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
+                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
         if (now_in_importlib && !in_importlib) {
             /* This is the link to this chunk of importlib tracebacks */
             outer_link = prev_link;
@@ -1329,8 +1325,7 @@ remove_importlib_frames(void)
 
         if (in_importlib &&
             (always_trim ||
-             PyUnicode_CompareWithASCIIString(code->co_name,
-                                              remove_frames) == 0)) {
+             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
             PyObject *tmp = *outer_link;
             *outer_link = next;
             Py_XINCREF(next);
@@ -1438,6 +1433,7 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
             }
             else if (!PyUnicode_Check(package)) {
                 PyErr_SetString(PyExc_TypeError, "__name__ must be a string");
+                goto error;
             }
             Py_INCREF(package);
 
@@ -1525,15 +1521,13 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *given_globals,
     _PyImport_AcquireLock();
 #endif
    /* From this point forward, goto error_with_unlock! */
-    if (PyDict_Check(globals)) {
-        builtins_import = _PyDict_GetItemId(globals, &PyId___import__);
-    }
+    /* XXX interp->builtins_copy is NULL in subinterpreter! */
+    builtins_import = _PyDict_GetItemId(interp->builtins_copy ?
+                                        interp->builtins_copy :
+                                        interp->builtins, &PyId___import__);
     if (builtins_import == NULL) {
-        builtins_import = _PyDict_GetItemId(interp->builtins, &PyId___import__);
-        if (builtins_import == NULL) {
-            PyErr_SetString(PyExc_ImportError, "__import__ not found");
-            goto error_with_unlock;
-        }
+        PyErr_SetString(PyExc_ImportError, "__import__ not found");
+        goto error_with_unlock;
     }
     Py_INCREF(builtins_import);
 
@@ -1823,8 +1817,8 @@ Returns the list of file suffixes used to identify extension modules.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_extension_suffixes_impl(PyModuleDef *module)
-/*[clinic end generated code: output=d44c1566ef362229 input=ecdeeecfcb6f839e]*/
+_imp_extension_suffixes_impl(PyObject *module)
+/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
 {
     PyObject *list;
     const char *suffix;
@@ -1862,8 +1856,8 @@ Initializes a frozen module.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_init_frozen_impl(PyModuleDef *module, PyObject *name)
-/*[clinic end generated code: output=a9de493bdd711878 input=13019adfc04f3fb3]*/
+_imp_init_frozen_impl(PyObject *module, PyObject *name)
+/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
 {
     int ret;
     PyObject *m;
@@ -1890,8 +1884,8 @@ Create a code object for a frozen module.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_get_frozen_object_impl(PyModuleDef *module, PyObject *name)
-/*[clinic end generated code: output=3114c970a47f2e3c input=ed689bc05358fdbd]*/
+_imp_get_frozen_object_impl(PyObject *module, PyObject *name)
+/*[clinic end generated code: output=2568cc5b7aa0da63 input=ed689bc05358fdbd]*/
 {
     return get_frozen_object(name);
 }
@@ -1906,8 +1900,8 @@ Returns True if the module name is of a frozen package.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_is_frozen_package_impl(PyModuleDef *module, PyObject *name)
-/*[clinic end generated code: output=3e4cab802b56d649 input=81b6cdecd080fbb8]*/
+_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
+/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
 {
     return is_frozen_package(name);
 }
@@ -1922,8 +1916,8 @@ Returns True if the module name corresponds to a built-in module.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_is_builtin_impl(PyModuleDef *module, PyObject *name)
-/*[clinic end generated code: output=2deec9cac6fb9a7e input=86befdac021dd1c7]*/
+_imp_is_builtin_impl(PyObject *module, PyObject *name)
+/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
 {
     return PyLong_FromLong(is_builtin(name));
 }
@@ -1938,8 +1932,8 @@ Returns True if the module name corresponds to a frozen module.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_is_frozen_impl(PyModuleDef *module, PyObject *name)
-/*[clinic end generated code: output=7de8e260c8e36aed input=7301dbca1897d66b]*/
+_imp_is_frozen_impl(PyObject *module, PyObject *name)
+/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
 {
     const struct _frozen *p;
 
@@ -1988,8 +1982,8 @@ Create an extension module.
 [clinic start generated code]*/
 
 static PyObject *
-_imp_create_dynamic_impl(PyModuleDef *module, PyObject *spec, PyObject *file)
-/*[clinic end generated code: output=935cde5b3872d56d input=c31b954f4cf4e09d]*/
+_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
+/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
 {
     PyObject *mod, *name, *path;
     FILE *fp;
@@ -2043,8 +2037,8 @@ Initialize an extension module.
 [clinic start generated code]*/
 
 static int
-_imp_exec_dynamic_impl(PyModuleDef *module, PyObject *mod)
-/*[clinic end generated code: output=4b84f1301b22d4bd input=9fdbfcb250280d3a]*/
+_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
+/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
 {
     return exec_builtin_or_dynamic(mod);
 }
@@ -2062,8 +2056,8 @@ Initialize a built-in module.
 [clinic start generated code]*/
 
 static int
-_imp_exec_builtin_impl(PyModuleDef *module, PyObject *mod)
-/*[clinic end generated code: output=215e99876a27e284 input=7beed5a2f12a60ca]*/
+_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
+/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
 {
     return exec_builtin_or_dynamic(mod);
 }
index 1aa585d..ea4f0e7 100644 (file)
@@ -147,6 +147,10 @@ _PyImport_LoadDynamicModuleWithSpec(PyObject *spec, FILE *fp)
     /* Package context is needed for single-phase init */
     oldcontext = _Py_PackageContext;
     _Py_PackageContext = PyUnicode_AsUTF8(name_unicode);
+    if (_Py_PackageContext == NULL) {
+        _Py_PackageContext = oldcontext;
+        goto error;
+    }
     m = p0();
     _Py_PackageContext = oldcontext;
 
index 7f6b753..a5fc936 100644 (file)
@@ -1920,70 +1920,69 @@ const unsigned char _Py_M__importlib[] = {
     115,32,109,117,115,116,32,98,101,32,101,120,112,108,105,99,
     105,116,108,121,32,112,97,115,115,101,100,32,105,110,46,10,
     10,32,32,32,32,114,141,0,0,0,114,34,0,0,0,78,
-    114,62,0,0,0,41,1,122,9,95,119,97,114,110,105,110,
-    103,115,41,16,114,57,0,0,0,114,14,0,0,0,114,13,
-    0,0,0,114,21,0,0,0,218,5,105,116,101,109,115,114,
-    177,0,0,0,114,76,0,0,0,114,150,0,0,0,114,82,
-    0,0,0,114,160,0,0,0,114,132,0,0,0,114,137,0,
-    0,0,114,1,0,0,0,114,200,0,0,0,114,5,0,0,
-    0,114,77,0,0,0,41,12,218,10,115,121,115,95,109,111,
-    100,117,108,101,218,11,95,105,109,112,95,109,111,100,117,108,
-    101,90,11,109,111,100,117,108,101,95,116,121,112,101,114,15,
-    0,0,0,114,89,0,0,0,114,99,0,0,0,114,88,0,
-    0,0,90,11,115,101,108,102,95,109,111,100,117,108,101,90,
-    12,98,117,105,108,116,105,110,95,110,97,109,101,90,14,98,
-    117,105,108,116,105,110,95,109,111,100,117,108,101,90,13,116,
-    104,114,101,97,100,95,109,111,100,117,108,101,90,14,119,101,
-    97,107,114,101,102,95,109,111,100,117,108,101,114,10,0,0,
-    0,114,10,0,0,0,114,11,0,0,0,218,6,95,115,101,
-    116,117,112,61,4,0,0,115,50,0,0,0,0,9,6,1,
-    6,3,12,1,28,1,15,1,15,1,9,1,15,1,9,2,
-    3,1,15,1,17,3,13,1,13,1,15,1,15,2,13,1,
-    20,3,3,1,16,1,13,2,11,1,16,3,12,1,114,204,
-    0,0,0,99,2,0,0,0,0,0,0,0,3,0,0,0,
-    3,0,0,0,67,0,0,0,115,87,0,0,0,116,0,0,
-    124,0,0,124,1,0,131,2,0,1,116,1,0,106,2,0,
-    106,3,0,116,4,0,131,1,0,1,116,1,0,106,2,0,
-    106,3,0,116,5,0,131,1,0,1,100,1,0,100,2,0,
-    108,6,0,125,2,0,124,2,0,97,7,0,124,2,0,106,
-    8,0,116,1,0,106,9,0,116,10,0,25,131,1,0,1,
-    100,2,0,83,41,3,122,50,73,110,115,116,97,108,108,32,
-    105,109,112,111,114,116,108,105,98,32,97,115,32,116,104,101,
-    32,105,109,112,108,101,109,101,110,116,97,116,105,111,110,32,
-    111,102,32,105,109,112,111,114,116,46,114,33,0,0,0,78,
-    41,11,114,204,0,0,0,114,14,0,0,0,114,174,0,0,
-    0,114,113,0,0,0,114,150,0,0,0,114,160,0,0,0,
-    218,26,95,102,114,111,122,101,110,95,105,109,112,111,114,116,
-    108,105,98,95,101,120,116,101,114,110,97,108,114,119,0,0,
-    0,218,8,95,105,110,115,116,97,108,108,114,21,0,0,0,
-    114,1,0,0,0,41,3,114,202,0,0,0,114,203,0,0,
-    0,114,205,0,0,0,114,10,0,0,0,114,10,0,0,0,
-    114,11,0,0,0,114,206,0,0,0,108,4,0,0,115,12,
-    0,0,0,0,2,13,2,16,1,16,3,12,1,6,1,114,
-    206,0,0,0,41,51,114,3,0,0,0,114,119,0,0,0,
-    114,12,0,0,0,114,16,0,0,0,114,17,0,0,0,114,
-    59,0,0,0,114,41,0,0,0,114,48,0,0,0,114,31,
-    0,0,0,114,32,0,0,0,114,53,0,0,0,114,54,0,
-    0,0,114,56,0,0,0,114,63,0,0,0,114,65,0,0,
-    0,114,75,0,0,0,114,81,0,0,0,114,84,0,0,0,
-    114,90,0,0,0,114,101,0,0,0,114,102,0,0,0,114,
-    106,0,0,0,114,85,0,0,0,218,6,111,98,106,101,99,
-    116,90,9,95,80,79,80,85,76,65,84,69,114,132,0,0,
-    0,114,137,0,0,0,114,144,0,0,0,114,97,0,0,0,
-    114,86,0,0,0,114,148,0,0,0,114,149,0,0,0,114,
-    87,0,0,0,114,150,0,0,0,114,160,0,0,0,114,165,
-    0,0,0,114,171,0,0,0,114,173,0,0,0,114,176,0,
-    0,0,114,181,0,0,0,114,191,0,0,0,114,182,0,0,
-    0,114,184,0,0,0,114,185,0,0,0,114,186,0,0,0,
-    114,194,0,0,0,114,196,0,0,0,114,199,0,0,0,114,
-    200,0,0,0,114,204,0,0,0,114,206,0,0,0,114,10,
-    0,0,0,114,10,0,0,0,114,10,0,0,0,114,11,0,
-    0,0,218,8,60,109,111,100,117,108,101,62,8,0,0,0,
-    115,96,0,0,0,6,17,6,2,12,8,12,4,19,20,6,
-    2,6,3,22,4,19,68,19,21,19,19,12,19,12,19,12,
-    11,18,8,12,11,12,12,12,16,12,36,19,27,19,101,24,
-    26,9,3,18,45,18,60,12,18,12,17,12,25,12,29,12,
-    23,12,16,19,73,19,77,19,13,12,9,12,9,15,40,12,
-    17,6,1,10,2,12,27,12,6,18,24,12,32,12,15,24,
-    35,12,7,12,47,
+    114,62,0,0,0,41,1,114,141,0,0,0,41,16,114,57,
+    0,0,0,114,14,0,0,0,114,13,0,0,0,114,21,0,
+    0,0,218,5,105,116,101,109,115,114,177,0,0,0,114,76,
+    0,0,0,114,150,0,0,0,114,82,0,0,0,114,160,0,
+    0,0,114,132,0,0,0,114,137,0,0,0,114,1,0,0,
+    0,114,200,0,0,0,114,5,0,0,0,114,77,0,0,0,
+    41,12,218,10,115,121,115,95,109,111,100,117,108,101,218,11,
+    95,105,109,112,95,109,111,100,117,108,101,90,11,109,111,100,
+    117,108,101,95,116,121,112,101,114,15,0,0,0,114,89,0,
+    0,0,114,99,0,0,0,114,88,0,0,0,90,11,115,101,
+    108,102,95,109,111,100,117,108,101,90,12,98,117,105,108,116,
+    105,110,95,110,97,109,101,90,14,98,117,105,108,116,105,110,
+    95,109,111,100,117,108,101,90,13,116,104,114,101,97,100,95,
+    109,111,100,117,108,101,90,14,119,101,97,107,114,101,102,95,
+    109,111,100,117,108,101,114,10,0,0,0,114,10,0,0,0,
+    114,11,0,0,0,218,6,95,115,101,116,117,112,61,4,0,
+    0,115,50,0,0,0,0,9,6,1,6,3,12,1,28,1,
+    15,1,15,1,9,1,15,1,9,2,3,1,15,1,17,3,
+    13,1,13,1,15,1,15,2,13,1,20,3,3,1,16,1,
+    13,2,11,1,16,3,12,1,114,204,0,0,0,99,2,0,
+    0,0,0,0,0,0,3,0,0,0,3,0,0,0,67,0,
+    0,0,115,87,0,0,0,116,0,0,124,0,0,124,1,0,
+    131,2,0,1,116,1,0,106,2,0,106,3,0,116,4,0,
+    131,1,0,1,116,1,0,106,2,0,106,3,0,116,5,0,
+    131,1,0,1,100,1,0,100,2,0,108,6,0,125,2,0,
+    124,2,0,97,7,0,124,2,0,106,8,0,116,1,0,106,
+    9,0,116,10,0,25,131,1,0,1,100,2,0,83,41,3,
+    122,50,73,110,115,116,97,108,108,32,105,109,112,111,114,116,
+    108,105,98,32,97,115,32,116,104,101,32,105,109,112,108,101,
+    109,101,110,116,97,116,105,111,110,32,111,102,32,105,109,112,
+    111,114,116,46,114,33,0,0,0,78,41,11,114,204,0,0,
+    0,114,14,0,0,0,114,174,0,0,0,114,113,0,0,0,
+    114,150,0,0,0,114,160,0,0,0,218,26,95,102,114,111,
+    122,101,110,95,105,109,112,111,114,116,108,105,98,95,101,120,
+    116,101,114,110,97,108,114,119,0,0,0,218,8,95,105,110,
+    115,116,97,108,108,114,21,0,0,0,114,1,0,0,0,41,
+    3,114,202,0,0,0,114,203,0,0,0,114,205,0,0,0,
+    114,10,0,0,0,114,10,0,0,0,114,11,0,0,0,114,
+    206,0,0,0,108,4,0,0,115,12,0,0,0,0,2,13,
+    2,16,1,16,3,12,1,6,1,114,206,0,0,0,41,51,
+    114,3,0,0,0,114,119,0,0,0,114,12,0,0,0,114,
+    16,0,0,0,114,17,0,0,0,114,59,0,0,0,114,41,
+    0,0,0,114,48,0,0,0,114,31,0,0,0,114,32,0,
+    0,0,114,53,0,0,0,114,54,0,0,0,114,56,0,0,
+    0,114,63,0,0,0,114,65,0,0,0,114,75,0,0,0,
+    114,81,0,0,0,114,84,0,0,0,114,90,0,0,0,114,
+    101,0,0,0,114,102,0,0,0,114,106,0,0,0,114,85,
+    0,0,0,218,6,111,98,106,101,99,116,90,9,95,80,79,
+    80,85,76,65,84,69,114,132,0,0,0,114,137,0,0,0,
+    114,144,0,0,0,114,97,0,0,0,114,86,0,0,0,114,
+    148,0,0,0,114,149,0,0,0,114,87,0,0,0,114,150,
+    0,0,0,114,160,0,0,0,114,165,0,0,0,114,171,0,
+    0,0,114,173,0,0,0,114,176,0,0,0,114,181,0,0,
+    0,114,191,0,0,0,114,182,0,0,0,114,184,0,0,0,
+    114,185,0,0,0,114,186,0,0,0,114,194,0,0,0,114,
+    196,0,0,0,114,199,0,0,0,114,200,0,0,0,114,204,
+    0,0,0,114,206,0,0,0,114,10,0,0,0,114,10,0,
+    0,0,114,10,0,0,0,114,11,0,0,0,218,8,60,109,
+    111,100,117,108,101,62,8,0,0,0,115,96,0,0,0,6,
+    17,6,2,12,8,12,4,19,20,6,2,6,3,22,4,19,
+    68,19,21,19,19,12,19,12,19,12,11,18,8,12,11,12,
+    12,12,16,12,36,19,27,19,101,24,26,9,3,18,45,18,
+    60,12,18,12,17,12,25,12,29,12,23,12,16,19,73,19,
+    77,19,13,12,9,12,9,15,40,12,17,6,1,10,2,12,
+    27,12,6,18,24,12,32,12,15,24,35,12,7,12,47,
 };
index 47f5c62..5ee843a 100644 (file)
@@ -1,53 +1,54 @@
 /* Auto-generated by Programs/_freeze_importlib.c */
 const unsigned char _Py_M__importlib_external[] = {
     99,0,0,0,0,0,0,0,0,0,0,0,0,7,0,0,
-    0,64,0,0,0,115,228,2,0,0,100,0,0,90,0,0,
-    100,96,0,90,1,0,100,4,0,100,5,0,132,0,0,90,
-    2,0,100,6,0,100,7,0,132,0,0,90,3,0,100,8,
-    0,100,9,0,132,0,0,90,4,0,100,10,0,100,11,0,
-    132,0,0,90,5,0,100,12,0,100,13,0,132,0,0,90,
-    6,0,100,14,0,100,15,0,132,0,0,90,7,0,100,16,
-    0,100,17,0,132,0,0,90,8,0,100,18,0,100,19,0,
-    132,0,0,90,9,0,100,20,0,100,21,0,132,0,0,90,
-    10,0,100,22,0,100,23,0,100,24,0,132,1,0,90,11,
-    0,101,12,0,101,11,0,106,13,0,131,1,0,90,14,0,
-    100,25,0,106,15,0,100,26,0,100,27,0,131,2,0,100,
-    28,0,23,90,16,0,101,17,0,106,18,0,101,16,0,100,
-    27,0,131,2,0,90,19,0,100,29,0,90,20,0,100,30,
-    0,90,21,0,100,31,0,103,1,0,90,22,0,100,32,0,
-    103,1,0,90,23,0,101,23,0,4,90,24,0,90,25,0,
+    0,64,0,0,0,115,244,2,0,0,100,0,0,90,0,0,
+    100,96,0,90,1,0,100,97,0,90,2,0,101,2,0,101,
+    1,0,23,90,3,0,100,4,0,100,5,0,132,0,0,90,
+    4,0,100,6,0,100,7,0,132,0,0,90,5,0,100,8,
+    0,100,9,0,132,0,0,90,6,0,100,10,0,100,11,0,
+    132,0,0,90,7,0,100,12,0,100,13,0,132,0,0,90,
+    8,0,100,14,0,100,15,0,132,0,0,90,9,0,100,16,
+    0,100,17,0,132,0,0,90,10,0,100,18,0,100,19,0,
+    132,0,0,90,11,0,100,20,0,100,21,0,132,0,0,90,
+    12,0,100,22,0,100,23,0,100,24,0,132,1,0,90,13,
+    0,101,14,0,101,13,0,106,15,0,131,1,0,90,16,0,
+    100,25,0,106,17,0,100,26,0,100,27,0,131,2,0,100,
+    28,0,23,90,18,0,101,19,0,106,20,0,101,18,0,100,
+    27,0,131,2,0,90,21,0,100,29,0,90,22,0,100,30,
+    0,90,23,0,100,31,0,103,1,0,90,24,0,100,32,0,
+    103,1,0,90,25,0,101,25,0,4,90,26,0,90,27,0,
     100,33,0,100,34,0,100,33,0,100,35,0,100,36,0,132,
-    1,1,90,26,0,100,37,0,100,38,0,132,0,0,90,27,
-    0,100,39,0,100,40,0,132,0,0,90,28,0,100,41,0,
-    100,42,0,132,0,0,90,29,0,100,43,0,100,44,0,132,
-    0,0,90,30,0,100,45,0,100,46,0,100,47,0,100,48,
-    0,132,0,1,90,31,0,100,49,0,100,50,0,132,0,0,
-    90,32,0,100,51,0,100,52,0,132,0,0,90,33,0,100,
+    1,1,90,28,0,100,37,0,100,38,0,132,0,0,90,29,
+    0,100,39,0,100,40,0,132,0,0,90,30,0,100,41,0,
+    100,42,0,132,0,0,90,31,0,100,43,0,100,44,0,132,
+    0,0,90,32,0,100,45,0,100,46,0,100,47,0,100,48,
+    0,132,0,1,90,33,0,100,49,0,100,50,0,132,0,0,
+    90,34,0,100,51,0,100,52,0,132,0,0,90,35,0,100,
     33,0,100,33,0,100,33,0,100,53,0,100,54,0,132,3,
-    0,90,34,0,100,33,0,100,33,0,100,33,0,100,55,0,
-    100,56,0,132,3,0,90,35,0,100,57,0,100,57,0,100,
-    58,0,100,59,0,132,2,0,90,36,0,100,60,0,100,61,
-    0,132,0,0,90,37,0,101,38,0,131,0,0,90,39,0,
-    100,33,0,100,62,0,100,33,0,100,63,0,101,39,0,100,
-    64,0,100,65,0,132,1,2,90,40,0,71,100,66,0,100,
-    67,0,132,0,0,100,67,0,131,2,0,90,41,0,71,100,
-    68,0,100,69,0,132,0,0,100,69,0,131,2,0,90,42,
-    0,71,100,70,0,100,71,0,132,0,0,100,71,0,101,42,
-    0,131,3,0,90,43,0,71,100,72,0,100,73,0,132,0,
-    0,100,73,0,131,2,0,90,44,0,71,100,74,0,100,75,
-    0,132,0,0,100,75,0,101,44,0,101,43,0,131,4,0,
-    90,45,0,71,100,76,0,100,77,0,132,0,0,100,77,0,
-    101,44,0,101,42,0,131,4,0,90,46,0,103,0,0,90,
-    47,0,71,100,78,0,100,79,0,132,0,0,100,79,0,101,
-    44,0,101,42,0,131,4,0,90,48,0,71,100,80,0,100,
-    81,0,132,0,0,100,81,0,131,2,0,90,49,0,71,100,
-    82,0,100,83,0,132,0,0,100,83,0,131,2,0,90,50,
+    0,90,36,0,100,33,0,100,33,0,100,33,0,100,55,0,
+    100,56,0,132,3,0,90,37,0,100,57,0,100,57,0,100,
+    58,0,100,59,0,132,2,0,90,38,0,100,60,0,100,61,
+    0,132,0,0,90,39,0,101,40,0,131,0,0,90,41,0,
+    100,33,0,100,62,0,100,33,0,100,63,0,101,41,0,100,
+    64,0,100,65,0,132,1,2,90,42,0,71,100,66,0,100,
+    67,0,132,0,0,100,67,0,131,2,0,90,43,0,71,100,
+    68,0,100,69,0,132,0,0,100,69,0,131,2,0,90,44,
+    0,71,100,70,0,100,71,0,132,0,0,100,71,0,101,44,
+    0,131,3,0,90,45,0,71,100,72,0,100,73,0,132,0,
+    0,100,73,0,131,2,0,90,46,0,71,100,74,0,100,75,
+    0,132,0,0,100,75,0,101,46,0,101,45,0,131,4,0,
+    90,47,0,71,100,76,0,100,77,0,132,0,0,100,77,0,
+    101,46,0,101,44,0,131,4,0,90,48,0,103,0,0,90,
+    49,0,71,100,78,0,100,79,0,132,0,0,100,79,0,101,
+    46,0,101,44,0,131,4,0,90,50,0,71,100,80,0,100,
+    81,0,132,0,0,100,81,0,131,2,0,90,51,0,71,100,
+    82,0,100,83,0,132,0,0,100,83,0,131,2,0,90,52,
     0,71,100,84,0,100,85,0,132,0,0,100,85,0,131,2,
-    0,90,51,0,71,100,86,0,100,87,0,132,0,0,100,87,
-    0,131,2,0,90,52,0,100,33,0,100,88,0,100,89,0,
-    132,1,0,90,53,0,100,90,0,100,91,0,132,0,0,90,
-    54,0,100,92,0,100,93,0,132,0,0,90,55,0,100,94,
-    0,100,95,0,132,0,0,90,56,0,100,33,0,83,41,97,
+    0,90,53,0,71,100,86,0,100,87,0,132,0,0,100,87,
+    0,131,2,0,90,54,0,100,33,0,100,88,0,100,89,0,
+    132,1,0,90,55,0,100,90,0,100,91,0,132,0,0,90,
+    56,0,100,92,0,100,93,0,132,0,0,90,57,0,100,94,
+    0,100,95,0,132,0,0,90,58,0,100,33,0,83,41,98,
     97,94,1,0,0,67,111,114,101,32,105,109,112,108,101,109,
     101,110,116,97,116,105,111,110,32,111,102,32,112,97,116,104,
     45,98,97,115,101,100,32,105,109,112,111,114,116,46,10,10,
@@ -72,2525 +73,2533 @@ const unsigned char _Py_M__importlib_external[] = {
     110,32,111,102,32,116,104,105,115,32,109,111,100,117,108,101,
     46,10,10,218,3,119,105,110,218,6,99,121,103,119,105,110,
     218,6,100,97,114,119,105,110,99,0,0,0,0,0,0,0,
-    0,1,0,0,0,2,0,0,0,67,0,0,0,115,49,0,
+    0,1,0,0,0,3,0,0,0,3,0,0,0,115,88,0,
     0,0,116,0,0,106,1,0,106,2,0,116,3,0,131,1,
-    0,114,33,0,100,1,0,100,2,0,132,0,0,125,0,0,
-    110,12,0,100,3,0,100,2,0,132,0,0,125,0,0,124,
-    0,0,83,41,4,78,99,0,0,0,0,0,0,0,0,0,
-    0,0,0,2,0,0,0,83,0,0,0,115,13,0,0,0,
-    100,1,0,116,0,0,106,1,0,107,6,0,83,41,2,122,
-    53,84,114,117,101,32,105,102,32,102,105,108,101,110,97,109,
-    101,115,32,109,117,115,116,32,98,101,32,99,104,101,99,107,
-    101,100,32,99,97,115,101,45,105,110,115,101,110,115,105,116,
-    105,118,101,108,121,46,115,12,0,0,0,80,89,84,72,79,
-    78,67,65,83,69,79,75,41,2,218,3,95,111,115,90,7,
-    101,110,118,105,114,111,110,169,0,114,4,0,0,0,114,4,
-    0,0,0,250,38,60,102,114,111,122,101,110,32,105,109,112,
-    111,114,116,108,105,98,46,95,98,111,111,116,115,116,114,97,
-    112,95,101,120,116,101,114,110,97,108,62,218,11,95,114,101,
-    108,97,120,95,99,97,115,101,30,0,0,0,115,2,0,0,
-    0,0,2,122,37,95,109,97,107,101,95,114,101,108,97,120,
-    95,99,97,115,101,46,60,108,111,99,97,108,115,62,46,95,
-    114,101,108,97,120,95,99,97,115,101,99,0,0,0,0,0,
-    0,0,0,0,0,0,0,1,0,0,0,83,0,0,0,115,
-    4,0,0,0,100,1,0,83,41,2,122,53,84,114,117,101,
-    32,105,102,32,102,105,108,101,110,97,109,101,115,32,109,117,
-    115,116,32,98,101,32,99,104,101,99,107,101,100,32,99,97,
-    115,101,45,105,110,115,101,110,115,105,116,105,118,101,108,121,
-    46,70,114,4,0,0,0,114,4,0,0,0,114,4,0,0,
-    0,114,4,0,0,0,114,5,0,0,0,114,6,0,0,0,
-    34,0,0,0,115,2,0,0,0,0,2,41,4,218,3,115,
-    121,115,218,8,112,108,97,116,102,111,114,109,218,10,115,116,
-    97,114,116,115,119,105,116,104,218,27,95,67,65,83,69,95,
-    73,78,83,69,78,83,73,84,73,86,69,95,80,76,65,84,
-    70,79,82,77,83,41,1,114,6,0,0,0,114,4,0,0,
-    0,114,4,0,0,0,114,5,0,0,0,218,16,95,109,97,
-    107,101,95,114,101,108,97,120,95,99,97,115,101,28,0,0,
-    0,115,8,0,0,0,0,1,18,1,15,4,12,3,114,11,
-    0,0,0,99,1,0,0,0,0,0,0,0,1,0,0,0,
-    3,0,0,0,67,0,0,0,115,26,0,0,0,116,0,0,
-    124,0,0,131,1,0,100,1,0,64,106,1,0,100,2,0,
-    100,3,0,131,2,0,83,41,4,122,42,67,111,110,118,101,
-    114,116,32,97,32,51,50,45,98,105,116,32,105,110,116,101,
-    103,101,114,32,116,111,32,108,105,116,116,108,101,45,101,110,
-    100,105,97,110,46,108,3,0,0,0,255,127,255,127,3,0,
-    233,4,0,0,0,218,6,108,105,116,116,108,101,41,2,218,
-    3,105,110,116,218,8,116,111,95,98,121,116,101,115,41,1,
-    218,1,120,114,4,0,0,0,114,4,0,0,0,114,5,0,
-    0,0,218,7,95,119,95,108,111,110,103,40,0,0,0,115,
-    2,0,0,0,0,2,114,17,0,0,0,99,1,0,0,0,
-    0,0,0,0,1,0,0,0,3,0,0,0,67,0,0,0,
-    115,16,0,0,0,116,0,0,106,1,0,124,0,0,100,1,
-    0,131,2,0,83,41,2,122,47,67,111,110,118,101,114,116,
-    32,52,32,98,121,116,101,115,32,105,110,32,108,105,116,116,
-    108,101,45,101,110,100,105,97,110,32,116,111,32,97,110,32,
-    105,110,116,101,103,101,114,46,114,13,0,0,0,41,2,114,
-    14,0,0,0,218,10,102,114,111,109,95,98,121,116,101,115,
-    41,1,90,9,105,110,116,95,98,121,116,101,115,114,4,0,
-    0,0,114,4,0,0,0,114,5,0,0,0,218,7,95,114,
-    95,108,111,110,103,45,0,0,0,115,2,0,0,0,0,2,
-    114,19,0,0,0,99,0,0,0,0,0,0,0,0,1,0,
-    0,0,3,0,0,0,71,0,0,0,115,26,0,0,0,116,
-    0,0,106,1,0,100,1,0,100,2,0,132,0,0,124,0,
-    0,68,131,1,0,131,1,0,83,41,3,122,31,82,101,112,
-    108,97,99,101,109,101,110,116,32,102,111,114,32,111,115,46,
-    112,97,116,104,46,106,111,105,110,40,41,46,99,1,0,0,
-    0,0,0,0,0,2,0,0,0,4,0,0,0,83,0,0,
-    0,115,37,0,0,0,103,0,0,124,0,0,93,27,0,125,
-    1,0,124,1,0,114,6,0,124,1,0,106,0,0,116,1,
-    0,131,1,0,145,2,0,113,6,0,83,114,4,0,0,0,
-    41,2,218,6,114,115,116,114,105,112,218,15,112,97,116,104,
-    95,115,101,112,97,114,97,116,111,114,115,41,2,218,2,46,
-    48,218,4,112,97,114,116,114,4,0,0,0,114,4,0,0,
-    0,114,5,0,0,0,250,10,60,108,105,115,116,99,111,109,
-    112,62,52,0,0,0,115,2,0,0,0,9,1,122,30,95,
-    112,97,116,104,95,106,111,105,110,46,60,108,111,99,97,108,
-    115,62,46,60,108,105,115,116,99,111,109,112,62,41,2,218,
-    8,112,97,116,104,95,115,101,112,218,4,106,111,105,110,41,
-    1,218,10,112,97,116,104,95,112,97,114,116,115,114,4,0,
-    0,0,114,4,0,0,0,114,5,0,0,0,218,10,95,112,
-    97,116,104,95,106,111,105,110,50,0,0,0,115,4,0,0,
-    0,0,2,15,1,114,28,0,0,0,99,1,0,0,0,0,
-    0,0,0,5,0,0,0,5,0,0,0,67,0,0,0,115,
-    134,0,0,0,116,0,0,116,1,0,131,1,0,100,1,0,
-    107,2,0,114,52,0,124,0,0,106,2,0,116,3,0,131,
-    1,0,92,3,0,125,1,0,125,2,0,125,3,0,124,1,
-    0,124,3,0,102,2,0,83,120,69,0,116,4,0,124,0,
-    0,131,1,0,68,93,55,0,125,4,0,124,4,0,116,1,
-    0,107,6,0,114,65,0,124,0,0,106,5,0,124,4,0,
-    100,2,0,100,1,0,131,1,1,92,2,0,125,1,0,125,
-    3,0,124,1,0,124,3,0,102,2,0,83,113,65,0,87,
-    100,3,0,124,0,0,102,2,0,83,41,4,122,32,82,101,
-    112,108,97,99,101,109,101,110,116,32,102,111,114,32,111,115,
-    46,112,97,116,104,46,115,112,108,105,116,40,41,46,233,1,
-    0,0,0,90,8,109,97,120,115,112,108,105,116,218,0,41,
-    6,218,3,108,101,110,114,21,0,0,0,218,10,114,112,97,
-    114,116,105,116,105,111,110,114,25,0,0,0,218,8,114,101,
-    118,101,114,115,101,100,218,6,114,115,112,108,105,116,41,5,
-    218,4,112,97,116,104,90,5,102,114,111,110,116,218,1,95,
-    218,4,116,97,105,108,114,16,0,0,0,114,4,0,0,0,
-    114,4,0,0,0,114,5,0,0,0,218,11,95,112,97,116,
-    104,95,115,112,108,105,116,56,0,0,0,115,16,0,0,0,
-    0,2,18,1,24,1,10,1,19,1,12,1,27,1,14,1,
-    114,38,0,0,0,99,1,0,0,0,0,0,0,0,1,0,
-    0,0,2,0,0,0,67,0,0,0,115,13,0,0,0,116,
-    0,0,106,1,0,124,0,0,131,1,0,83,41,1,122,126,
-    83,116,97,116,32,116,104,101,32,112,97,116,104,46,10,10,
-    32,32,32,32,77,97,100,101,32,97,32,115,101,112,97,114,
-    97,116,101,32,102,117,110,99,116,105,111,110,32,116,111,32,
-    109,97,107,101,32,105,116,32,101,97,115,105,101,114,32,116,
-    111,32,111,118,101,114,114,105,100,101,32,105,110,32,101,120,
-    112,101,114,105,109,101,110,116,115,10,32,32,32,32,40,101,
-    46,103,46,32,99,97,99,104,101,32,115,116,97,116,32,114,
-    101,115,117,108,116,115,41,46,10,10,32,32,32,32,41,2,
-    114,3,0,0,0,90,4,115,116,97,116,41,1,114,35,0,
-    0,0,114,4,0,0,0,114,4,0,0,0,114,5,0,0,
-    0,218,10,95,112,97,116,104,95,115,116,97,116,68,0,0,
-    0,115,2,0,0,0,0,7,114,39,0,0,0,99,2,0,
-    0,0,0,0,0,0,3,0,0,0,11,0,0,0,67,0,
-    0,0,115,58,0,0,0,121,16,0,116,0,0,124,0,0,
-    131,1,0,125,2,0,87,110,22,0,4,116,1,0,107,10,
-    0,114,40,0,1,1,1,100,1,0,83,89,110,1,0,88,
-    124,2,0,106,2,0,100,2,0,64,124,1,0,107,2,0,
-    83,41,3,122,49,84,101,115,116,32,119,104,101,116,104,101,
-    114,32,116,104,101,32,112,97,116,104,32,105,115,32,116,104,
-    101,32,115,112,101,99,105,102,105,101,100,32,109,111,100,101,
-    32,116,121,112,101,46,70,105,0,240,0,0,41,3,114,39,
-    0,0,0,218,7,79,83,69,114,114,111,114,218,7,115,116,
-    95,109,111,100,101,41,3,114,35,0,0,0,218,4,109,111,
-    100,101,90,9,115,116,97,116,95,105,110,102,111,114,4,0,
-    0,0,114,4,0,0,0,114,5,0,0,0,218,18,95,112,
-    97,116,104,95,105,115,95,109,111,100,101,95,116,121,112,101,
-    78,0,0,0,115,10,0,0,0,0,2,3,1,16,1,13,
-    1,9,1,114,43,0,0,0,99,1,0,0,0,0,0,0,
-    0,1,0,0,0,3,0,0,0,67,0,0,0,115,13,0,
-    0,0,116,0,0,124,0,0,100,1,0,131,2,0,83,41,
-    2,122,31,82,101,112,108,97,99,101,109,101,110,116,32,102,
-    111,114,32,111,115,46,112,97,116,104,46,105,115,102,105,108,
-    101,46,105,0,128,0,0,41,1,114,43,0,0,0,41,1,
-    114,35,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,218,12,95,112,97,116,104,95,105,115,102,105,
-    108,101,87,0,0,0,115,2,0,0,0,0,2,114,44,0,
-    0,0,99,1,0,0,0,0,0,0,0,1,0,0,0,3,
-    0,0,0,67,0,0,0,115,31,0,0,0,124,0,0,115,
-    18,0,116,0,0,106,1,0,131,0,0,125,0,0,116,2,
-    0,124,0,0,100,1,0,131,2,0,83,41,2,122,30,82,
-    101,112,108,97,99,101,109,101,110,116,32,102,111,114,32,111,
-    115,46,112,97,116,104,46,105,115,100,105,114,46,105,0,64,
-    0,0,41,3,114,3,0,0,0,218,6,103,101,116,99,119,
-    100,114,43,0,0,0,41,1,114,35,0,0,0,114,4,0,
-    0,0,114,4,0,0,0,114,5,0,0,0,218,11,95,112,
-    97,116,104,95,105,115,100,105,114,92,0,0,0,115,6,0,
-    0,0,0,2,6,1,12,1,114,46,0,0,0,105,182,1,
-    0,0,99,3,0,0,0,0,0,0,0,6,0,0,0,17,
-    0,0,0,67,0,0,0,115,193,0,0,0,100,1,0,106,
-    0,0,124,0,0,116,1,0,124,0,0,131,1,0,131,2,
-    0,125,3,0,116,2,0,106,3,0,124,3,0,116,2,0,
-    106,4,0,116,2,0,106,5,0,66,116,2,0,106,6,0,
-    66,124,2,0,100,2,0,64,131,3,0,125,4,0,121,61,
-    0,116,7,0,106,8,0,124,4,0,100,3,0,131,2,0,
-    143,20,0,125,5,0,124,5,0,106,9,0,124,1,0,131,
-    1,0,1,87,100,4,0,81,82,88,116,2,0,106,10,0,
-    124,3,0,124,0,0,131,2,0,1,87,110,59,0,4,116,
-    11,0,107,10,0,114,188,0,1,1,1,121,17,0,116,2,
-    0,106,12,0,124,3,0,131,1,0,1,87,110,18,0,4,
-    116,11,0,107,10,0,114,180,0,1,1,1,89,110,1,0,
-    88,130,0,0,89,110,1,0,88,100,4,0,83,41,5,122,
-    162,66,101,115,116,45,101,102,102,111,114,116,32,102,117,110,
-    99,116,105,111,110,32,116,111,32,119,114,105,116,101,32,100,
-    97,116,97,32,116,111,32,97,32,112,97,116,104,32,97,116,
-    111,109,105,99,97,108,108,121,46,10,32,32,32,32,66,101,
-    32,112,114,101,112,97,114,101,100,32,116,111,32,104,97,110,
-    100,108,101,32,97,32,70,105,108,101,69,120,105,115,116,115,
-    69,114,114,111,114,32,105,102,32,99,111,110,99,117,114,114,
-    101,110,116,32,119,114,105,116,105,110,103,32,111,102,32,116,
-    104,101,10,32,32,32,32,116,101,109,112,111,114,97,114,121,
-    32,102,105,108,101,32,105,115,32,97,116,116,101,109,112,116,
-    101,100,46,122,5,123,125,46,123,125,105,182,1,0,0,90,
-    2,119,98,78,41,13,218,6,102,111,114,109,97,116,218,2,
-    105,100,114,3,0,0,0,90,4,111,112,101,110,90,6,79,
-    95,69,88,67,76,90,7,79,95,67,82,69,65,84,90,8,
-    79,95,87,82,79,78,76,89,218,3,95,105,111,218,6,70,
-    105,108,101,73,79,218,5,119,114,105,116,101,218,7,114,101,
-    112,108,97,99,101,114,40,0,0,0,90,6,117,110,108,105,
-    110,107,41,6,114,35,0,0,0,218,4,100,97,116,97,114,
-    42,0,0,0,90,8,112,97,116,104,95,116,109,112,90,2,
-    102,100,218,4,102,105,108,101,114,4,0,0,0,114,4,0,
-    0,0,114,5,0,0,0,218,13,95,119,114,105,116,101,95,
-    97,116,111,109,105,99,99,0,0,0,115,26,0,0,0,0,
-    5,24,1,9,1,33,1,3,3,21,1,20,1,20,1,13,
-    1,3,1,17,1,13,1,5,1,114,55,0,0,0,105,22,
-    13,0,0,233,2,0,0,0,114,13,0,0,0,115,2,0,
-    0,0,13,10,90,11,95,95,112,121,99,97,99,104,101,95,
-    95,122,4,111,112,116,45,122,3,46,112,121,122,4,46,112,
-    121,99,78,218,12,111,112,116,105,109,105,122,97,116,105,111,
-    110,99,2,0,0,0,1,0,0,0,11,0,0,0,6,0,
-    0,0,67,0,0,0,115,87,1,0,0,124,1,0,100,1,
-    0,107,9,0,114,76,0,116,0,0,106,1,0,100,2,0,
-    116,2,0,131,2,0,1,124,2,0,100,1,0,107,9,0,
-    114,58,0,100,3,0,125,3,0,116,3,0,124,3,0,131,
-    1,0,130,1,0,124,1,0,114,70,0,100,4,0,110,3,
-    0,100,5,0,125,2,0,116,4,0,124,0,0,131,1,0,
-    92,2,0,125,4,0,125,5,0,124,5,0,106,5,0,100,
-    6,0,131,1,0,92,3,0,125,6,0,125,7,0,125,8,
-    0,116,6,0,106,7,0,106,8,0,125,9,0,124,9,0,
-    100,1,0,107,8,0,114,154,0,116,9,0,100,7,0,131,
-    1,0,130,1,0,100,4,0,106,10,0,124,6,0,114,172,
-    0,124,6,0,110,3,0,124,8,0,124,7,0,124,9,0,
-    103,3,0,131,1,0,125,10,0,124,2,0,100,1,0,107,
-    8,0,114,241,0,116,6,0,106,11,0,106,12,0,100,8,
-    0,107,2,0,114,229,0,100,4,0,125,2,0,110,12,0,
-    116,6,0,106,11,0,106,12,0,125,2,0,116,13,0,124,
-    2,0,131,1,0,125,2,0,124,2,0,100,4,0,107,3,
-    0,114,63,1,124,2,0,106,14,0,131,0,0,115,42,1,
-    116,15,0,100,9,0,106,16,0,124,2,0,131,1,0,131,
-    1,0,130,1,0,100,10,0,106,16,0,124,10,0,116,17,
-    0,124,2,0,131,3,0,125,10,0,116,18,0,124,4,0,
-    116,19,0,124,10,0,116,20,0,100,8,0,25,23,131,3,
-    0,83,41,11,97,254,2,0,0,71,105,118,101,110,32,116,
-    104,101,32,112,97,116,104,32,116,111,32,97,32,46,112,121,
-    32,102,105,108,101,44,32,114,101,116,117,114,110,32,116,104,
-    101,32,112,97,116,104,32,116,111,32,105,116,115,32,46,112,
-    121,99,32,102,105,108,101,46,10,10,32,32,32,32,84,104,
-    101,32,46,112,121,32,102,105,108,101,32,100,111,101,115,32,
-    110,111,116,32,110,101,101,100,32,116,111,32,101,120,105,115,
-    116,59,32,116,104,105,115,32,115,105,109,112,108,121,32,114,
-    101,116,117,114,110,115,32,116,104,101,32,112,97,116,104,32,
-    116,111,32,116,104,101,10,32,32,32,32,46,112,121,99,32,
-    102,105,108,101,32,99,97,108,99,117,108,97,116,101,100,32,
-    97,115,32,105,102,32,116,104,101,32,46,112,121,32,102,105,
-    108,101,32,119,101,114,101,32,105,109,112,111,114,116,101,100,
-    46,10,10,32,32,32,32,84,104,101,32,39,111,112,116,105,
-    109,105,122,97,116,105,111,110,39,32,112,97,114,97,109,101,
-    116,101,114,32,99,111,110,116,114,111,108,115,32,116,104,101,
-    32,112,114,101,115,117,109,101,100,32,111,112,116,105,109,105,
-    122,97,116,105,111,110,32,108,101,118,101,108,32,111,102,10,
-    32,32,32,32,116,104,101,32,98,121,116,101,99,111,100,101,
-    32,102,105,108,101,46,32,73,102,32,39,111,112,116,105,109,
-    105,122,97,116,105,111,110,39,32,105,115,32,110,111,116,32,
-    78,111,110,101,44,32,116,104,101,32,115,116,114,105,110,103,
-    32,114,101,112,114,101,115,101,110,116,97,116,105,111,110,10,
-    32,32,32,32,111,102,32,116,104,101,32,97,114,103,117,109,
-    101,110,116,32,105,115,32,116,97,107,101,110,32,97,110,100,
-    32,118,101,114,105,102,105,101,100,32,116,111,32,98,101,32,
-    97,108,112,104,97,110,117,109,101,114,105,99,32,40,101,108,
-    115,101,32,86,97,108,117,101,69,114,114,111,114,10,32,32,
-    32,32,105,115,32,114,97,105,115,101,100,41,46,10,10,32,
-    32,32,32,84,104,101,32,100,101,98,117,103,95,111,118,101,
-    114,114,105,100,101,32,112,97,114,97,109,101,116,101,114,32,
-    105,115,32,100,101,112,114,101,99,97,116,101,100,46,32,73,
-    102,32,100,101,98,117,103,95,111,118,101,114,114,105,100,101,
-    32,105,115,32,110,111,116,32,78,111,110,101,44,10,32,32,
-    32,32,97,32,84,114,117,101,32,118,97,108,117,101,32,105,
-    115,32,116,104,101,32,115,97,109,101,32,97,115,32,115,101,
-    116,116,105,110,103,32,39,111,112,116,105,109,105,122,97,116,
-    105,111,110,39,32,116,111,32,116,104,101,32,101,109,112,116,
-    121,32,115,116,114,105,110,103,10,32,32,32,32,119,104,105,
-    108,101,32,97,32,70,97,108,115,101,32,118,97,108,117,101,
-    32,105,115,32,101,113,117,105,118,97,108,101,110,116,32,116,
-    111,32,115,101,116,116,105,110,103,32,39,111,112,116,105,109,
-    105,122,97,116,105,111,110,39,32,116,111,32,39,49,39,46,
-    10,10,32,32,32,32,73,102,32,115,121,115,46,105,109,112,
-    108,101,109,101,110,116,97,116,105,111,110,46,99,97,99,104,
-    101,95,116,97,103,32,105,115,32,78,111,110,101,32,116,104,
-    101,110,32,78,111,116,73,109,112,108,101,109,101,110,116,101,
-    100,69,114,114,111,114,32,105,115,32,114,97,105,115,101,100,
-    46,10,10,32,32,32,32,78,122,70,116,104,101,32,100,101,
-    98,117,103,95,111,118,101,114,114,105,100,101,32,112,97,114,
-    97,109,101,116,101,114,32,105,115,32,100,101,112,114,101,99,
-    97,116,101,100,59,32,117,115,101,32,39,111,112,116,105,109,
-    105,122,97,116,105,111,110,39,32,105,110,115,116,101,97,100,
-    122,50,100,101,98,117,103,95,111,118,101,114,114,105,100,101,
-    32,111,114,32,111,112,116,105,109,105,122,97,116,105,111,110,
-    32,109,117,115,116,32,98,101,32,115,101,116,32,116,111,32,
-    78,111,110,101,114,30,0,0,0,114,29,0,0,0,218,1,
-    46,122,36,115,121,115,46,105,109,112,108,101,109,101,110,116,
-    97,116,105,111,110,46,99,97,99,104,101,95,116,97,103,32,
-    105,115,32,78,111,110,101,233,0,0,0,0,122,24,123,33,
-    114,125,32,105,115,32,110,111,116,32,97,108,112,104,97,110,
-    117,109,101,114,105,99,122,7,123,125,46,123,125,123,125,41,
-    21,218,9,95,119,97,114,110,105,110,103,115,218,4,119,97,
-    114,110,218,18,68,101,112,114,101,99,97,116,105,111,110,87,
-    97,114,110,105,110,103,218,9,84,121,112,101,69,114,114,111,
-    114,114,38,0,0,0,114,32,0,0,0,114,7,0,0,0,
-    218,14,105,109,112,108,101,109,101,110,116,97,116,105,111,110,
-    218,9,99,97,99,104,101,95,116,97,103,218,19,78,111,116,
-    73,109,112,108,101,109,101,110,116,101,100,69,114,114,111,114,
-    114,26,0,0,0,218,5,102,108,97,103,115,218,8,111,112,
-    116,105,109,105,122,101,218,3,115,116,114,218,7,105,115,97,
-    108,110,117,109,218,10,86,97,108,117,101,69,114,114,111,114,
-    114,47,0,0,0,218,4,95,79,80,84,114,28,0,0,0,
-    218,8,95,80,89,67,65,67,72,69,218,17,66,89,84,69,
-    67,79,68,69,95,83,85,70,70,73,88,69,83,41,11,114,
-    35,0,0,0,90,14,100,101,98,117,103,95,111,118,101,114,
-    114,105,100,101,114,57,0,0,0,218,7,109,101,115,115,97,
-    103,101,218,4,104,101,97,100,114,37,0,0,0,90,4,98,
-    97,115,101,218,3,115,101,112,218,4,114,101,115,116,90,3,
-    116,97,103,90,15,97,108,109,111,115,116,95,102,105,108,101,
-    110,97,109,101,114,4,0,0,0,114,4,0,0,0,114,5,
-    0,0,0,218,17,99,97,99,104,101,95,102,114,111,109,95,
-    115,111,117,114,99,101,246,0,0,0,115,46,0,0,0,0,
-    18,12,1,9,1,7,1,12,1,6,1,12,1,18,1,18,
-    1,24,1,12,1,12,1,12,1,36,1,12,1,18,1,9,
-    2,12,1,12,1,12,1,12,1,21,1,21,1,114,79,0,
-    0,0,99,1,0,0,0,0,0,0,0,8,0,0,0,5,
-    0,0,0,67,0,0,0,115,62,1,0,0,116,0,0,106,
-    1,0,106,2,0,100,1,0,107,8,0,114,30,0,116,3,
-    0,100,2,0,131,1,0,130,1,0,116,4,0,124,0,0,
-    131,1,0,92,2,0,125,1,0,125,2,0,116,4,0,124,
-    1,0,131,1,0,92,2,0,125,1,0,125,3,0,124,3,
-    0,116,5,0,107,3,0,114,102,0,116,6,0,100,3,0,
-    106,7,0,116,5,0,124,0,0,131,2,0,131,1,0,130,
-    1,0,124,2,0,106,8,0,100,4,0,131,1,0,125,4,
-    0,124,4,0,100,11,0,107,7,0,114,153,0,116,6,0,
-    100,7,0,106,7,0,124,2,0,131,1,0,131,1,0,130,
-    1,0,110,125,0,124,4,0,100,6,0,107,2,0,114,22,
-    1,124,2,0,106,9,0,100,4,0,100,5,0,131,2,0,
-    100,12,0,25,125,5,0,124,5,0,106,10,0,116,11,0,
-    131,1,0,115,223,0,116,6,0,100,8,0,106,7,0,116,
-    11,0,131,1,0,131,1,0,130,1,0,124,5,0,116,12,
-    0,116,11,0,131,1,0,100,1,0,133,2,0,25,125,6,
-    0,124,6,0,106,13,0,131,0,0,115,22,1,116,6,0,
-    100,9,0,106,7,0,124,5,0,131,1,0,131,1,0,130,
-    1,0,124,2,0,106,14,0,100,4,0,131,1,0,100,10,
-    0,25,125,7,0,116,15,0,124,1,0,124,7,0,116,16,
-    0,100,10,0,25,23,131,2,0,83,41,13,97,110,1,0,
-    0,71,105,118,101,110,32,116,104,101,32,112,97,116,104,32,
-    116,111,32,97,32,46,112,121,99,46,32,102,105,108,101,44,
-    32,114,101,116,117,114,110,32,116,104,101,32,112,97,116,104,
-    32,116,111,32,105,116,115,32,46,112,121,32,102,105,108,101,
-    46,10,10,32,32,32,32,84,104,101,32,46,112,121,99,32,
-    102,105,108,101,32,100,111,101,115,32,110,111,116,32,110,101,
-    101,100,32,116,111,32,101,120,105,115,116,59,32,116,104,105,
-    115,32,115,105,109,112,108,121,32,114,101,116,117,114,110,115,
-    32,116,104,101,32,112,97,116,104,32,116,111,10,32,32,32,
-    32,116,104,101,32,46,112,121,32,102,105,108,101,32,99,97,
-    108,99,117,108,97,116,101,100,32,116,111,32,99,111,114,114,
-    101,115,112,111,110,100,32,116,111,32,116,104,101,32,46,112,
-    121,99,32,102,105,108,101,46,32,32,73,102,32,112,97,116,
-    104,32,100,111,101,115,10,32,32,32,32,110,111,116,32,99,
-    111,110,102,111,114,109,32,116,111,32,80,69,80,32,51,49,
-    52,55,47,52,56,56,32,102,111,114,109,97,116,44,32,86,
-    97,108,117,101,69,114,114,111,114,32,119,105,108,108,32,98,
-    101,32,114,97,105,115,101,100,46,32,73,102,10,32,32,32,
-    32,115,121,115,46,105,109,112,108,101,109,101,110,116,97,116,
-    105,111,110,46,99,97,99,104,101,95,116,97,103,32,105,115,
-    32,78,111,110,101,32,116,104,101,110,32,78,111,116,73,109,
-    112,108,101,109,101,110,116,101,100,69,114,114,111,114,32,105,
-    115,32,114,97,105,115,101,100,46,10,10,32,32,32,32,78,
-    122,36,115,121,115,46,105,109,112,108,101,109,101,110,116,97,
-    116,105,111,110,46,99,97,99,104,101,95,116,97,103,32,105,
-    115,32,78,111,110,101,122,37,123,125,32,110,111,116,32,98,
-    111,116,116,111,109,45,108,101,118,101,108,32,100,105,114,101,
-    99,116,111,114,121,32,105,110,32,123,33,114,125,114,58,0,
-    0,0,114,56,0,0,0,233,3,0,0,0,122,33,101,120,
-    112,101,99,116,101,100,32,111,110,108,121,32,50,32,111,114,
-    32,51,32,100,111,116,115,32,105,110,32,123,33,114,125,122,
-    57,111,112,116,105,109,105,122,97,116,105,111,110,32,112,111,
-    114,116,105,111,110,32,111,102,32,102,105,108,101,110,97,109,
-    101,32,100,111,101,115,32,110,111,116,32,115,116,97,114,116,
-    32,119,105,116,104,32,123,33,114,125,122,52,111,112,116,105,
-    109,105,122,97,116,105,111,110,32,108,101,118,101,108,32,123,
-    33,114,125,32,105,115,32,110,111,116,32,97,110,32,97,108,
-    112,104,97,110,117,109,101,114,105,99,32,118,97,108,117,101,
-    114,59,0,0,0,62,2,0,0,0,114,56,0,0,0,114,
-    80,0,0,0,233,254,255,255,255,41,17,114,7,0,0,0,
-    114,64,0,0,0,114,65,0,0,0,114,66,0,0,0,114,
-    38,0,0,0,114,73,0,0,0,114,71,0,0,0,114,47,
-    0,0,0,218,5,99,111,117,110,116,114,34,0,0,0,114,
-    9,0,0,0,114,72,0,0,0,114,31,0,0,0,114,70,
-    0,0,0,218,9,112,97,114,116,105,116,105,111,110,114,28,
-    0,0,0,218,15,83,79,85,82,67,69,95,83,85,70,70,
-    73,88,69,83,41,8,114,35,0,0,0,114,76,0,0,0,
-    90,16,112,121,99,97,99,104,101,95,102,105,108,101,110,97,
-    109,101,90,7,112,121,99,97,99,104,101,90,9,100,111,116,
-    95,99,111,117,110,116,114,57,0,0,0,90,9,111,112,116,
-    95,108,101,118,101,108,90,13,98,97,115,101,95,102,105,108,
-    101,110,97,109,101,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,218,17,115,111,117,114,99,101,95,102,114,111,
-    109,95,99,97,99,104,101,34,1,0,0,115,44,0,0,0,
-    0,9,18,1,12,1,18,1,18,1,12,1,9,1,15,1,
-    15,1,12,1,9,1,15,1,12,1,22,1,15,1,9,1,
-    12,1,22,1,12,1,9,1,12,1,19,1,114,85,0,0,
-    0,99,1,0,0,0,0,0,0,0,5,0,0,0,12,0,
-    0,0,67,0,0,0,115,164,0,0,0,116,0,0,124,0,
-    0,131,1,0,100,1,0,107,2,0,114,22,0,100,2,0,
-    83,124,0,0,106,1,0,100,3,0,131,1,0,92,3,0,
-    125,1,0,125,2,0,125,3,0,124,1,0,12,115,81,0,
-    124,3,0,106,2,0,131,0,0,100,7,0,100,8,0,133,
-    2,0,25,100,6,0,107,3,0,114,85,0,124,0,0,83,
-    121,16,0,116,3,0,124,0,0,131,1,0,125,4,0,87,
-    110,40,0,4,116,4,0,116,5,0,102,2,0,107,10,0,
-    114,143,0,1,1,1,124,0,0,100,2,0,100,9,0,133,
-    2,0,25,125,4,0,89,110,1,0,88,116,6,0,124,4,
-    0,131,1,0,114,160,0,124,4,0,83,124,0,0,83,41,
-    10,122,188,67,111,110,118,101,114,116,32,97,32,98,121,116,
-    101,99,111,100,101,32,102,105,108,101,32,112,97,116,104,32,
-    116,111,32,97,32,115,111,117,114,99,101,32,112,97,116,104,
-    32,40,105,102,32,112,111,115,115,105,98,108,101,41,46,10,
-    10,32,32,32,32,84,104,105,115,32,102,117,110,99,116,105,
-    111,110,32,101,120,105,115,116,115,32,112,117,114,101,108,121,
-    32,102,111,114,32,98,97,99,107,119,97,114,100,115,45,99,
-    111,109,112,97,116,105,98,105,108,105,116,121,32,102,111,114,
-    10,32,32,32,32,80,121,73,109,112,111,114,116,95,69,120,
-    101,99,67,111,100,101,77,111,100,117,108,101,87,105,116,104,
-    70,105,108,101,110,97,109,101,115,40,41,32,105,110,32,116,
-    104,101,32,67,32,65,80,73,46,10,10,32,32,32,32,114,
-    59,0,0,0,78,114,58,0,0,0,114,80,0,0,0,114,
-    29,0,0,0,90,2,112,121,233,253,255,255,255,233,255,255,
-    255,255,114,87,0,0,0,41,7,114,31,0,0,0,114,32,
-    0,0,0,218,5,108,111,119,101,114,114,85,0,0,0,114,
-    66,0,0,0,114,71,0,0,0,114,44,0,0,0,41,5,
-    218,13,98,121,116,101,99,111,100,101,95,112,97,116,104,114,
-    78,0,0,0,114,36,0,0,0,90,9,101,120,116,101,110,
-    115,105,111,110,218,11,115,111,117,114,99,101,95,112,97,116,
-    104,114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,
-    218,15,95,103,101,116,95,115,111,117,114,99,101,102,105,108,
-    101,67,1,0,0,115,20,0,0,0,0,7,18,1,4,1,
-    24,1,35,1,4,1,3,1,16,1,19,1,21,1,114,91,
-    0,0,0,99,1,0,0,0,0,0,0,0,1,0,0,0,
-    11,0,0,0,67,0,0,0,115,92,0,0,0,124,0,0,
-    106,0,0,116,1,0,116,2,0,131,1,0,131,1,0,114,
-    59,0,121,14,0,116,3,0,124,0,0,131,1,0,83,87,
-    113,88,0,4,116,4,0,107,10,0,114,55,0,1,1,1,
-    89,113,88,0,88,110,29,0,124,0,0,106,0,0,116,1,
-    0,116,5,0,131,1,0,131,1,0,114,84,0,124,0,0,
-    83,100,0,0,83,100,0,0,83,41,1,78,41,6,218,8,
-    101,110,100,115,119,105,116,104,218,5,116,117,112,108,101,114,
-    84,0,0,0,114,79,0,0,0,114,66,0,0,0,114,74,
-    0,0,0,41,1,218,8,102,105,108,101,110,97,109,101,114,
-    4,0,0,0,114,4,0,0,0,114,5,0,0,0,218,11,
-    95,103,101,116,95,99,97,99,104,101,100,86,1,0,0,115,
-    16,0,0,0,0,1,21,1,3,1,14,1,13,1,8,1,
-    21,1,4,2,114,95,0,0,0,99,1,0,0,0,0,0,
-    0,0,2,0,0,0,11,0,0,0,67,0,0,0,115,60,
-    0,0,0,121,19,0,116,0,0,124,0,0,131,1,0,106,
-    1,0,125,1,0,87,110,24,0,4,116,2,0,107,10,0,
-    114,45,0,1,1,1,100,1,0,125,1,0,89,110,1,0,
-    88,124,1,0,100,2,0,79,125,1,0,124,1,0,83,41,
-    3,122,51,67,97,108,99,117,108,97,116,101,32,116,104,101,
-    32,109,111,100,101,32,112,101,114,109,105,115,115,105,111,110,
-    115,32,102,111,114,32,97,32,98,121,116,101,99,111,100,101,
-    32,102,105,108,101,46,105,182,1,0,0,233,128,0,0,0,
-    41,3,114,39,0,0,0,114,41,0,0,0,114,40,0,0,
-    0,41,2,114,35,0,0,0,114,42,0,0,0,114,4,0,
-    0,0,114,4,0,0,0,114,5,0,0,0,218,10,95,99,
-    97,108,99,95,109,111,100,101,98,1,0,0,115,12,0,0,
-    0,0,2,3,1,19,1,13,1,11,3,10,1,114,97,0,
-    0,0,218,9,118,101,114,98,111,115,105,116,121,114,29,0,
-    0,0,99,1,0,0,0,1,0,0,0,3,0,0,0,4,
-    0,0,0,71,0,0,0,115,75,0,0,0,116,0,0,106,
-    1,0,106,2,0,124,1,0,107,5,0,114,71,0,124,0,
-    0,106,3,0,100,6,0,131,1,0,115,43,0,100,3,0,
-    124,0,0,23,125,0,0,116,4,0,124,0,0,106,5,0,
-    124,2,0,140,0,0,100,4,0,116,0,0,106,6,0,131,
-    1,1,1,100,5,0,83,41,7,122,61,80,114,105,110,116,
-    32,116,104,101,32,109,101,115,115,97,103,101,32,116,111,32,
-    115,116,100,101,114,114,32,105,102,32,45,118,47,80,89,84,
-    72,79,78,86,69,82,66,79,83,69,32,105,115,32,116,117,
-    114,110,101,100,32,111,110,46,250,1,35,250,7,105,109,112,
-    111,114,116,32,122,2,35,32,114,54,0,0,0,78,41,2,
-    114,99,0,0,0,114,100,0,0,0,41,7,114,7,0,0,
-    0,114,67,0,0,0,218,7,118,101,114,98,111,115,101,114,
-    9,0,0,0,218,5,112,114,105,110,116,114,47,0,0,0,
-    218,6,115,116,100,101,114,114,41,3,114,75,0,0,0,114,
-    98,0,0,0,218,4,97,114,103,115,114,4,0,0,0,114,
-    4,0,0,0,114,5,0,0,0,218,16,95,118,101,114,98,
-    111,115,101,95,109,101,115,115,97,103,101,110,1,0,0,115,
-    8,0,0,0,0,2,18,1,15,1,10,1,114,105,0,0,
-    0,99,1,0,0,0,0,0,0,0,3,0,0,0,11,0,
-    0,0,3,0,0,0,115,84,0,0,0,100,1,0,135,0,
-    0,102,1,0,100,2,0,100,3,0,134,1,0,125,1,0,
-    121,13,0,116,0,0,106,1,0,125,2,0,87,110,30,0,
-    4,116,2,0,107,10,0,114,66,0,1,1,1,100,4,0,
-    100,5,0,132,0,0,125,2,0,89,110,1,0,88,124,2,
-    0,124,1,0,136,0,0,131,2,0,1,124,1,0,83,41,
-    6,122,252,68,101,99,111,114,97,116,111,114,32,116,111,32,
-    118,101,114,105,102,121,32,116,104,97,116,32,116,104,101,32,
-    109,111,100,117,108,101,32,98,101,105,110,103,32,114,101,113,
-    117,101,115,116,101,100,32,109,97,116,99,104,101,115,32,116,
-    104,101,32,111,110,101,32,116,104,101,10,32,32,32,32,108,
-    111,97,100,101,114,32,99,97,110,32,104,97,110,100,108,101,
-    46,10,10,32,32,32,32,84,104,101,32,102,105,114,115,116,
-    32,97,114,103,117,109,101,110,116,32,40,115,101,108,102,41,
-    32,109,117,115,116,32,100,101,102,105,110,101,32,95,110,97,
-    109,101,32,119,104,105,99,104,32,116,104,101,32,115,101,99,
-    111,110,100,32,97,114,103,117,109,101,110,116,32,105,115,10,
-    32,32,32,32,99,111,109,112,97,114,101,100,32,97,103,97,
-    105,110,115,116,46,32,73,102,32,116,104,101,32,99,111,109,
-    112,97,114,105,115,111,110,32,102,97,105,108,115,32,116,104,
-    101,110,32,73,109,112,111,114,116,69,114,114,111,114,32,105,
-    115,32,114,97,105,115,101,100,46,10,10,32,32,32,32,78,
-    99,2,0,0,0,0,0,0,0,4,0,0,0,5,0,0,
-    0,31,0,0,0,115,89,0,0,0,124,1,0,100,0,0,
-    107,8,0,114,24,0,124,0,0,106,0,0,125,1,0,110,
-    46,0,124,0,0,106,0,0,124,1,0,107,3,0,114,70,
-    0,116,1,0,100,1,0,124,0,0,106,0,0,124,1,0,
-    102,2,0,22,100,2,0,124,1,0,131,1,1,130,1,0,
-    136,0,0,124,0,0,124,1,0,124,2,0,124,3,0,142,
-    2,0,83,41,3,78,122,30,108,111,97,100,101,114,32,102,
-    111,114,32,37,115,32,99,97,110,110,111,116,32,104,97,110,
-    100,108,101,32,37,115,218,4,110,97,109,101,41,2,114,106,
-    0,0,0,218,11,73,109,112,111,114,116,69,114,114,111,114,
-    41,4,218,4,115,101,108,102,114,106,0,0,0,114,104,0,
-    0,0,90,6,107,119,97,114,103,115,41,1,218,6,109,101,
-    116,104,111,100,114,4,0,0,0,114,5,0,0,0,218,19,
-    95,99,104,101,99,107,95,110,97,109,101,95,119,114,97,112,
-    112,101,114,126,1,0,0,115,12,0,0,0,0,1,12,1,
-    12,1,15,1,6,1,25,1,122,40,95,99,104,101,99,107,
-    95,110,97,109,101,46,60,108,111,99,97,108,115,62,46,95,
-    99,104,101,99,107,95,110,97,109,101,95,119,114,97,112,112,
-    101,114,99,2,0,0,0,0,0,0,0,3,0,0,0,7,
-    0,0,0,83,0,0,0,115,92,0,0,0,120,66,0,100,
-    1,0,100,2,0,100,3,0,100,4,0,103,4,0,68,93,
-    46,0,125,2,0,116,0,0,124,1,0,124,2,0,131,2,
-    0,114,19,0,116,1,0,124,0,0,124,2,0,116,2,0,
-    124,1,0,124,2,0,131,2,0,131,3,0,1,113,19,0,
-    87,124,0,0,106,3,0,106,4,0,124,1,0,106,3,0,
-    131,1,0,1,100,0,0,83,41,5,78,218,10,95,95,109,
-    111,100,117,108,101,95,95,218,8,95,95,110,97,109,101,95,
-    95,218,12,95,95,113,117,97,108,110,97,109,101,95,95,218,
-    7,95,95,100,111,99,95,95,41,5,218,7,104,97,115,97,
-    116,116,114,218,7,115,101,116,97,116,116,114,218,7,103,101,
-    116,97,116,116,114,218,8,95,95,100,105,99,116,95,95,218,
-    6,117,112,100,97,116,101,41,3,90,3,110,101,119,90,3,
-    111,108,100,114,52,0,0,0,114,4,0,0,0,114,4,0,
-    0,0,114,5,0,0,0,218,5,95,119,114,97,112,137,1,
-    0,0,115,8,0,0,0,0,1,25,1,15,1,29,1,122,
-    26,95,99,104,101,99,107,95,110,97,109,101,46,60,108,111,
-    99,97,108,115,62,46,95,119,114,97,112,41,3,218,10,95,
-    98,111,111,116,115,116,114,97,112,114,120,0,0,0,218,9,
-    78,97,109,101,69,114,114,111,114,41,3,114,109,0,0,0,
-    114,110,0,0,0,114,120,0,0,0,114,4,0,0,0,41,
-    1,114,109,0,0,0,114,5,0,0,0,218,11,95,99,104,
-    101,99,107,95,110,97,109,101,118,1,0,0,115,14,0,0,
-    0,0,8,21,7,3,1,13,1,13,2,17,5,13,1,114,
-    123,0,0,0,99,2,0,0,0,0,0,0,0,5,0,0,
-    0,4,0,0,0,67,0,0,0,115,84,0,0,0,124,0,
-    0,106,0,0,124,1,0,131,1,0,92,2,0,125,2,0,
-    125,3,0,124,2,0,100,1,0,107,8,0,114,80,0,116,
-    1,0,124,3,0,131,1,0,114,80,0,100,2,0,125,4,
-    0,116,2,0,106,3,0,124,4,0,106,4,0,124,3,0,
-    100,3,0,25,131,1,0,116,5,0,131,2,0,1,124,2,
-    0,83,41,4,122,155,84,114,121,32,116,111,32,102,105,110,
-    100,32,97,32,108,111,97,100,101,114,32,102,111,114,32,116,
-    104,101,32,115,112,101,99,105,102,105,101,100,32,109,111,100,
-    117,108,101,32,98,121,32,100,101,108,101,103,97,116,105,110,
-    103,32,116,111,10,32,32,32,32,115,101,108,102,46,102,105,
-    110,100,95,108,111,97,100,101,114,40,41,46,10,10,32,32,
-    32,32,84,104,105,115,32,109,101,116,104,111,100,32,105,115,
-    32,100,101,112,114,101,99,97,116,101,100,32,105,110,32,102,
-    97,118,111,114,32,111,102,32,102,105,110,100,101,114,46,102,
-    105,110,100,95,115,112,101,99,40,41,46,10,10,32,32,32,
-    32,78,122,44,78,111,116,32,105,109,112,111,114,116,105,110,
-    103,32,100,105,114,101,99,116,111,114,121,32,123,125,58,32,
-    109,105,115,115,105,110,103,32,95,95,105,110,105,116,95,95,
-    114,59,0,0,0,41,6,218,11,102,105,110,100,95,108,111,
-    97,100,101,114,114,31,0,0,0,114,60,0,0,0,114,61,
-    0,0,0,114,47,0,0,0,218,13,73,109,112,111,114,116,
-    87,97,114,110,105,110,103,41,5,114,108,0,0,0,218,8,
-    102,117,108,108,110,97,109,101,218,6,108,111,97,100,101,114,
-    218,8,112,111,114,116,105,111,110,115,218,3,109,115,103,114,
-    4,0,0,0,114,4,0,0,0,114,5,0,0,0,218,17,
-    95,102,105,110,100,95,109,111,100,117,108,101,95,115,104,105,
-    109,146,1,0,0,115,10,0,0,0,0,10,21,1,24,1,
-    6,1,29,1,114,130,0,0,0,99,4,0,0,0,0,0,
-    0,0,11,0,0,0,19,0,0,0,67,0,0,0,115,240,
-    1,0,0,105,0,0,125,4,0,124,2,0,100,1,0,107,
-    9,0,114,31,0,124,2,0,124,4,0,100,2,0,60,110,
-    6,0,100,3,0,125,2,0,124,3,0,100,1,0,107,9,
-    0,114,59,0,124,3,0,124,4,0,100,4,0,60,124,0,
-    0,100,1,0,100,5,0,133,2,0,25,125,5,0,124,0,
-    0,100,5,0,100,6,0,133,2,0,25,125,6,0,124,0,
-    0,100,6,0,100,7,0,133,2,0,25,125,7,0,124,5,
-    0,116,0,0,107,3,0,114,168,0,100,8,0,106,1,0,
-    124,2,0,124,5,0,131,2,0,125,8,0,116,2,0,100,
-    9,0,124,8,0,131,2,0,1,116,3,0,124,8,0,124,
-    4,0,141,1,0,130,1,0,110,119,0,116,4,0,124,6,
-    0,131,1,0,100,5,0,107,3,0,114,229,0,100,10,0,
+    0,114,72,0,116,0,0,106,1,0,106,2,0,116,4,0,
+    131,1,0,114,45,0,100,1,0,137,0,0,110,6,0,100,
+    2,0,137,0,0,135,0,0,102,1,0,100,3,0,100,4,
+    0,134,0,0,125,0,0,110,12,0,100,5,0,100,4,0,
+    132,0,0,125,0,0,124,0,0,83,41,6,78,90,12,80,
+    89,84,72,79,78,67,65,83,69,79,75,115,12,0,0,0,
+    80,89,84,72,79,78,67,65,83,69,79,75,99,0,0,0,
+    0,0,0,0,0,0,0,0,0,2,0,0,0,19,0,0,
+    0,115,13,0,0,0,136,0,0,116,0,0,106,1,0,107,
+    6,0,83,41,1,122,53,84,114,117,101,32,105,102,32,102,
+    105,108,101,110,97,109,101,115,32,109,117,115,116,32,98,101,
+    32,99,104,101,99,107,101,100,32,99,97,115,101,45,105,110,
+    115,101,110,115,105,116,105,118,101,108,121,46,41,2,218,3,
+    95,111,115,90,7,101,110,118,105,114,111,110,169,0,41,1,
+    218,3,107,101,121,114,4,0,0,0,250,38,60,102,114,111,
+    122,101,110,32,105,109,112,111,114,116,108,105,98,46,95,98,
+    111,111,116,115,116,114,97,112,95,101,120,116,101,114,110,97,
+    108,62,218,11,95,114,101,108,97,120,95,99,97,115,101,37,
+    0,0,0,115,2,0,0,0,0,2,122,37,95,109,97,107,
+    101,95,114,101,108,97,120,95,99,97,115,101,46,60,108,111,
+    99,97,108,115,62,46,95,114,101,108,97,120,95,99,97,115,
+    101,99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
+    0,0,83,0,0,0,115,4,0,0,0,100,1,0,83,41,
+    2,122,53,84,114,117,101,32,105,102,32,102,105,108,101,110,
+    97,109,101,115,32,109,117,115,116,32,98,101,32,99,104,101,
+    99,107,101,100,32,99,97,115,101,45,105,110,115,101,110,115,
+    105,116,105,118,101,108,121,46,70,114,4,0,0,0,114,4,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,114,7,0,0,0,41,0,0,0,115,2,0,0,0,
+    0,2,41,5,218,3,115,121,115,218,8,112,108,97,116,102,
+    111,114,109,218,10,115,116,97,114,116,115,119,105,116,104,218,
+    27,95,67,65,83,69,95,73,78,83,69,78,83,73,84,73,
+    86,69,95,80,76,65,84,70,79,82,77,83,218,35,95,67,
+    65,83,69,95,73,78,83,69,78,83,73,84,73,86,69,95,
+    80,76,65,84,70,79,82,77,83,95,83,84,82,95,75,69,
+    89,41,1,114,7,0,0,0,114,4,0,0,0,41,1,114,
+    5,0,0,0,114,6,0,0,0,218,16,95,109,97,107,101,
+    95,114,101,108,97,120,95,99,97,115,101,30,0,0,0,115,
+    14,0,0,0,0,1,18,1,18,1,9,2,6,2,21,4,
+    12,3,114,13,0,0,0,99,1,0,0,0,0,0,0,0,
+    1,0,0,0,3,0,0,0,67,0,0,0,115,26,0,0,
+    0,116,0,0,124,0,0,131,1,0,100,1,0,64,106,1,
+    0,100,2,0,100,3,0,131,2,0,83,41,4,122,42,67,
+    111,110,118,101,114,116,32,97,32,51,50,45,98,105,116,32,
+    105,110,116,101,103,101,114,32,116,111,32,108,105,116,116,108,
+    101,45,101,110,100,105,97,110,46,108,3,0,0,0,255,127,
+    255,127,3,0,233,4,0,0,0,218,6,108,105,116,116,108,
+    101,41,2,218,3,105,110,116,218,8,116,111,95,98,121,116,
+    101,115,41,1,218,1,120,114,4,0,0,0,114,4,0,0,
+    0,114,6,0,0,0,218,7,95,119,95,108,111,110,103,47,
+    0,0,0,115,2,0,0,0,0,2,114,19,0,0,0,99,
+    1,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0,
+    67,0,0,0,115,16,0,0,0,116,0,0,106,1,0,124,
+    0,0,100,1,0,131,2,0,83,41,2,122,47,67,111,110,
+    118,101,114,116,32,52,32,98,121,116,101,115,32,105,110,32,
+    108,105,116,116,108,101,45,101,110,100,105,97,110,32,116,111,
+    32,97,110,32,105,110,116,101,103,101,114,46,114,15,0,0,
+    0,41,2,114,16,0,0,0,218,10,102,114,111,109,95,98,
+    121,116,101,115,41,1,90,9,105,110,116,95,98,121,116,101,
+    115,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    218,7,95,114,95,108,111,110,103,52,0,0,0,115,2,0,
+    0,0,0,2,114,21,0,0,0,99,0,0,0,0,0,0,
+    0,0,1,0,0,0,3,0,0,0,71,0,0,0,115,26,
+    0,0,0,116,0,0,106,1,0,100,1,0,100,2,0,132,
+    0,0,124,0,0,68,131,1,0,131,1,0,83,41,3,122,
+    31,82,101,112,108,97,99,101,109,101,110,116,32,102,111,114,
+    32,111,115,46,112,97,116,104,46,106,111,105,110,40,41,46,
+    99,1,0,0,0,0,0,0,0,2,0,0,0,4,0,0,
+    0,83,0,0,0,115,37,0,0,0,103,0,0,124,0,0,
+    93,27,0,125,1,0,124,1,0,114,6,0,124,1,0,106,
+    0,0,116,1,0,131,1,0,145,2,0,113,6,0,83,114,
+    4,0,0,0,41,2,218,6,114,115,116,114,105,112,218,15,
+    112,97,116,104,95,115,101,112,97,114,97,116,111,114,115,41,
+    2,218,2,46,48,218,4,112,97,114,116,114,4,0,0,0,
+    114,4,0,0,0,114,6,0,0,0,250,10,60,108,105,115,
+    116,99,111,109,112,62,59,0,0,0,115,2,0,0,0,9,
+    1,122,30,95,112,97,116,104,95,106,111,105,110,46,60,108,
+    111,99,97,108,115,62,46,60,108,105,115,116,99,111,109,112,
+    62,41,2,218,8,112,97,116,104,95,115,101,112,218,4,106,
+    111,105,110,41,1,218,10,112,97,116,104,95,112,97,114,116,
+    115,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    218,10,95,112,97,116,104,95,106,111,105,110,57,0,0,0,
+    115,4,0,0,0,0,2,15,1,114,30,0,0,0,99,1,
+    0,0,0,0,0,0,0,5,0,0,0,5,0,0,0,67,
+    0,0,0,115,134,0,0,0,116,0,0,116,1,0,131,1,
+    0,100,1,0,107,2,0,114,52,0,124,0,0,106,2,0,
+    116,3,0,131,1,0,92,3,0,125,1,0,125,2,0,125,
+    3,0,124,1,0,124,3,0,102,2,0,83,120,69,0,116,
+    4,0,124,0,0,131,1,0,68,93,55,0,125,4,0,124,
+    4,0,116,1,0,107,6,0,114,65,0,124,0,0,106,5,
+    0,124,4,0,100,2,0,100,1,0,131,1,1,92,2,0,
+    125,1,0,125,3,0,124,1,0,124,3,0,102,2,0,83,
+    113,65,0,87,100,3,0,124,0,0,102,2,0,83,41,4,
+    122,32,82,101,112,108,97,99,101,109,101,110,116,32,102,111,
+    114,32,111,115,46,112,97,116,104,46,115,112,108,105,116,40,
+    41,46,233,1,0,0,0,90,8,109,97,120,115,112,108,105,
+    116,218,0,41,6,218,3,108,101,110,114,23,0,0,0,218,
+    10,114,112,97,114,116,105,116,105,111,110,114,27,0,0,0,
+    218,8,114,101,118,101,114,115,101,100,218,6,114,115,112,108,
+    105,116,41,5,218,4,112,97,116,104,90,5,102,114,111,110,
+    116,218,1,95,218,4,116,97,105,108,114,18,0,0,0,114,
+    4,0,0,0,114,4,0,0,0,114,6,0,0,0,218,11,
+    95,112,97,116,104,95,115,112,108,105,116,63,0,0,0,115,
+    16,0,0,0,0,2,18,1,24,1,10,1,19,1,12,1,
+    27,1,14,1,114,40,0,0,0,99,1,0,0,0,0,0,
+    0,0,1,0,0,0,2,0,0,0,67,0,0,0,115,13,
+    0,0,0,116,0,0,106,1,0,124,0,0,131,1,0,83,
+    41,1,122,126,83,116,97,116,32,116,104,101,32,112,97,116,
+    104,46,10,10,32,32,32,32,77,97,100,101,32,97,32,115,
+    101,112,97,114,97,116,101,32,102,117,110,99,116,105,111,110,
+    32,116,111,32,109,97,107,101,32,105,116,32,101,97,115,105,
+    101,114,32,116,111,32,111,118,101,114,114,105,100,101,32,105,
+    110,32,101,120,112,101,114,105,109,101,110,116,115,10,32,32,
+    32,32,40,101,46,103,46,32,99,97,99,104,101,32,115,116,
+    97,116,32,114,101,115,117,108,116,115,41,46,10,10,32,32,
+    32,32,41,2,114,3,0,0,0,90,4,115,116,97,116,41,
+    1,114,37,0,0,0,114,4,0,0,0,114,4,0,0,0,
+    114,6,0,0,0,218,10,95,112,97,116,104,95,115,116,97,
+    116,75,0,0,0,115,2,0,0,0,0,7,114,41,0,0,
+    0,99,2,0,0,0,0,0,0,0,3,0,0,0,11,0,
+    0,0,67,0,0,0,115,58,0,0,0,121,16,0,116,0,
+    0,124,0,0,131,1,0,125,2,0,87,110,22,0,4,116,
+    1,0,107,10,0,114,40,0,1,1,1,100,1,0,83,89,
+    110,1,0,88,124,2,0,106,2,0,100,2,0,64,124,1,
+    0,107,2,0,83,41,3,122,49,84,101,115,116,32,119,104,
+    101,116,104,101,114,32,116,104,101,32,112,97,116,104,32,105,
+    115,32,116,104,101,32,115,112,101,99,105,102,105,101,100,32,
+    109,111,100,101,32,116,121,112,101,46,70,105,0,240,0,0,
+    41,3,114,41,0,0,0,218,7,79,83,69,114,114,111,114,
+    218,7,115,116,95,109,111,100,101,41,3,114,37,0,0,0,
+    218,4,109,111,100,101,90,9,115,116,97,116,95,105,110,102,
+    111,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    218,18,95,112,97,116,104,95,105,115,95,109,111,100,101,95,
+    116,121,112,101,85,0,0,0,115,10,0,0,0,0,2,3,
+    1,16,1,13,1,9,1,114,45,0,0,0,99,1,0,0,
+    0,0,0,0,0,1,0,0,0,3,0,0,0,67,0,0,
+    0,115,13,0,0,0,116,0,0,124,0,0,100,1,0,131,
+    2,0,83,41,2,122,31,82,101,112,108,97,99,101,109,101,
+    110,116,32,102,111,114,32,111,115,46,112,97,116,104,46,105,
+    115,102,105,108,101,46,105,0,128,0,0,41,1,114,45,0,
+    0,0,41,1,114,37,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,12,95,112,97,116,104,95,
+    105,115,102,105,108,101,94,0,0,0,115,2,0,0,0,0,
+    2,114,46,0,0,0,99,1,0,0,0,0,0,0,0,1,
+    0,0,0,3,0,0,0,67,0,0,0,115,31,0,0,0,
+    124,0,0,115,18,0,116,0,0,106,1,0,131,0,0,125,
+    0,0,116,2,0,124,0,0,100,1,0,131,2,0,83,41,
+    2,122,30,82,101,112,108,97,99,101,109,101,110,116,32,102,
+    111,114,32,111,115,46,112,97,116,104,46,105,115,100,105,114,
+    46,105,0,64,0,0,41,3,114,3,0,0,0,218,6,103,
+    101,116,99,119,100,114,45,0,0,0,41,1,114,37,0,0,
+    0,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    218,11,95,112,97,116,104,95,105,115,100,105,114,99,0,0,
+    0,115,6,0,0,0,0,2,6,1,12,1,114,48,0,0,
+    0,105,182,1,0,0,99,3,0,0,0,0,0,0,0,6,
+    0,0,0,17,0,0,0,67,0,0,0,115,193,0,0,0,
+    100,1,0,106,0,0,124,0,0,116,1,0,124,0,0,131,
+    1,0,131,2,0,125,3,0,116,2,0,106,3,0,124,3,
+    0,116,2,0,106,4,0,116,2,0,106,5,0,66,116,2,
+    0,106,6,0,66,124,2,0,100,2,0,64,131,3,0,125,
+    4,0,121,61,0,116,7,0,106,8,0,124,4,0,100,3,
+    0,131,2,0,143,20,0,125,5,0,124,5,0,106,9,0,
+    124,1,0,131,1,0,1,87,100,4,0,81,82,88,116,2,
+    0,106,10,0,124,3,0,124,0,0,131,2,0,1,87,110,
+    59,0,4,116,11,0,107,10,0,114,188,0,1,1,1,121,
+    17,0,116,2,0,106,12,0,124,3,0,131,1,0,1,87,
+    110,18,0,4,116,11,0,107,10,0,114,180,0,1,1,1,
+    89,110,1,0,88,130,0,0,89,110,1,0,88,100,4,0,
+    83,41,5,122,162,66,101,115,116,45,101,102,102,111,114,116,
+    32,102,117,110,99,116,105,111,110,32,116,111,32,119,114,105,
+    116,101,32,100,97,116,97,32,116,111,32,97,32,112,97,116,
+    104,32,97,116,111,109,105,99,97,108,108,121,46,10,32,32,
+    32,32,66,101,32,112,114,101,112,97,114,101,100,32,116,111,
+    32,104,97,110,100,108,101,32,97,32,70,105,108,101,69,120,
+    105,115,116,115,69,114,114,111,114,32,105,102,32,99,111,110,
+    99,117,114,114,101,110,116,32,119,114,105,116,105,110,103,32,
+    111,102,32,116,104,101,10,32,32,32,32,116,101,109,112,111,
+    114,97,114,121,32,102,105,108,101,32,105,115,32,97,116,116,
+    101,109,112,116,101,100,46,122,5,123,125,46,123,125,105,182,
+    1,0,0,90,2,119,98,78,41,13,218,6,102,111,114,109,
+    97,116,218,2,105,100,114,3,0,0,0,90,4,111,112,101,
+    110,90,6,79,95,69,88,67,76,90,7,79,95,67,82,69,
+    65,84,90,8,79,95,87,82,79,78,76,89,218,3,95,105,
+    111,218,6,70,105,108,101,73,79,218,5,119,114,105,116,101,
+    218,7,114,101,112,108,97,99,101,114,42,0,0,0,90,6,
+    117,110,108,105,110,107,41,6,114,37,0,0,0,218,4,100,
+    97,116,97,114,44,0,0,0,90,8,112,97,116,104,95,116,
+    109,112,90,2,102,100,218,4,102,105,108,101,114,4,0,0,
+    0,114,4,0,0,0,114,6,0,0,0,218,13,95,119,114,
+    105,116,101,95,97,116,111,109,105,99,106,0,0,0,115,26,
+    0,0,0,0,5,24,1,9,1,33,1,3,3,21,1,20,
+    1,20,1,13,1,3,1,17,1,13,1,5,1,114,57,0,
+    0,0,105,23,13,0,0,233,2,0,0,0,114,15,0,0,
+    0,115,2,0,0,0,13,10,90,11,95,95,112,121,99,97,
+    99,104,101,95,95,122,4,111,112,116,45,122,3,46,112,121,
+    122,4,46,112,121,99,78,218,12,111,112,116,105,109,105,122,
+    97,116,105,111,110,99,2,0,0,0,1,0,0,0,11,0,
+    0,0,6,0,0,0,67,0,0,0,115,87,1,0,0,124,
+    1,0,100,1,0,107,9,0,114,76,0,116,0,0,106,1,
+    0,100,2,0,116,2,0,131,2,0,1,124,2,0,100,1,
+    0,107,9,0,114,58,0,100,3,0,125,3,0,116,3,0,
+    124,3,0,131,1,0,130,1,0,124,1,0,114,70,0,100,
+    4,0,110,3,0,100,5,0,125,2,0,116,4,0,124,0,
+    0,131,1,0,92,2,0,125,4,0,125,5,0,124,5,0,
+    106,5,0,100,6,0,131,1,0,92,3,0,125,6,0,125,
+    7,0,125,8,0,116,6,0,106,7,0,106,8,0,125,9,
+    0,124,9,0,100,1,0,107,8,0,114,154,0,116,9,0,
+    100,7,0,131,1,0,130,1,0,100,4,0,106,10,0,124,
+    6,0,114,172,0,124,6,0,110,3,0,124,8,0,124,7,
+    0,124,9,0,103,3,0,131,1,0,125,10,0,124,2,0,
+    100,1,0,107,8,0,114,241,0,116,6,0,106,11,0,106,
+    12,0,100,8,0,107,2,0,114,229,0,100,4,0,125,2,
+    0,110,12,0,116,6,0,106,11,0,106,12,0,125,2,0,
+    116,13,0,124,2,0,131,1,0,125,2,0,124,2,0,100,
+    4,0,107,3,0,114,63,1,124,2,0,106,14,0,131,0,
+    0,115,42,1,116,15,0,100,9,0,106,16,0,124,2,0,
+    131,1,0,131,1,0,130,1,0,100,10,0,106,16,0,124,
+    10,0,116,17,0,124,2,0,131,3,0,125,10,0,116,18,
+    0,124,4,0,116,19,0,124,10,0,116,20,0,100,8,0,
+    25,23,131,3,0,83,41,11,97,254,2,0,0,71,105,118,
+    101,110,32,116,104,101,32,112,97,116,104,32,116,111,32,97,
+    32,46,112,121,32,102,105,108,101,44,32,114,101,116,117,114,
+    110,32,116,104,101,32,112,97,116,104,32,116,111,32,105,116,
+    115,32,46,112,121,99,32,102,105,108,101,46,10,10,32,32,
+    32,32,84,104,101,32,46,112,121,32,102,105,108,101,32,100,
+    111,101,115,32,110,111,116,32,110,101,101,100,32,116,111,32,
+    101,120,105,115,116,59,32,116,104,105,115,32,115,105,109,112,
+    108,121,32,114,101,116,117,114,110,115,32,116,104,101,32,112,
+    97,116,104,32,116,111,32,116,104,101,10,32,32,32,32,46,
+    112,121,99,32,102,105,108,101,32,99,97,108,99,117,108,97,
+    116,101,100,32,97,115,32,105,102,32,116,104,101,32,46,112,
+    121,32,102,105,108,101,32,119,101,114,101,32,105,109,112,111,
+    114,116,101,100,46,10,10,32,32,32,32,84,104,101,32,39,
+    111,112,116,105,109,105,122,97,116,105,111,110,39,32,112,97,
+    114,97,109,101,116,101,114,32,99,111,110,116,114,111,108,115,
+    32,116,104,101,32,112,114,101,115,117,109,101,100,32,111,112,
+    116,105,109,105,122,97,116,105,111,110,32,108,101,118,101,108,
+    32,111,102,10,32,32,32,32,116,104,101,32,98,121,116,101,
+    99,111,100,101,32,102,105,108,101,46,32,73,102,32,39,111,
+    112,116,105,109,105,122,97,116,105,111,110,39,32,105,115,32,
+    110,111,116,32,78,111,110,101,44,32,116,104,101,32,115,116,
+    114,105,110,103,32,114,101,112,114,101,115,101,110,116,97,116,
+    105,111,110,10,32,32,32,32,111,102,32,116,104,101,32,97,
+    114,103,117,109,101,110,116,32,105,115,32,116,97,107,101,110,
+    32,97,110,100,32,118,101,114,105,102,105,101,100,32,116,111,
+    32,98,101,32,97,108,112,104,97,110,117,109,101,114,105,99,
+    32,40,101,108,115,101,32,86,97,108,117,101,69,114,114,111,
+    114,10,32,32,32,32,105,115,32,114,97,105,115,101,100,41,
+    46,10,10,32,32,32,32,84,104,101,32,100,101,98,117,103,
+    95,111,118,101,114,114,105,100,101,32,112,97,114,97,109,101,
+    116,101,114,32,105,115,32,100,101,112,114,101,99,97,116,101,
+    100,46,32,73,102,32,100,101,98,117,103,95,111,118,101,114,
+    114,105,100,101,32,105,115,32,110,111,116,32,78,111,110,101,
+    44,10,32,32,32,32,97,32,84,114,117,101,32,118,97,108,
+    117,101,32,105,115,32,116,104,101,32,115,97,109,101,32,97,
+    115,32,115,101,116,116,105,110,103,32,39,111,112,116,105,109,
+    105,122,97,116,105,111,110,39,32,116,111,32,116,104,101,32,
+    101,109,112,116,121,32,115,116,114,105,110,103,10,32,32,32,
+    32,119,104,105,108,101,32,97,32,70,97,108,115,101,32,118,
+    97,108,117,101,32,105,115,32,101,113,117,105,118,97,108,101,
+    110,116,32,116,111,32,115,101,116,116,105,110,103,32,39,111,
+    112,116,105,109,105,122,97,116,105,111,110,39,32,116,111,32,
+    39,49,39,46,10,10,32,32,32,32,73,102,32,115,121,115,
+    46,105,109,112,108,101,109,101,110,116,97,116,105,111,110,46,
+    99,97,99,104,101,95,116,97,103,32,105,115,32,78,111,110,
+    101,32,116,104,101,110,32,78,111,116,73,109,112,108,101,109,
+    101,110,116,101,100,69,114,114,111,114,32,105,115,32,114,97,
+    105,115,101,100,46,10,10,32,32,32,32,78,122,70,116,104,
+    101,32,100,101,98,117,103,95,111,118,101,114,114,105,100,101,
+    32,112,97,114,97,109,101,116,101,114,32,105,115,32,100,101,
+    112,114,101,99,97,116,101,100,59,32,117,115,101,32,39,111,
+    112,116,105,109,105,122,97,116,105,111,110,39,32,105,110,115,
+    116,101,97,100,122,50,100,101,98,117,103,95,111,118,101,114,
+    114,105,100,101,32,111,114,32,111,112,116,105,109,105,122,97,
+    116,105,111,110,32,109,117,115,116,32,98,101,32,115,101,116,
+    32,116,111,32,78,111,110,101,114,32,0,0,0,114,31,0,
+    0,0,218,1,46,122,36,115,121,115,46,105,109,112,108,101,
+    109,101,110,116,97,116,105,111,110,46,99,97,99,104,101,95,
+    116,97,103,32,105,115,32,78,111,110,101,233,0,0,0,0,
+    122,24,123,33,114,125,32,105,115,32,110,111,116,32,97,108,
+    112,104,97,110,117,109,101,114,105,99,122,7,123,125,46,123,
+    125,123,125,41,21,218,9,95,119,97,114,110,105,110,103,115,
+    218,4,119,97,114,110,218,18,68,101,112,114,101,99,97,116,
+    105,111,110,87,97,114,110,105,110,103,218,9,84,121,112,101,
+    69,114,114,111,114,114,40,0,0,0,114,34,0,0,0,114,
+    8,0,0,0,218,14,105,109,112,108,101,109,101,110,116,97,
+    116,105,111,110,218,9,99,97,99,104,101,95,116,97,103,218,
+    19,78,111,116,73,109,112,108,101,109,101,110,116,101,100,69,
+    114,114,111,114,114,28,0,0,0,218,5,102,108,97,103,115,
+    218,8,111,112,116,105,109,105,122,101,218,3,115,116,114,218,
+    7,105,115,97,108,110,117,109,218,10,86,97,108,117,101,69,
+    114,114,111,114,114,49,0,0,0,218,4,95,79,80,84,114,
+    30,0,0,0,218,8,95,80,89,67,65,67,72,69,218,17,
+    66,89,84,69,67,79,68,69,95,83,85,70,70,73,88,69,
+    83,41,11,114,37,0,0,0,90,14,100,101,98,117,103,95,
+    111,118,101,114,114,105,100,101,114,59,0,0,0,218,7,109,
+    101,115,115,97,103,101,218,4,104,101,97,100,114,39,0,0,
+    0,90,4,98,97,115,101,218,3,115,101,112,218,4,114,101,
+    115,116,90,3,116,97,103,90,15,97,108,109,111,115,116,95,
+    102,105,108,101,110,97,109,101,114,4,0,0,0,114,4,0,
+    0,0,114,6,0,0,0,218,17,99,97,99,104,101,95,102,
+    114,111,109,95,115,111,117,114,99,101,254,0,0,0,115,46,
+    0,0,0,0,18,12,1,9,1,7,1,12,1,6,1,12,
+    1,18,1,18,1,24,1,12,1,12,1,12,1,36,1,12,
+    1,18,1,9,2,12,1,12,1,12,1,12,1,21,1,21,
+    1,114,81,0,0,0,99,1,0,0,0,0,0,0,0,8,
+    0,0,0,5,0,0,0,67,0,0,0,115,62,1,0,0,
+    116,0,0,106,1,0,106,2,0,100,1,0,107,8,0,114,
+    30,0,116,3,0,100,2,0,131,1,0,130,1,0,116,4,
+    0,124,0,0,131,1,0,92,2,0,125,1,0,125,2,0,
+    116,4,0,124,1,0,131,1,0,92,2,0,125,1,0,125,
+    3,0,124,3,0,116,5,0,107,3,0,114,102,0,116,6,
+    0,100,3,0,106,7,0,116,5,0,124,0,0,131,2,0,
+    131,1,0,130,1,0,124,2,0,106,8,0,100,4,0,131,
+    1,0,125,4,0,124,4,0,100,11,0,107,7,0,114,153,
+    0,116,6,0,100,7,0,106,7,0,124,2,0,131,1,0,
+    131,1,0,130,1,0,110,125,0,124,4,0,100,6,0,107,
+    2,0,114,22,1,124,2,0,106,9,0,100,4,0,100,5,
+    0,131,2,0,100,12,0,25,125,5,0,124,5,0,106,10,
+    0,116,11,0,131,1,0,115,223,0,116,6,0,100,8,0,
+    106,7,0,116,11,0,131,1,0,131,1,0,130,1,0,124,
+    5,0,116,12,0,116,11,0,131,1,0,100,1,0,133,2,
+    0,25,125,6,0,124,6,0,106,13,0,131,0,0,115,22,
+    1,116,6,0,100,9,0,106,7,0,124,5,0,131,1,0,
+    131,1,0,130,1,0,124,2,0,106,14,0,100,4,0,131,
+    1,0,100,10,0,25,125,7,0,116,15,0,124,1,0,124,
+    7,0,116,16,0,100,10,0,25,23,131,2,0,83,41,13,
+    97,110,1,0,0,71,105,118,101,110,32,116,104,101,32,112,
+    97,116,104,32,116,111,32,97,32,46,112,121,99,46,32,102,
+    105,108,101,44,32,114,101,116,117,114,110,32,116,104,101,32,
+    112,97,116,104,32,116,111,32,105,116,115,32,46,112,121,32,
+    102,105,108,101,46,10,10,32,32,32,32,84,104,101,32,46,
+    112,121,99,32,102,105,108,101,32,100,111,101,115,32,110,111,
+    116,32,110,101,101,100,32,116,111,32,101,120,105,115,116,59,
+    32,116,104,105,115,32,115,105,109,112,108,121,32,114,101,116,
+    117,114,110,115,32,116,104,101,32,112,97,116,104,32,116,111,
+    10,32,32,32,32,116,104,101,32,46,112,121,32,102,105,108,
+    101,32,99,97,108,99,117,108,97,116,101,100,32,116,111,32,
+    99,111,114,114,101,115,112,111,110,100,32,116,111,32,116,104,
+    101,32,46,112,121,99,32,102,105,108,101,46,32,32,73,102,
+    32,112,97,116,104,32,100,111,101,115,10,32,32,32,32,110,
+    111,116,32,99,111,110,102,111,114,109,32,116,111,32,80,69,
+    80,32,51,49,52,55,47,52,56,56,32,102,111,114,109,97,
+    116,44,32,86,97,108,117,101,69,114,114,111,114,32,119,105,
+    108,108,32,98,101,32,114,97,105,115,101,100,46,32,73,102,
+    10,32,32,32,32,115,121,115,46,105,109,112,108,101,109,101,
+    110,116,97,116,105,111,110,46,99,97,99,104,101,95,116,97,
+    103,32,105,115,32,78,111,110,101,32,116,104,101,110,32,78,
+    111,116,73,109,112,108,101,109,101,110,116,101,100,69,114,114,
+    111,114,32,105,115,32,114,97,105,115,101,100,46,10,10,32,
+    32,32,32,78,122,36,115,121,115,46,105,109,112,108,101,109,
+    101,110,116,97,116,105,111,110,46,99,97,99,104,101,95,116,
+    97,103,32,105,115,32,78,111,110,101,122,37,123,125,32,110,
+    111,116,32,98,111,116,116,111,109,45,108,101,118,101,108,32,
+    100,105,114,101,99,116,111,114,121,32,105,110,32,123,33,114,
+    125,114,60,0,0,0,114,58,0,0,0,233,3,0,0,0,
+    122,33,101,120,112,101,99,116,101,100,32,111,110,108,121,32,
+    50,32,111,114,32,51,32,100,111,116,115,32,105,110,32,123,
+    33,114,125,122,57,111,112,116,105,109,105,122,97,116,105,111,
+    110,32,112,111,114,116,105,111,110,32,111,102,32,102,105,108,
+    101,110,97,109,101,32,100,111,101,115,32,110,111,116,32,115,
+    116,97,114,116,32,119,105,116,104,32,123,33,114,125,122,52,
+    111,112,116,105,109,105,122,97,116,105,111,110,32,108,101,118,
+    101,108,32,123,33,114,125,32,105,115,32,110,111,116,32,97,
+    110,32,97,108,112,104,97,110,117,109,101,114,105,99,32,118,
+    97,108,117,101,114,61,0,0,0,62,2,0,0,0,114,58,
+    0,0,0,114,82,0,0,0,233,254,255,255,255,41,17,114,
+    8,0,0,0,114,66,0,0,0,114,67,0,0,0,114,68,
+    0,0,0,114,40,0,0,0,114,75,0,0,0,114,73,0,
+    0,0,114,49,0,0,0,218,5,99,111,117,110,116,114,36,
+    0,0,0,114,10,0,0,0,114,74,0,0,0,114,33,0,
+    0,0,114,72,0,0,0,218,9,112,97,114,116,105,116,105,
+    111,110,114,30,0,0,0,218,15,83,79,85,82,67,69,95,
+    83,85,70,70,73,88,69,83,41,8,114,37,0,0,0,114,
+    78,0,0,0,90,16,112,121,99,97,99,104,101,95,102,105,
+    108,101,110,97,109,101,90,7,112,121,99,97,99,104,101,90,
+    9,100,111,116,95,99,111,117,110,116,114,59,0,0,0,90,
+    9,111,112,116,95,108,101,118,101,108,90,13,98,97,115,101,
+    95,102,105,108,101,110,97,109,101,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,17,115,111,117,114,99,101,
+    95,102,114,111,109,95,99,97,99,104,101,42,1,0,0,115,
+    44,0,0,0,0,9,18,1,12,1,18,1,18,1,12,1,
+    9,1,15,1,15,1,12,1,9,1,15,1,12,1,22,1,
+    15,1,9,1,12,1,22,1,12,1,9,1,12,1,19,1,
+    114,87,0,0,0,99,1,0,0,0,0,0,0,0,5,0,
+    0,0,12,0,0,0,67,0,0,0,115,164,0,0,0,116,
+    0,0,124,0,0,131,1,0,100,1,0,107,2,0,114,22,
+    0,100,2,0,83,124,0,0,106,1,0,100,3,0,131,1,
+    0,92,3,0,125,1,0,125,2,0,125,3,0,124,1,0,
+    12,115,81,0,124,3,0,106,2,0,131,0,0,100,7,0,
+    100,8,0,133,2,0,25,100,6,0,107,3,0,114,85,0,
+    124,0,0,83,121,16,0,116,3,0,124,0,0,131,1,0,
+    125,4,0,87,110,40,0,4,116,4,0,116,5,0,102,2,
+    0,107,10,0,114,143,0,1,1,1,124,0,0,100,2,0,
+    100,9,0,133,2,0,25,125,4,0,89,110,1,0,88,116,
+    6,0,124,4,0,131,1,0,114,160,0,124,4,0,83,124,
+    0,0,83,41,10,122,188,67,111,110,118,101,114,116,32,97,
+    32,98,121,116,101,99,111,100,101,32,102,105,108,101,32,112,
+    97,116,104,32,116,111,32,97,32,115,111,117,114,99,101,32,
+    112,97,116,104,32,40,105,102,32,112,111,115,115,105,98,108,
+    101,41,46,10,10,32,32,32,32,84,104,105,115,32,102,117,
+    110,99,116,105,111,110,32,101,120,105,115,116,115,32,112,117,
+    114,101,108,121,32,102,111,114,32,98,97,99,107,119,97,114,
+    100,115,45,99,111,109,112,97,116,105,98,105,108,105,116,121,
+    32,102,111,114,10,32,32,32,32,80,121,73,109,112,111,114,
+    116,95,69,120,101,99,67,111,100,101,77,111,100,117,108,101,
+    87,105,116,104,70,105,108,101,110,97,109,101,115,40,41,32,
+    105,110,32,116,104,101,32,67,32,65,80,73,46,10,10,32,
+    32,32,32,114,61,0,0,0,78,114,60,0,0,0,114,82,
+    0,0,0,114,31,0,0,0,90,2,112,121,233,253,255,255,
+    255,233,255,255,255,255,114,89,0,0,0,41,7,114,33,0,
+    0,0,114,34,0,0,0,218,5,108,111,119,101,114,114,87,
+    0,0,0,114,68,0,0,0,114,73,0,0,0,114,46,0,
+    0,0,41,5,218,13,98,121,116,101,99,111,100,101,95,112,
+    97,116,104,114,80,0,0,0,114,38,0,0,0,90,9,101,
+    120,116,101,110,115,105,111,110,218,11,115,111,117,114,99,101,
+    95,112,97,116,104,114,4,0,0,0,114,4,0,0,0,114,
+    6,0,0,0,218,15,95,103,101,116,95,115,111,117,114,99,
+    101,102,105,108,101,75,1,0,0,115,20,0,0,0,0,7,
+    18,1,4,1,24,1,35,1,4,1,3,1,16,1,19,1,
+    21,1,114,93,0,0,0,99,1,0,0,0,0,0,0,0,
+    1,0,0,0,11,0,0,0,67,0,0,0,115,92,0,0,
+    0,124,0,0,106,0,0,116,1,0,116,2,0,131,1,0,
+    131,1,0,114,59,0,121,14,0,116,3,0,124,0,0,131,
+    1,0,83,87,113,88,0,4,116,4,0,107,10,0,114,55,
+    0,1,1,1,89,113,88,0,88,110,29,0,124,0,0,106,
+    0,0,116,1,0,116,5,0,131,1,0,131,1,0,114,84,
+    0,124,0,0,83,100,0,0,83,100,0,0,83,41,1,78,
+    41,6,218,8,101,110,100,115,119,105,116,104,218,5,116,117,
+    112,108,101,114,86,0,0,0,114,81,0,0,0,114,68,0,
+    0,0,114,76,0,0,0,41,1,218,8,102,105,108,101,110,
+    97,109,101,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,218,11,95,103,101,116,95,99,97,99,104,101,100,94,
+    1,0,0,115,16,0,0,0,0,1,21,1,3,1,14,1,
+    13,1,8,1,21,1,4,2,114,97,0,0,0,99,1,0,
+    0,0,0,0,0,0,2,0,0,0,11,0,0,0,67,0,
+    0,0,115,60,0,0,0,121,19,0,116,0,0,124,0,0,
+    131,1,0,106,1,0,125,1,0,87,110,24,0,4,116,2,
+    0,107,10,0,114,45,0,1,1,1,100,1,0,125,1,0,
+    89,110,1,0,88,124,1,0,100,2,0,79,125,1,0,124,
+    1,0,83,41,3,122,51,67,97,108,99,117,108,97,116,101,
+    32,116,104,101,32,109,111,100,101,32,112,101,114,109,105,115,
+    115,105,111,110,115,32,102,111,114,32,97,32,98,121,116,101,
+    99,111,100,101,32,102,105,108,101,46,105,182,1,0,0,233,
+    128,0,0,0,41,3,114,41,0,0,0,114,43,0,0,0,
+    114,42,0,0,0,41,2,114,37,0,0,0,114,44,0,0,
+    0,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    218,10,95,99,97,108,99,95,109,111,100,101,106,1,0,0,
+    115,12,0,0,0,0,2,3,1,19,1,13,1,11,3,10,
+    1,114,99,0,0,0,218,9,118,101,114,98,111,115,105,116,
+    121,114,31,0,0,0,99,1,0,0,0,1,0,0,0,3,
+    0,0,0,4,0,0,0,71,0,0,0,115,75,0,0,0,
+    116,0,0,106,1,0,106,2,0,124,1,0,107,5,0,114,
+    71,0,124,0,0,106,3,0,100,6,0,131,1,0,115,43,
+    0,100,3,0,124,0,0,23,125,0,0,116,4,0,124,0,
+    0,106,5,0,124,2,0,140,0,0,100,4,0,116,0,0,
+    106,6,0,131,1,1,1,100,5,0,83,41,7,122,61,80,
+    114,105,110,116,32,116,104,101,32,109,101,115,115,97,103,101,
+    32,116,111,32,115,116,100,101,114,114,32,105,102,32,45,118,
+    47,80,89,84,72,79,78,86,69,82,66,79,83,69,32,105,
+    115,32,116,117,114,110,101,100,32,111,110,46,250,1,35,250,
+    7,105,109,112,111,114,116,32,122,2,35,32,114,56,0,0,
+    0,78,41,2,114,101,0,0,0,114,102,0,0,0,41,7,
+    114,8,0,0,0,114,69,0,0,0,218,7,118,101,114,98,
+    111,115,101,114,10,0,0,0,218,5,112,114,105,110,116,114,
+    49,0,0,0,218,6,115,116,100,101,114,114,41,3,114,77,
+    0,0,0,114,100,0,0,0,218,4,97,114,103,115,114,4,
+    0,0,0,114,4,0,0,0,114,6,0,0,0,218,16,95,
+    118,101,114,98,111,115,101,95,109,101,115,115,97,103,101,118,
+    1,0,0,115,8,0,0,0,0,2,18,1,15,1,10,1,
+    114,107,0,0,0,99,1,0,0,0,0,0,0,0,3,0,
+    0,0,11,0,0,0,3,0,0,0,115,84,0,0,0,100,
+    1,0,135,0,0,102,1,0,100,2,0,100,3,0,134,1,
+    0,125,1,0,121,13,0,116,0,0,106,1,0,125,2,0,
+    87,110,30,0,4,116,2,0,107,10,0,114,66,0,1,1,
+    1,100,4,0,100,5,0,132,0,0,125,2,0,89,110,1,
+    0,88,124,2,0,124,1,0,136,0,0,131,2,0,1,124,
+    1,0,83,41,6,122,252,68,101,99,111,114,97,116,111,114,
+    32,116,111,32,118,101,114,105,102,121,32,116,104,97,116,32,
+    116,104,101,32,109,111,100,117,108,101,32,98,101,105,110,103,
+    32,114,101,113,117,101,115,116,101,100,32,109,97,116,99,104,
+    101,115,32,116,104,101,32,111,110,101,32,116,104,101,10,32,
+    32,32,32,108,111,97,100,101,114,32,99,97,110,32,104,97,
+    110,100,108,101,46,10,10,32,32,32,32,84,104,101,32,102,
+    105,114,115,116,32,97,114,103,117,109,101,110,116,32,40,115,
+    101,108,102,41,32,109,117,115,116,32,100,101,102,105,110,101,
+    32,95,110,97,109,101,32,119,104,105,99,104,32,116,104,101,
+    32,115,101,99,111,110,100,32,97,114,103,117,109,101,110,116,
+    32,105,115,10,32,32,32,32,99,111,109,112,97,114,101,100,
+    32,97,103,97,105,110,115,116,46,32,73,102,32,116,104,101,
+    32,99,111,109,112,97,114,105,115,111,110,32,102,97,105,108,
+    115,32,116,104,101,110,32,73,109,112,111,114,116,69,114,114,
+    111,114,32,105,115,32,114,97,105,115,101,100,46,10,10,32,
+    32,32,32,78,99,2,0,0,0,0,0,0,0,4,0,0,
+    0,5,0,0,0,31,0,0,0,115,89,0,0,0,124,1,
+    0,100,0,0,107,8,0,114,24,0,124,0,0,106,0,0,
+    125,1,0,110,46,0,124,0,0,106,0,0,124,1,0,107,
+    3,0,114,70,0,116,1,0,100,1,0,124,0,0,106,0,
+    0,124,1,0,102,2,0,22,100,2,0,124,1,0,131,1,
+    1,130,1,0,136,0,0,124,0,0,124,1,0,124,2,0,
+    124,3,0,142,2,0,83,41,3,78,122,30,108,111,97,100,
+    101,114,32,102,111,114,32,37,115,32,99,97,110,110,111,116,
+    32,104,97,110,100,108,101,32,37,115,218,4,110,97,109,101,
+    41,2,114,108,0,0,0,218,11,73,109,112,111,114,116,69,
+    114,114,111,114,41,4,218,4,115,101,108,102,114,108,0,0,
+    0,114,106,0,0,0,90,6,107,119,97,114,103,115,41,1,
+    218,6,109,101,116,104,111,100,114,4,0,0,0,114,6,0,
+    0,0,218,19,95,99,104,101,99,107,95,110,97,109,101,95,
+    119,114,97,112,112,101,114,134,1,0,0,115,12,0,0,0,
+    0,1,12,1,12,1,15,1,6,1,25,1,122,40,95,99,
+    104,101,99,107,95,110,97,109,101,46,60,108,111,99,97,108,
+    115,62,46,95,99,104,101,99,107,95,110,97,109,101,95,119,
+    114,97,112,112,101,114,99,2,0,0,0,0,0,0,0,3,
+    0,0,0,7,0,0,0,83,0,0,0,115,92,0,0,0,
+    120,66,0,100,1,0,100,2,0,100,3,0,100,4,0,103,
+    4,0,68,93,46,0,125,2,0,116,0,0,124,1,0,124,
+    2,0,131,2,0,114,19,0,116,1,0,124,0,0,124,2,
+    0,116,2,0,124,1,0,124,2,0,131,2,0,131,3,0,
+    1,113,19,0,87,124,0,0,106,3,0,106,4,0,124,1,
+    0,106,3,0,131,1,0,1,100,0,0,83,41,5,78,218,
+    10,95,95,109,111,100,117,108,101,95,95,218,8,95,95,110,
+    97,109,101,95,95,218,12,95,95,113,117,97,108,110,97,109,
+    101,95,95,218,7,95,95,100,111,99,95,95,41,5,218,7,
+    104,97,115,97,116,116,114,218,7,115,101,116,97,116,116,114,
+    218,7,103,101,116,97,116,116,114,218,8,95,95,100,105,99,
+    116,95,95,218,6,117,112,100,97,116,101,41,3,90,3,110,
+    101,119,90,3,111,108,100,114,54,0,0,0,114,4,0,0,
+    0,114,4,0,0,0,114,6,0,0,0,218,5,95,119,114,
+    97,112,145,1,0,0,115,8,0,0,0,0,1,25,1,15,
+    1,29,1,122,26,95,99,104,101,99,107,95,110,97,109,101,
+    46,60,108,111,99,97,108,115,62,46,95,119,114,97,112,41,
+    3,218,10,95,98,111,111,116,115,116,114,97,112,114,122,0,
+    0,0,218,9,78,97,109,101,69,114,114,111,114,41,3,114,
+    111,0,0,0,114,112,0,0,0,114,122,0,0,0,114,4,
+    0,0,0,41,1,114,111,0,0,0,114,6,0,0,0,218,
+    11,95,99,104,101,99,107,95,110,97,109,101,126,1,0,0,
+    115,14,0,0,0,0,8,21,7,3,1,13,1,13,2,17,
+    5,13,1,114,125,0,0,0,99,2,0,0,0,0,0,0,
+    0,5,0,0,0,4,0,0,0,67,0,0,0,115,84,0,
+    0,0,124,0,0,106,0,0,124,1,0,131,1,0,92,2,
+    0,125,2,0,125,3,0,124,2,0,100,1,0,107,8,0,
+    114,80,0,116,1,0,124,3,0,131,1,0,114,80,0,100,
+    2,0,125,4,0,116,2,0,106,3,0,124,4,0,106,4,
+    0,124,3,0,100,3,0,25,131,1,0,116,5,0,131,2,
+    0,1,124,2,0,83,41,4,122,155,84,114,121,32,116,111,
+    32,102,105,110,100,32,97,32,108,111,97,100,101,114,32,102,
+    111,114,32,116,104,101,32,115,112,101,99,105,102,105,101,100,
+    32,109,111,100,117,108,101,32,98,121,32,100,101,108,101,103,
+    97,116,105,110,103,32,116,111,10,32,32,32,32,115,101,108,
+    102,46,102,105,110,100,95,108,111,97,100,101,114,40,41,46,
+    10,10,32,32,32,32,84,104,105,115,32,109,101,116,104,111,
+    100,32,105,115,32,100,101,112,114,101,99,97,116,101,100,32,
+    105,110,32,102,97,118,111,114,32,111,102,32,102,105,110,100,
+    101,114,46,102,105,110,100,95,115,112,101,99,40,41,46,10,
+    10,32,32,32,32,78,122,44,78,111,116,32,105,109,112,111,
+    114,116,105,110,103,32,100,105,114,101,99,116,111,114,121,32,
+    123,125,58,32,109,105,115,115,105,110,103,32,95,95,105,110,
+    105,116,95,95,114,61,0,0,0,41,6,218,11,102,105,110,
+    100,95,108,111,97,100,101,114,114,33,0,0,0,114,62,0,
+    0,0,114,63,0,0,0,114,49,0,0,0,218,13,73,109,
+    112,111,114,116,87,97,114,110,105,110,103,41,5,114,110,0,
+    0,0,218,8,102,117,108,108,110,97,109,101,218,6,108,111,
+    97,100,101,114,218,8,112,111,114,116,105,111,110,115,218,3,
+    109,115,103,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,218,17,95,102,105,110,100,95,109,111,100,117,108,101,
+    95,115,104,105,109,154,1,0,0,115,10,0,0,0,0,10,
+    21,1,24,1,6,1,29,1,114,132,0,0,0,99,4,0,
+    0,0,0,0,0,0,11,0,0,0,19,0,0,0,67,0,
+    0,0,115,240,1,0,0,105,0,0,125,4,0,124,2,0,
+    100,1,0,107,9,0,114,31,0,124,2,0,124,4,0,100,
+    2,0,60,110,6,0,100,3,0,125,2,0,124,3,0,100,
+    1,0,107,9,0,114,59,0,124,3,0,124,4,0,100,4,
+    0,60,124,0,0,100,1,0,100,5,0,133,2,0,25,125,
+    5,0,124,0,0,100,5,0,100,6,0,133,2,0,25,125,
+    6,0,124,0,0,100,6,0,100,7,0,133,2,0,25,125,
+    7,0,124,5,0,116,0,0,107,3,0,114,168,0,100,8,
+    0,106,1,0,124,2,0,124,5,0,131,2,0,125,8,0,
+    116,2,0,100,9,0,124,8,0,131,2,0,1,116,3,0,
+    124,8,0,124,4,0,141,1,0,130,1,0,110,119,0,116,
+    4,0,124,6,0,131,1,0,100,5,0,107,3,0,114,229,
+    0,100,10,0,106,1,0,124,2,0,131,1,0,125,8,0,
+    116,2,0,100,9,0,124,8,0,131,2,0,1,116,5,0,
+    124,8,0,131,1,0,130,1,0,110,58,0,116,4,0,124,
+    7,0,131,1,0,100,5,0,107,3,0,114,31,1,100,11,
+    0,106,1,0,124,2,0,131,1,0,125,8,0,116,2,0,
+    100,9,0,124,8,0,131,2,0,1,116,5,0,124,8,0,
+    131,1,0,130,1,0,124,1,0,100,1,0,107,9,0,114,
+    226,1,121,20,0,116,6,0,124,1,0,100,12,0,25,131,
+    1,0,125,9,0,87,110,18,0,4,116,7,0,107,10,0,
+    114,83,1,1,1,1,89,110,62,0,88,116,8,0,124,6,
+    0,131,1,0,124,9,0,107,3,0,114,145,1,100,13,0,
     106,1,0,124,2,0,131,1,0,125,8,0,116,2,0,100,
-    9,0,124,8,0,131,2,0,1,116,5,0,124,8,0,131,
-    1,0,130,1,0,110,58,0,116,4,0,124,7,0,131,1,
-    0,100,5,0,107,3,0,114,31,1,100,11,0,106,1,0,
-    124,2,0,131,1,0,125,8,0,116,2,0,100,9,0,124,
-    8,0,131,2,0,1,116,5,0,124,8,0,131,1,0,130,
-    1,0,124,1,0,100,1,0,107,9,0,114,226,1,121,20,
-    0,116,6,0,124,1,0,100,12,0,25,131,1,0,125,9,
-    0,87,110,18,0,4,116,7,0,107,10,0,114,83,1,1,
-    1,1,89,110,62,0,88,116,8,0,124,6,0,131,1,0,
-    124,9,0,107,3,0,114,145,1,100,13,0,106,1,0,124,
-    2,0,131,1,0,125,8,0,116,2,0,100,9,0,124,8,
-    0,131,2,0,1,116,3,0,124,8,0,124,4,0,141,1,
-    0,130,1,0,121,18,0,124,1,0,100,14,0,25,100,15,
-    0,64,125,10,0,87,110,18,0,4,116,7,0,107,10,0,
-    114,183,1,1,1,1,89,110,43,0,88,116,8,0,124,7,
-    0,131,1,0,124,10,0,107,3,0,114,226,1,116,3,0,
-    100,13,0,106,1,0,124,2,0,131,1,0,124,4,0,141,
-    1,0,130,1,0,124,0,0,100,7,0,100,1,0,133,2,
-    0,25,83,41,16,97,122,1,0,0,86,97,108,105,100,97,
-    116,101,32,116,104,101,32,104,101,97,100,101,114,32,111,102,
-    32,116,104,101,32,112,97,115,115,101,100,45,105,110,32,98,
-    121,116,101,99,111,100,101,32,97,103,97,105,110,115,116,32,
-    115,111,117,114,99,101,95,115,116,97,116,115,32,40,105,102,
-    10,32,32,32,32,103,105,118,101,110,41,32,97,110,100,32,
-    114,101,116,117,114,110,105,110,103,32,116,104,101,32,98,121,
-    116,101,99,111,100,101,32,116,104,97,116,32,99,97,110,32,
-    98,101,32,99,111,109,112,105,108,101,100,32,98,121,32,99,
-    111,109,112,105,108,101,40,41,46,10,10,32,32,32,32,65,
-    108,108,32,111,116,104,101,114,32,97,114,103,117,109,101,110,
-    116,115,32,97,114,101,32,117,115,101,100,32,116,111,32,101,
-    110,104,97,110,99,101,32,101,114,114,111,114,32,114,101,112,
-    111,114,116,105,110,103,46,10,10,32,32,32,32,73,109,112,
-    111,114,116,69,114,114,111,114,32,105,115,32,114,97,105,115,
-    101,100,32,119,104,101,110,32,116,104,101,32,109,97,103,105,
-    99,32,110,117,109,98,101,114,32,105,115,32,105,110,99,111,
-    114,114,101,99,116,32,111,114,32,116,104,101,32,98,121,116,
-    101,99,111,100,101,32,105,115,10,32,32,32,32,102,111,117,
-    110,100,32,116,111,32,98,101,32,115,116,97,108,101,46,32,
-    69,79,70,69,114,114,111,114,32,105,115,32,114,97,105,115,
-    101,100,32,119,104,101,110,32,116,104,101,32,100,97,116,97,
-    32,105,115,32,102,111,117,110,100,32,116,111,32,98,101,10,
-    32,32,32,32,116,114,117,110,99,97,116,101,100,46,10,10,
-    32,32,32,32,78,114,106,0,0,0,122,10,60,98,121,116,
-    101,99,111,100,101,62,114,35,0,0,0,114,12,0,0,0,
-    233,8,0,0,0,233,12,0,0,0,122,30,98,97,100,32,
-    109,97,103,105,99,32,110,117,109,98,101,114,32,105,110,32,
-    123,33,114,125,58,32,123,33,114,125,122,2,123,125,122,43,
-    114,101,97,99,104,101,100,32,69,79,70,32,119,104,105,108,
-    101,32,114,101,97,100,105,110,103,32,116,105,109,101,115,116,
-    97,109,112,32,105,110,32,123,33,114,125,122,48,114,101,97,
-    99,104,101,100,32,69,79,70,32,119,104,105,108,101,32,114,
-    101,97,100,105,110,103,32,115,105,122,101,32,111,102,32,115,
-    111,117,114,99,101,32,105,110,32,123,33,114,125,218,5,109,
-    116,105,109,101,122,26,98,121,116,101,99,111,100,101,32,105,
-    115,32,115,116,97,108,101,32,102,111,114,32,123,33,114,125,
-    218,4,115,105,122,101,108,3,0,0,0,255,127,255,127,3,
-    0,41,9,218,12,77,65,71,73,67,95,78,85,77,66,69,
-    82,114,47,0,0,0,114,105,0,0,0,114,107,0,0,0,
-    114,31,0,0,0,218,8,69,79,70,69,114,114,111,114,114,
-    14,0,0,0,218,8,75,101,121,69,114,114,111,114,114,19,
-    0,0,0,41,11,114,53,0,0,0,218,12,115,111,117,114,
-    99,101,95,115,116,97,116,115,114,106,0,0,0,114,35,0,
-    0,0,90,11,101,120,99,95,100,101,116,97,105,108,115,90,
-    5,109,97,103,105,99,90,13,114,97,119,95,116,105,109,101,
-    115,116,97,109,112,90,8,114,97,119,95,115,105,122,101,114,
-    75,0,0,0,218,12,115,111,117,114,99,101,95,109,116,105,
-    109,101,218,11,115,111,117,114,99,101,95,115,105,122,101,114,
-    4,0,0,0,114,4,0,0,0,114,5,0,0,0,218,25,
-    95,118,97,108,105,100,97,116,101,95,98,121,116,101,99,111,
-    100,101,95,104,101,97,100,101,114,163,1,0,0,115,76,0,
-    0,0,0,11,6,1,12,1,13,3,6,1,12,1,10,1,
-    16,1,16,1,16,1,12,1,18,1,13,1,18,1,18,1,
-    15,1,13,1,15,1,18,1,15,1,13,1,12,1,12,1,
-    3,1,20,1,13,1,5,2,18,1,15,1,13,1,15,1,
-    3,1,18,1,13,1,5,2,18,1,15,1,9,1,114,141,
-    0,0,0,99,4,0,0,0,0,0,0,0,5,0,0,0,
-    6,0,0,0,67,0,0,0,115,112,0,0,0,116,0,0,
-    106,1,0,124,0,0,131,1,0,125,4,0,116,2,0,124,
-    4,0,116,3,0,131,2,0,114,75,0,116,4,0,100,1,
-    0,124,2,0,131,2,0,1,124,3,0,100,2,0,107,9,
-    0,114,71,0,116,5,0,106,6,0,124,4,0,124,3,0,
-    131,2,0,1,124,4,0,83,116,7,0,100,3,0,106,8,
-    0,124,2,0,131,1,0,100,4,0,124,1,0,100,5,0,
-    124,2,0,131,1,2,130,1,0,100,2,0,83,41,6,122,
-    60,67,111,109,112,105,108,101,32,98,121,116,101,99,111,100,
-    101,32,97,115,32,114,101,116,117,114,110,101,100,32,98,121,
-    32,95,118,97,108,105,100,97,116,101,95,98,121,116,101,99,
-    111,100,101,95,104,101,97,100,101,114,40,41,46,122,21,99,
-    111,100,101,32,111,98,106,101,99,116,32,102,114,111,109,32,
-    123,33,114,125,78,122,23,78,111,110,45,99,111,100,101,32,
-    111,98,106,101,99,116,32,105,110,32,123,33,114,125,114,106,
-    0,0,0,114,35,0,0,0,41,9,218,7,109,97,114,115,
-    104,97,108,90,5,108,111,97,100,115,218,10,105,115,105,110,
-    115,116,97,110,99,101,218,10,95,99,111,100,101,95,116,121,
-    112,101,114,105,0,0,0,218,4,95,105,109,112,90,16,95,
-    102,105,120,95,99,111,95,102,105,108,101,110,97,109,101,114,
-    107,0,0,0,114,47,0,0,0,41,5,114,53,0,0,0,
-    114,106,0,0,0,114,89,0,0,0,114,90,0,0,0,218,
-    4,99,111,100,101,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,218,17,95,99,111,109,112,105,108,101,95,98,
-    121,116,101,99,111,100,101,218,1,0,0,115,16,0,0,0,
-    0,2,15,1,15,1,13,1,12,1,16,1,4,2,18,1,
-    114,147,0,0,0,114,59,0,0,0,99,3,0,0,0,0,
-    0,0,0,4,0,0,0,3,0,0,0,67,0,0,0,115,
-    76,0,0,0,116,0,0,116,1,0,131,1,0,125,3,0,
-    124,3,0,106,2,0,116,3,0,124,1,0,131,1,0,131,
-    1,0,1,124,3,0,106,2,0,116,3,0,124,2,0,131,
-    1,0,131,1,0,1,124,3,0,106,2,0,116,4,0,106,
-    5,0,124,0,0,131,1,0,131,1,0,1,124,3,0,83,
-    41,1,122,80,67,111,109,112,105,108,101,32,97,32,99,111,
-    100,101,32,111,98,106,101,99,116,32,105,110,116,111,32,98,
-    121,116,101,99,111,100,101,32,102,111,114,32,119,114,105,116,
-    105,110,103,32,111,117,116,32,116,111,32,97,32,98,121,116,
-    101,45,99,111,109,112,105,108,101,100,10,32,32,32,32,102,
-    105,108,101,46,41,6,218,9,98,121,116,101,97,114,114,97,
-    121,114,135,0,0,0,218,6,101,120,116,101,110,100,114,17,
-    0,0,0,114,142,0,0,0,90,5,100,117,109,112,115,41,
-    4,114,146,0,0,0,114,133,0,0,0,114,140,0,0,0,
-    114,53,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,218,17,95,99,111,100,101,95,116,111,95,98,
-    121,116,101,99,111,100,101,230,1,0,0,115,10,0,0,0,
-    0,3,12,1,19,1,19,1,22,1,114,150,0,0,0,99,
-    1,0,0,0,0,0,0,0,5,0,0,0,4,0,0,0,
-    67,0,0,0,115,89,0,0,0,100,1,0,100,2,0,108,
-    0,0,125,1,0,116,1,0,106,2,0,124,0,0,131,1,
-    0,106,3,0,125,2,0,124,1,0,106,4,0,124,2,0,
-    131,1,0,125,3,0,116,1,0,106,5,0,100,2,0,100,
-    3,0,131,2,0,125,4,0,124,4,0,106,6,0,124,0,
-    0,106,6,0,124,3,0,100,1,0,25,131,1,0,131,1,
-    0,83,41,4,122,121,68,101,99,111,100,101,32,98,121,116,
-    101,115,32,114,101,112,114,101,115,101,110,116,105,110,103,32,
-    115,111,117,114,99,101,32,99,111,100,101,32,97,110,100,32,
-    114,101,116,117,114,110,32,116,104,101,32,115,116,114,105,110,
-    103,46,10,10,32,32,32,32,85,110,105,118,101,114,115,97,
-    108,32,110,101,119,108,105,110,101,32,115,117,112,112,111,114,
-    116,32,105,115,32,117,115,101,100,32,105,110,32,116,104,101,
-    32,100,101,99,111,100,105,110,103,46,10,32,32,32,32,114,
-    59,0,0,0,78,84,41,7,218,8,116,111,107,101,110,105,
-    122,101,114,49,0,0,0,90,7,66,121,116,101,115,73,79,
-    90,8,114,101,97,100,108,105,110,101,90,15,100,101,116,101,
-    99,116,95,101,110,99,111,100,105,110,103,90,25,73,110,99,
-    114,101,109,101,110,116,97,108,78,101,119,108,105,110,101,68,
-    101,99,111,100,101,114,218,6,100,101,99,111,100,101,41,5,
-    218,12,115,111,117,114,99,101,95,98,121,116,101,115,114,151,
-    0,0,0,90,21,115,111,117,114,99,101,95,98,121,116,101,
-    115,95,114,101,97,100,108,105,110,101,218,8,101,110,99,111,
-    100,105,110,103,90,15,110,101,119,108,105,110,101,95,100,101,
-    99,111,100,101,114,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,218,13,100,101,99,111,100,101,95,115,111,117,
-    114,99,101,240,1,0,0,115,10,0,0,0,0,5,12,1,
-    18,1,15,1,18,1,114,155,0,0,0,114,127,0,0,0,
-    218,26,115,117,98,109,111,100,117,108,101,95,115,101,97,114,
-    99,104,95,108,111,99,97,116,105,111,110,115,99,2,0,0,
-    0,2,0,0,0,9,0,0,0,19,0,0,0,67,0,0,
-    0,115,89,1,0,0,124,1,0,100,1,0,107,8,0,114,
-    73,0,100,2,0,125,1,0,116,0,0,124,2,0,100,3,
-    0,131,2,0,114,73,0,121,19,0,124,2,0,106,1,0,
-    124,0,0,131,1,0,125,1,0,87,110,18,0,4,116,2,
-    0,107,10,0,114,72,0,1,1,1,89,110,1,0,88,116,
-    3,0,106,4,0,124,0,0,124,2,0,100,4,0,124,1,
-    0,131,2,1,125,4,0,100,5,0,124,4,0,95,5,0,
-    124,2,0,100,1,0,107,8,0,114,194,0,120,73,0,116,
-    6,0,131,0,0,68,93,58,0,92,2,0,125,5,0,125,
-    6,0,124,1,0,106,7,0,116,8,0,124,6,0,131,1,
-    0,131,1,0,114,128,0,124,5,0,124,0,0,124,1,0,
-    131,2,0,125,2,0,124,2,0,124,4,0,95,9,0,80,
-    113,128,0,87,100,1,0,83,124,3,0,116,10,0,107,8,
-    0,114,23,1,116,0,0,124,2,0,100,6,0,131,2,0,
-    114,32,1,121,19,0,124,2,0,106,11,0,124,0,0,131,
-    1,0,125,7,0,87,110,18,0,4,116,2,0,107,10,0,
-    114,4,1,1,1,1,89,113,32,1,88,124,7,0,114,32,
-    1,103,0,0,124,4,0,95,12,0,110,9,0,124,3,0,
-    124,4,0,95,12,0,124,4,0,106,12,0,103,0,0,107,
-    2,0,114,85,1,124,1,0,114,85,1,116,13,0,124,1,
-    0,131,1,0,100,7,0,25,125,8,0,124,4,0,106,12,
-    0,106,14,0,124,8,0,131,1,0,1,124,4,0,83,41,
-    8,97,61,1,0,0,82,101,116,117,114,110,32,97,32,109,
-    111,100,117,108,101,32,115,112,101,99,32,98,97,115,101,100,
-    32,111,110,32,97,32,102,105,108,101,32,108,111,99,97,116,
-    105,111,110,46,10,10,32,32,32,32,84,111,32,105,110,100,
-    105,99,97,116,101,32,116,104,97,116,32,116,104,101,32,109,
-    111,100,117,108,101,32,105,115,32,97,32,112,97,99,107,97,
-    103,101,44,32,115,101,116,10,32,32,32,32,115,117,98,109,
-    111,100,117,108,101,95,115,101,97,114,99,104,95,108,111,99,
-    97,116,105,111,110,115,32,116,111,32,97,32,108,105,115,116,
-    32,111,102,32,100,105,114,101,99,116,111,114,121,32,112,97,
-    116,104,115,46,32,32,65,110,10,32,32,32,32,101,109,112,
-    116,121,32,108,105,115,116,32,105,115,32,115,117,102,102,105,
-    99,105,101,110,116,44,32,116,104,111,117,103,104,32,105,116,
-    115,32,110,111,116,32,111,116,104,101,114,119,105,115,101,32,
-    117,115,101,102,117,108,32,116,111,32,116,104,101,10,32,32,
-    32,32,105,109,112,111,114,116,32,115,121,115,116,101,109,46,
-    10,10,32,32,32,32,84,104,101,32,108,111,97,100,101,114,
-    32,109,117,115,116,32,116,97,107,101,32,97,32,115,112,101,
-    99,32,97,115,32,105,116,115,32,111,110,108,121,32,95,95,
-    105,110,105,116,95,95,40,41,32,97,114,103,46,10,10,32,
-    32,32,32,78,122,9,60,117,110,107,110,111,119,110,62,218,
-    12,103,101,116,95,102,105,108,101,110,97,109,101,218,6,111,
-    114,105,103,105,110,84,218,10,105,115,95,112,97,99,107,97,
-    103,101,114,59,0,0,0,41,15,114,115,0,0,0,114,157,
-    0,0,0,114,107,0,0,0,114,121,0,0,0,218,10,77,
-    111,100,117,108,101,83,112,101,99,90,13,95,115,101,116,95,
-    102,105,108,101,97,116,116,114,218,27,95,103,101,116,95,115,
-    117,112,112,111,114,116,101,100,95,102,105,108,101,95,108,111,
-    97,100,101,114,115,114,92,0,0,0,114,93,0,0,0,114,
-    127,0,0,0,218,9,95,80,79,80,85,76,65,84,69,114,
-    159,0,0,0,114,156,0,0,0,114,38,0,0,0,218,6,
-    97,112,112,101,110,100,41,9,114,106,0,0,0,90,8,108,
-    111,99,97,116,105,111,110,114,127,0,0,0,114,156,0,0,
-    0,218,4,115,112,101,99,218,12,108,111,97,100,101,114,95,
-    99,108,97,115,115,218,8,115,117,102,102,105,120,101,115,114,
-    159,0,0,0,90,7,100,105,114,110,97,109,101,114,4,0,
-    0,0,114,4,0,0,0,114,5,0,0,0,218,23,115,112,
-    101,99,95,102,114,111,109,95,102,105,108,101,95,108,111,99,
-    97,116,105,111,110,1,2,0,0,115,60,0,0,0,0,12,
-    12,4,6,1,15,2,3,1,19,1,13,1,5,8,24,1,
-    9,3,12,1,22,1,21,1,15,1,9,1,5,2,4,3,
-    12,2,15,1,3,1,19,1,13,1,5,2,6,1,12,2,
-    9,1,15,1,6,1,16,1,16,2,114,167,0,0,0,99,
-    0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,
-    64,0,0,0,115,121,0,0,0,101,0,0,90,1,0,100,
-    0,0,90,2,0,100,1,0,90,3,0,100,2,0,90,4,
-    0,100,3,0,90,5,0,100,4,0,90,6,0,101,7,0,
-    100,5,0,100,6,0,132,0,0,131,1,0,90,8,0,101,
-    7,0,100,7,0,100,8,0,132,0,0,131,1,0,90,9,
-    0,101,7,0,100,9,0,100,9,0,100,10,0,100,11,0,
-    132,2,0,131,1,0,90,10,0,101,7,0,100,9,0,100,
-    12,0,100,13,0,132,1,0,131,1,0,90,11,0,100,9,
-    0,83,41,14,218,21,87,105,110,100,111,119,115,82,101,103,
-    105,115,116,114,121,70,105,110,100,101,114,122,62,77,101,116,
-    97,32,112,97,116,104,32,102,105,110,100,101,114,32,102,111,
-    114,32,109,111,100,117,108,101,115,32,100,101,99,108,97,114,
-    101,100,32,105,110,32,116,104,101,32,87,105,110,100,111,119,
-    115,32,114,101,103,105,115,116,114,121,46,122,59,83,111,102,
-    116,119,97,114,101,92,80,121,116,104,111,110,92,80,121,116,
-    104,111,110,67,111,114,101,92,123,115,121,115,95,118,101,114,
-    115,105,111,110,125,92,77,111,100,117,108,101,115,92,123,102,
-    117,108,108,110,97,109,101,125,122,65,83,111,102,116,119,97,
-    114,101,92,80,121,116,104,111,110,92,80,121,116,104,111,110,
-    67,111,114,101,92,123,115,121,115,95,118,101,114,115,105,111,
-    110,125,92,77,111,100,117,108,101,115,92,123,102,117,108,108,
-    110,97,109,101,125,92,68,101,98,117,103,70,99,2,0,0,
-    0,0,0,0,0,2,0,0,0,11,0,0,0,67,0,0,
-    0,115,67,0,0,0,121,23,0,116,0,0,106,1,0,116,
-    0,0,106,2,0,124,1,0,131,2,0,83,87,110,37,0,
-    4,116,3,0,107,10,0,114,62,0,1,1,1,116,0,0,
-    106,1,0,116,0,0,106,4,0,124,1,0,131,2,0,83,
-    89,110,1,0,88,100,0,0,83,41,1,78,41,5,218,7,
-    95,119,105,110,114,101,103,90,7,79,112,101,110,75,101,121,
-    90,17,72,75,69,89,95,67,85,82,82,69,78,84,95,85,
-    83,69,82,114,40,0,0,0,90,18,72,75,69,89,95,76,
-    79,67,65,76,95,77,65,67,72,73,78,69,41,2,218,3,
-    99,108,115,218,3,107,101,121,114,4,0,0,0,114,4,0,
-    0,0,114,5,0,0,0,218,14,95,111,112,101,110,95,114,
-    101,103,105,115,116,114,121,79,2,0,0,115,8,0,0,0,
-    0,2,3,1,23,1,13,1,122,36,87,105,110,100,111,119,
+    9,0,124,8,0,131,2,0,1,116,3,0,124,8,0,124,
+    4,0,141,1,0,130,1,0,121,18,0,124,1,0,100,14,
+    0,25,100,15,0,64,125,10,0,87,110,18,0,4,116,7,
+    0,107,10,0,114,183,1,1,1,1,89,110,43,0,88,116,
+    8,0,124,7,0,131,1,0,124,10,0,107,3,0,114,226,
+    1,116,3,0,100,13,0,106,1,0,124,2,0,131,1,0,
+    124,4,0,141,1,0,130,1,0,124,0,0,100,7,0,100,
+    1,0,133,2,0,25,83,41,16,97,122,1,0,0,86,97,
+    108,105,100,97,116,101,32,116,104,101,32,104,101,97,100,101,
+    114,32,111,102,32,116,104,101,32,112,97,115,115,101,100,45,
+    105,110,32,98,121,116,101,99,111,100,101,32,97,103,97,105,
+    110,115,116,32,115,111,117,114,99,101,95,115,116,97,116,115,
+    32,40,105,102,10,32,32,32,32,103,105,118,101,110,41,32,
+    97,110,100,32,114,101,116,117,114,110,105,110,103,32,116,104,
+    101,32,98,121,116,101,99,111,100,101,32,116,104,97,116,32,
+    99,97,110,32,98,101,32,99,111,109,112,105,108,101,100,32,
+    98,121,32,99,111,109,112,105,108,101,40,41,46,10,10,32,
+    32,32,32,65,108,108,32,111,116,104,101,114,32,97,114,103,
+    117,109,101,110,116,115,32,97,114,101,32,117,115,101,100,32,
+    116,111,32,101,110,104,97,110,99,101,32,101,114,114,111,114,
+    32,114,101,112,111,114,116,105,110,103,46,10,10,32,32,32,
+    32,73,109,112,111,114,116,69,114,114,111,114,32,105,115,32,
+    114,97,105,115,101,100,32,119,104,101,110,32,116,104,101,32,
+    109,97,103,105,99,32,110,117,109,98,101,114,32,105,115,32,
+    105,110,99,111,114,114,101,99,116,32,111,114,32,116,104,101,
+    32,98,121,116,101,99,111,100,101,32,105,115,10,32,32,32,
+    32,102,111,117,110,100,32,116,111,32,98,101,32,115,116,97,
+    108,101,46,32,69,79,70,69,114,114,111,114,32,105,115,32,
+    114,97,105,115,101,100,32,119,104,101,110,32,116,104,101,32,
+    100,97,116,97,32,105,115,32,102,111,117,110,100,32,116,111,
+    32,98,101,10,32,32,32,32,116,114,117,110,99,97,116,101,
+    100,46,10,10,32,32,32,32,78,114,108,0,0,0,122,10,
+    60,98,121,116,101,99,111,100,101,62,114,37,0,0,0,114,
+    14,0,0,0,233,8,0,0,0,233,12,0,0,0,122,30,
+    98,97,100,32,109,97,103,105,99,32,110,117,109,98,101,114,
+    32,105,110,32,123,33,114,125,58,32,123,33,114,125,122,2,
+    123,125,122,43,114,101,97,99,104,101,100,32,69,79,70,32,
+    119,104,105,108,101,32,114,101,97,100,105,110,103,32,116,105,
+    109,101,115,116,97,109,112,32,105,110,32,123,33,114,125,122,
+    48,114,101,97,99,104,101,100,32,69,79,70,32,119,104,105,
+    108,101,32,114,101,97,100,105,110,103,32,115,105,122,101,32,
+    111,102,32,115,111,117,114,99,101,32,105,110,32,123,33,114,
+    125,218,5,109,116,105,109,101,122,26,98,121,116,101,99,111,
+    100,101,32,105,115,32,115,116,97,108,101,32,102,111,114,32,
+    123,33,114,125,218,4,115,105,122,101,108,3,0,0,0,255,
+    127,255,127,3,0,41,9,218,12,77,65,71,73,67,95,78,
+    85,77,66,69,82,114,49,0,0,0,114,107,0,0,0,114,
+    109,0,0,0,114,33,0,0,0,218,8,69,79,70,69,114,
+    114,111,114,114,16,0,0,0,218,8,75,101,121,69,114,114,
+    111,114,114,21,0,0,0,41,11,114,55,0,0,0,218,12,
+    115,111,117,114,99,101,95,115,116,97,116,115,114,108,0,0,
+    0,114,37,0,0,0,90,11,101,120,99,95,100,101,116,97,
+    105,108,115,90,5,109,97,103,105,99,90,13,114,97,119,95,
+    116,105,109,101,115,116,97,109,112,90,8,114,97,119,95,115,
+    105,122,101,114,77,0,0,0,218,12,115,111,117,114,99,101,
+    95,109,116,105,109,101,218,11,115,111,117,114,99,101,95,115,
+    105,122,101,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,218,25,95,118,97,108,105,100,97,116,101,95,98,121,
+    116,101,99,111,100,101,95,104,101,97,100,101,114,171,1,0,
+    0,115,76,0,0,0,0,11,6,1,12,1,13,3,6,1,
+    12,1,10,1,16,1,16,1,16,1,12,1,18,1,13,1,
+    18,1,18,1,15,1,13,1,15,1,18,1,15,1,13,1,
+    12,1,12,1,3,1,20,1,13,1,5,2,18,1,15,1,
+    13,1,15,1,3,1,18,1,13,1,5,2,18,1,15,1,
+    9,1,114,143,0,0,0,99,4,0,0,0,0,0,0,0,
+    5,0,0,0,6,0,0,0,67,0,0,0,115,112,0,0,
+    0,116,0,0,106,1,0,124,0,0,131,1,0,125,4,0,
+    116,2,0,124,4,0,116,3,0,131,2,0,114,75,0,116,
+    4,0,100,1,0,124,2,0,131,2,0,1,124,3,0,100,
+    2,0,107,9,0,114,71,0,116,5,0,106,6,0,124,4,
+    0,124,3,0,131,2,0,1,124,4,0,83,116,7,0,100,
+    3,0,106,8,0,124,2,0,131,1,0,100,4,0,124,1,
+    0,100,5,0,124,2,0,131,1,2,130,1,0,100,2,0,
+    83,41,6,122,60,67,111,109,112,105,108,101,32,98,121,116,
+    101,99,111,100,101,32,97,115,32,114,101,116,117,114,110,101,
+    100,32,98,121,32,95,118,97,108,105,100,97,116,101,95,98,
+    121,116,101,99,111,100,101,95,104,101,97,100,101,114,40,41,
+    46,122,21,99,111,100,101,32,111,98,106,101,99,116,32,102,
+    114,111,109,32,123,33,114,125,78,122,23,78,111,110,45,99,
+    111,100,101,32,111,98,106,101,99,116,32,105,110,32,123,33,
+    114,125,114,108,0,0,0,114,37,0,0,0,41,9,218,7,
+    109,97,114,115,104,97,108,90,5,108,111,97,100,115,218,10,
+    105,115,105,110,115,116,97,110,99,101,218,10,95,99,111,100,
+    101,95,116,121,112,101,114,107,0,0,0,218,4,95,105,109,
+    112,90,16,95,102,105,120,95,99,111,95,102,105,108,101,110,
+    97,109,101,114,109,0,0,0,114,49,0,0,0,41,5,114,
+    55,0,0,0,114,108,0,0,0,114,91,0,0,0,114,92,
+    0,0,0,218,4,99,111,100,101,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,17,95,99,111,109,112,105,
+    108,101,95,98,121,116,101,99,111,100,101,226,1,0,0,115,
+    16,0,0,0,0,2,15,1,15,1,13,1,12,1,16,1,
+    4,2,18,1,114,149,0,0,0,114,61,0,0,0,99,3,
+    0,0,0,0,0,0,0,4,0,0,0,3,0,0,0,67,
+    0,0,0,115,76,0,0,0,116,0,0,116,1,0,131,1,
+    0,125,3,0,124,3,0,106,2,0,116,3,0,124,1,0,
+    131,1,0,131,1,0,1,124,3,0,106,2,0,116,3,0,
+    124,2,0,131,1,0,131,1,0,1,124,3,0,106,2,0,
+    116,4,0,106,5,0,124,0,0,131,1,0,131,1,0,1,
+    124,3,0,83,41,1,122,80,67,111,109,112,105,108,101,32,
+    97,32,99,111,100,101,32,111,98,106,101,99,116,32,105,110,
+    116,111,32,98,121,116,101,99,111,100,101,32,102,111,114,32,
+    119,114,105,116,105,110,103,32,111,117,116,32,116,111,32,97,
+    32,98,121,116,101,45,99,111,109,112,105,108,101,100,10,32,
+    32,32,32,102,105,108,101,46,41,6,218,9,98,121,116,101,
+    97,114,114,97,121,114,137,0,0,0,218,6,101,120,116,101,
+    110,100,114,19,0,0,0,114,144,0,0,0,90,5,100,117,
+    109,112,115,41,4,114,148,0,0,0,114,135,0,0,0,114,
+    142,0,0,0,114,55,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,17,95,99,111,100,101,95,
+    116,111,95,98,121,116,101,99,111,100,101,238,1,0,0,115,
+    10,0,0,0,0,3,12,1,19,1,19,1,22,1,114,152,
+    0,0,0,99,1,0,0,0,0,0,0,0,5,0,0,0,
+    4,0,0,0,67,0,0,0,115,89,0,0,0,100,1,0,
+    100,2,0,108,0,0,125,1,0,116,1,0,106,2,0,124,
+    0,0,131,1,0,106,3,0,125,2,0,124,1,0,106,4,
+    0,124,2,0,131,1,0,125,3,0,116,1,0,106,5,0,
+    100,2,0,100,3,0,131,2,0,125,4,0,124,4,0,106,
+    6,0,124,0,0,106,6,0,124,3,0,100,1,0,25,131,
+    1,0,131,1,0,83,41,4,122,121,68,101,99,111,100,101,
+    32,98,121,116,101,115,32,114,101,112,114,101,115,101,110,116,
+    105,110,103,32,115,111,117,114,99,101,32,99,111,100,101,32,
+    97,110,100,32,114,101,116,117,114,110,32,116,104,101,32,115,
+    116,114,105,110,103,46,10,10,32,32,32,32,85,110,105,118,
+    101,114,115,97,108,32,110,101,119,108,105,110,101,32,115,117,
+    112,112,111,114,116,32,105,115,32,117,115,101,100,32,105,110,
+    32,116,104,101,32,100,101,99,111,100,105,110,103,46,10,32,
+    32,32,32,114,61,0,0,0,78,84,41,7,218,8,116,111,
+    107,101,110,105,122,101,114,51,0,0,0,90,7,66,121,116,
+    101,115,73,79,90,8,114,101,97,100,108,105,110,101,90,15,
+    100,101,116,101,99,116,95,101,110,99,111,100,105,110,103,90,
+    25,73,110,99,114,101,109,101,110,116,97,108,78,101,119,108,
+    105,110,101,68,101,99,111,100,101,114,218,6,100,101,99,111,
+    100,101,41,5,218,12,115,111,117,114,99,101,95,98,121,116,
+    101,115,114,153,0,0,0,90,21,115,111,117,114,99,101,95,
+    98,121,116,101,115,95,114,101,97,100,108,105,110,101,218,8,
+    101,110,99,111,100,105,110,103,90,15,110,101,119,108,105,110,
+    101,95,100,101,99,111,100,101,114,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,13,100,101,99,111,100,101,
+    95,115,111,117,114,99,101,248,1,0,0,115,10,0,0,0,
+    0,5,12,1,18,1,15,1,18,1,114,157,0,0,0,114,
+    129,0,0,0,218,26,115,117,98,109,111,100,117,108,101,95,
+    115,101,97,114,99,104,95,108,111,99,97,116,105,111,110,115,
+    99,2,0,0,0,2,0,0,0,9,0,0,0,19,0,0,
+    0,67,0,0,0,115,89,1,0,0,124,1,0,100,1,0,
+    107,8,0,114,73,0,100,2,0,125,1,0,116,0,0,124,
+    2,0,100,3,0,131,2,0,114,73,0,121,19,0,124,2,
+    0,106,1,0,124,0,0,131,1,0,125,1,0,87,110,18,
+    0,4,116,2,0,107,10,0,114,72,0,1,1,1,89,110,
+    1,0,88,116,3,0,106,4,0,124,0,0,124,2,0,100,
+    4,0,124,1,0,131,2,1,125,4,0,100,5,0,124,4,
+    0,95,5,0,124,2,0,100,1,0,107,8,0,114,194,0,
+    120,73,0,116,6,0,131,0,0,68,93,58,0,92,2,0,
+    125,5,0,125,6,0,124,1,0,106,7,0,116,8,0,124,
+    6,0,131,1,0,131,1,0,114,128,0,124,5,0,124,0,
+    0,124,1,0,131,2,0,125,2,0,124,2,0,124,4,0,
+    95,9,0,80,113,128,0,87,100,1,0,83,124,3,0,116,
+    10,0,107,8,0,114,23,1,116,0,0,124,2,0,100,6,
+    0,131,2,0,114,32,1,121,19,0,124,2,0,106,11,0,
+    124,0,0,131,1,0,125,7,0,87,110,18,0,4,116,2,
+    0,107,10,0,114,4,1,1,1,1,89,113,32,1,88,124,
+    7,0,114,32,1,103,0,0,124,4,0,95,12,0,110,9,
+    0,124,3,0,124,4,0,95,12,0,124,4,0,106,12,0,
+    103,0,0,107,2,0,114,85,1,124,1,0,114,85,1,116,
+    13,0,124,1,0,131,1,0,100,7,0,25,125,8,0,124,
+    4,0,106,12,0,106,14,0,124,8,0,131,1,0,1,124,
+    4,0,83,41,8,97,61,1,0,0,82,101,116,117,114,110,
+    32,97,32,109,111,100,117,108,101,32,115,112,101,99,32,98,
+    97,115,101,100,32,111,110,32,97,32,102,105,108,101,32,108,
+    111,99,97,116,105,111,110,46,10,10,32,32,32,32,84,111,
+    32,105,110,100,105,99,97,116,101,32,116,104,97,116,32,116,
+    104,101,32,109,111,100,117,108,101,32,105,115,32,97,32,112,
+    97,99,107,97,103,101,44,32,115,101,116,10,32,32,32,32,
+    115,117,98,109,111,100,117,108,101,95,115,101,97,114,99,104,
+    95,108,111,99,97,116,105,111,110,115,32,116,111,32,97,32,
+    108,105,115,116,32,111,102,32,100,105,114,101,99,116,111,114,
+    121,32,112,97,116,104,115,46,32,32,65,110,10,32,32,32,
+    32,101,109,112,116,121,32,108,105,115,116,32,105,115,32,115,
+    117,102,102,105,99,105,101,110,116,44,32,116,104,111,117,103,
+    104,32,105,116,115,32,110,111,116,32,111,116,104,101,114,119,
+    105,115,101,32,117,115,101,102,117,108,32,116,111,32,116,104,
+    101,10,32,32,32,32,105,109,112,111,114,116,32,115,121,115,
+    116,101,109,46,10,10,32,32,32,32,84,104,101,32,108,111,
+    97,100,101,114,32,109,117,115,116,32,116,97,107,101,32,97,
+    32,115,112,101,99,32,97,115,32,105,116,115,32,111,110,108,
+    121,32,95,95,105,110,105,116,95,95,40,41,32,97,114,103,
+    46,10,10,32,32,32,32,78,122,9,60,117,110,107,110,111,
+    119,110,62,218,12,103,101,116,95,102,105,108,101,110,97,109,
+    101,218,6,111,114,105,103,105,110,84,218,10,105,115,95,112,
+    97,99,107,97,103,101,114,61,0,0,0,41,15,114,117,0,
+    0,0,114,159,0,0,0,114,109,0,0,0,114,123,0,0,
+    0,218,10,77,111,100,117,108,101,83,112,101,99,90,13,95,
+    115,101,116,95,102,105,108,101,97,116,116,114,218,27,95,103,
+    101,116,95,115,117,112,112,111,114,116,101,100,95,102,105,108,
+    101,95,108,111,97,100,101,114,115,114,94,0,0,0,114,95,
+    0,0,0,114,129,0,0,0,218,9,95,80,79,80,85,76,
+    65,84,69,114,161,0,0,0,114,158,0,0,0,114,40,0,
+    0,0,218,6,97,112,112,101,110,100,41,9,114,108,0,0,
+    0,90,8,108,111,99,97,116,105,111,110,114,129,0,0,0,
+    114,158,0,0,0,218,4,115,112,101,99,218,12,108,111,97,
+    100,101,114,95,99,108,97,115,115,218,8,115,117,102,102,105,
+    120,101,115,114,161,0,0,0,90,7,100,105,114,110,97,109,
+    101,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    218,23,115,112,101,99,95,102,114,111,109,95,102,105,108,101,
+    95,108,111,99,97,116,105,111,110,9,2,0,0,115,60,0,
+    0,0,0,12,12,4,6,1,15,2,3,1,19,1,13,1,
+    5,8,24,1,9,3,12,1,22,1,21,1,15,1,9,1,
+    5,2,4,3,12,2,15,1,3,1,19,1,13,1,5,2,
+    6,1,12,2,9,1,15,1,6,1,16,1,16,2,114,169,
+    0,0,0,99,0,0,0,0,0,0,0,0,0,0,0,0,
+    5,0,0,0,64,0,0,0,115,121,0,0,0,101,0,0,
+    90,1,0,100,0,0,90,2,0,100,1,0,90,3,0,100,
+    2,0,90,4,0,100,3,0,90,5,0,100,4,0,90,6,
+    0,101,7,0,100,5,0,100,6,0,132,0,0,131,1,0,
+    90,8,0,101,7,0,100,7,0,100,8,0,132,0,0,131,
+    1,0,90,9,0,101,7,0,100,9,0,100,9,0,100,10,
+    0,100,11,0,132,2,0,131,1,0,90,10,0,101,7,0,
+    100,9,0,100,12,0,100,13,0,132,1,0,131,1,0,90,
+    11,0,100,9,0,83,41,14,218,21,87,105,110,100,111,119,
+    115,82,101,103,105,115,116,114,121,70,105,110,100,101,114,122,
+    62,77,101,116,97,32,112,97,116,104,32,102,105,110,100,101,
+    114,32,102,111,114,32,109,111,100,117,108,101,115,32,100,101,
+    99,108,97,114,101,100,32,105,110,32,116,104,101,32,87,105,
+    110,100,111,119,115,32,114,101,103,105,115,116,114,121,46,122,
+    59,83,111,102,116,119,97,114,101,92,80,121,116,104,111,110,
+    92,80,121,116,104,111,110,67,111,114,101,92,123,115,121,115,
+    95,118,101,114,115,105,111,110,125,92,77,111,100,117,108,101,
+    115,92,123,102,117,108,108,110,97,109,101,125,122,65,83,111,
+    102,116,119,97,114,101,92,80,121,116,104,111,110,92,80,121,
+    116,104,111,110,67,111,114,101,92,123,115,121,115,95,118,101,
+    114,115,105,111,110,125,92,77,111,100,117,108,101,115,92,123,
+    102,117,108,108,110,97,109,101,125,92,68,101,98,117,103,70,
+    99,2,0,0,0,0,0,0,0,2,0,0,0,11,0,0,
+    0,67,0,0,0,115,67,0,0,0,121,23,0,116,0,0,
+    106,1,0,116,0,0,106,2,0,124,1,0,131,2,0,83,
+    87,110,37,0,4,116,3,0,107,10,0,114,62,0,1,1,
+    1,116,0,0,106,1,0,116,0,0,106,4,0,124,1,0,
+    131,2,0,83,89,110,1,0,88,100,0,0,83,41,1,78,
+    41,5,218,7,95,119,105,110,114,101,103,90,7,79,112,101,
+    110,75,101,121,90,17,72,75,69,89,95,67,85,82,82,69,
+    78,84,95,85,83,69,82,114,42,0,0,0,90,18,72,75,
+    69,89,95,76,79,67,65,76,95,77,65,67,72,73,78,69,
+    41,2,218,3,99,108,115,114,5,0,0,0,114,4,0,0,
+    0,114,4,0,0,0,114,6,0,0,0,218,14,95,111,112,
+    101,110,95,114,101,103,105,115,116,114,121,87,2,0,0,115,
+    8,0,0,0,0,2,3,1,23,1,13,1,122,36,87,105,
+    110,100,111,119,115,82,101,103,105,115,116,114,121,70,105,110,
+    100,101,114,46,95,111,112,101,110,95,114,101,103,105,115,116,
+    114,121,99,2,0,0,0,0,0,0,0,6,0,0,0,16,
+    0,0,0,67,0,0,0,115,143,0,0,0,124,0,0,106,
+    0,0,114,21,0,124,0,0,106,1,0,125,2,0,110,9,
+    0,124,0,0,106,2,0,125,2,0,124,2,0,106,3,0,
+    100,1,0,124,1,0,100,2,0,116,4,0,106,5,0,100,
+    0,0,100,3,0,133,2,0,25,131,0,2,125,3,0,121,
+    47,0,124,0,0,106,6,0,124,3,0,131,1,0,143,25,
+    0,125,4,0,116,7,0,106,8,0,124,4,0,100,4,0,
+    131,2,0,125,5,0,87,100,0,0,81,82,88,87,110,22,
+    0,4,116,9,0,107,10,0,114,138,0,1,1,1,100,0,
+    0,83,89,110,1,0,88,124,5,0,83,41,5,78,114,128,
+    0,0,0,90,11,115,121,115,95,118,101,114,115,105,111,110,
+    114,82,0,0,0,114,32,0,0,0,41,10,218,11,68,69,
+    66,85,71,95,66,85,73,76,68,218,18,82,69,71,73,83,
+    84,82,89,95,75,69,89,95,68,69,66,85,71,218,12,82,
+    69,71,73,83,84,82,89,95,75,69,89,114,49,0,0,0,
+    114,8,0,0,0,218,7,118,101,114,115,105,111,110,114,173,
+    0,0,0,114,171,0,0,0,90,10,81,117,101,114,121,86,
+    97,108,117,101,114,42,0,0,0,41,6,114,172,0,0,0,
+    114,128,0,0,0,90,12,114,101,103,105,115,116,114,121,95,
+    107,101,121,114,5,0,0,0,90,4,104,107,101,121,218,8,
+    102,105,108,101,112,97,116,104,114,4,0,0,0,114,4,0,
+    0,0,114,6,0,0,0,218,16,95,115,101,97,114,99,104,
+    95,114,101,103,105,115,116,114,121,94,2,0,0,115,22,0,
+    0,0,0,2,9,1,12,2,9,1,15,1,22,1,3,1,
+    18,1,29,1,13,1,9,1,122,38,87,105,110,100,111,119,
     115,82,101,103,105,115,116,114,121,70,105,110,100,101,114,46,
-    95,111,112,101,110,95,114,101,103,105,115,116,114,121,99,2,
-    0,0,0,0,0,0,0,6,0,0,0,16,0,0,0,67,
-    0,0,0,115,143,0,0,0,124,0,0,106,0,0,114,21,
-    0,124,0,0,106,1,0,125,2,0,110,9,0,124,0,0,
-    106,2,0,125,2,0,124,2,0,106,3,0,100,1,0,124,
-    1,0,100,2,0,116,4,0,106,5,0,100,0,0,100,3,
-    0,133,2,0,25,131,0,2,125,3,0,121,47,0,124,0,
-    0,106,6,0,124,3,0,131,1,0,143,25,0,125,4,0,
-    116,7,0,106,8,0,124,4,0,100,4,0,131,2,0,125,
-    5,0,87,100,0,0,81,82,88,87,110,22,0,4,116,9,
-    0,107,10,0,114,138,0,1,1,1,100,0,0,83,89,110,
-    1,0,88,124,5,0,83,41,5,78,114,126,0,0,0,90,
-    11,115,121,115,95,118,101,114,115,105,111,110,114,80,0,0,
-    0,114,30,0,0,0,41,10,218,11,68,69,66,85,71,95,
-    66,85,73,76,68,218,18,82,69,71,73,83,84,82,89,95,
-    75,69,89,95,68,69,66,85,71,218,12,82,69,71,73,83,
-    84,82,89,95,75,69,89,114,47,0,0,0,114,7,0,0,
-    0,218,7,118,101,114,115,105,111,110,114,172,0,0,0,114,
-    169,0,0,0,90,10,81,117,101,114,121,86,97,108,117,101,
-    114,40,0,0,0,41,6,114,170,0,0,0,114,126,0,0,
-    0,90,12,114,101,103,105,115,116,114,121,95,107,101,121,114,
-    171,0,0,0,90,4,104,107,101,121,218,8,102,105,108,101,
-    112,97,116,104,114,4,0,0,0,114,4,0,0,0,114,5,
-    0,0,0,218,16,95,115,101,97,114,99,104,95,114,101,103,
-    105,115,116,114,121,86,2,0,0,115,22,0,0,0,0,2,
-    9,1,12,2,9,1,15,1,22,1,3,1,18,1,29,1,
-    13,1,9,1,122,38,87,105,110,100,111,119,115,82,101,103,
-    105,115,116,114,121,70,105,110,100,101,114,46,95,115,101,97,
-    114,99,104,95,114,101,103,105,115,116,114,121,78,99,4,0,
-    0,0,0,0,0,0,8,0,0,0,14,0,0,0,67,0,
-    0,0,115,158,0,0,0,124,0,0,106,0,0,124,1,0,
-    131,1,0,125,4,0,124,4,0,100,0,0,107,8,0,114,
-    31,0,100,0,0,83,121,14,0,116,1,0,124,4,0,131,
-    1,0,1,87,110,22,0,4,116,2,0,107,10,0,114,69,
-    0,1,1,1,100,0,0,83,89,110,1,0,88,120,81,0,
-    116,3,0,131,0,0,68,93,70,0,92,2,0,125,5,0,
-    125,6,0,124,4,0,106,4,0,116,5,0,124,6,0,131,
-    1,0,131,1,0,114,80,0,116,6,0,106,7,0,124,1,
-    0,124,5,0,124,1,0,124,4,0,131,2,0,100,1,0,
-    124,4,0,131,2,1,125,7,0,124,7,0,83,113,80,0,
-    87,100,0,0,83,41,2,78,114,158,0,0,0,41,8,114,
-    178,0,0,0,114,39,0,0,0,114,40,0,0,0,114,161,
-    0,0,0,114,92,0,0,0,114,93,0,0,0,114,121,0,
-    0,0,218,16,115,112,101,99,95,102,114,111,109,95,108,111,
-    97,100,101,114,41,8,114,170,0,0,0,114,126,0,0,0,
-    114,35,0,0,0,218,6,116,97,114,103,101,116,114,177,0,
-    0,0,114,127,0,0,0,114,166,0,0,0,114,164,0,0,
-    0,114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,
-    218,9,102,105,110,100,95,115,112,101,99,101,2,0,0,115,
-    26,0,0,0,0,2,15,1,12,1,4,1,3,1,14,1,
-    13,1,9,1,22,1,21,1,9,1,15,1,9,1,122,31,
-    87,105,110,100,111,119,115,82,101,103,105,115,116,114,121,70,
-    105,110,100,101,114,46,102,105,110,100,95,115,112,101,99,99,
-    3,0,0,0,0,0,0,0,4,0,0,0,3,0,0,0,
-    67,0,0,0,115,45,0,0,0,124,0,0,106,0,0,124,
-    1,0,124,2,0,131,2,0,125,3,0,124,3,0,100,1,
-    0,107,9,0,114,37,0,124,3,0,106,1,0,83,100,1,
-    0,83,100,1,0,83,41,2,122,108,70,105,110,100,32,109,
-    111,100,117,108,101,32,110,97,109,101,100,32,105,110,32,116,
-    104,101,32,114,101,103,105,115,116,114,121,46,10,10,32,32,
-    32,32,32,32,32,32,84,104,105,115,32,109,101,116,104,111,
-    100,32,105,115,32,100,101,112,114,101,99,97,116,101,100,46,
-    32,32,85,115,101,32,101,120,101,99,95,109,111,100,117,108,
-    101,40,41,32,105,110,115,116,101,97,100,46,10,10,32,32,
-    32,32,32,32,32,32,78,41,2,114,181,0,0,0,114,127,
-    0,0,0,41,4,114,170,0,0,0,114,126,0,0,0,114,
-    35,0,0,0,114,164,0,0,0,114,4,0,0,0,114,4,
-    0,0,0,114,5,0,0,0,218,11,102,105,110,100,95,109,
-    111,100,117,108,101,117,2,0,0,115,8,0,0,0,0,7,
-    18,1,12,1,7,2,122,33,87,105,110,100,111,119,115,82,
-    101,103,105,115,116,114,121,70,105,110,100,101,114,46,102,105,
-    110,100,95,109,111,100,117,108,101,41,12,114,112,0,0,0,
-    114,111,0,0,0,114,113,0,0,0,114,114,0,0,0,114,
-    175,0,0,0,114,174,0,0,0,114,173,0,0,0,218,11,
-    99,108,97,115,115,109,101,116,104,111,100,114,172,0,0,0,
-    114,178,0,0,0,114,181,0,0,0,114,182,0,0,0,114,
-    4,0,0,0,114,4,0,0,0,114,4,0,0,0,114,5,
-    0,0,0,114,168,0,0,0,67,2,0,0,115,20,0,0,
-    0,12,2,6,3,6,3,6,2,6,2,18,7,18,15,3,
-    1,21,15,3,1,114,168,0,0,0,99,0,0,0,0,0,
-    0,0,0,0,0,0,0,2,0,0,0,64,0,0,0,115,
-    70,0,0,0,101,0,0,90,1,0,100,0,0,90,2,0,
-    100,1,0,90,3,0,100,2,0,100,3,0,132,0,0,90,
-    4,0,100,4,0,100,5,0,132,0,0,90,5,0,100,6,
-    0,100,7,0,132,0,0,90,6,0,100,8,0,100,9,0,
-    132,0,0,90,7,0,100,10,0,83,41,11,218,13,95,76,
-    111,97,100,101,114,66,97,115,105,99,115,122,83,66,97,115,
-    101,32,99,108,97,115,115,32,111,102,32,99,111,109,109,111,
-    110,32,99,111,100,101,32,110,101,101,100,101,100,32,98,121,
-    32,98,111,116,104,32,83,111,117,114,99,101,76,111,97,100,
-    101,114,32,97,110,100,10,32,32,32,32,83,111,117,114,99,
-    101,108,101,115,115,70,105,108,101,76,111,97,100,101,114,46,
-    99,2,0,0,0,0,0,0,0,5,0,0,0,3,0,0,
-    0,67,0,0,0,115,88,0,0,0,116,0,0,124,0,0,
-    106,1,0,124,1,0,131,1,0,131,1,0,100,1,0,25,
-    125,2,0,124,2,0,106,2,0,100,2,0,100,1,0,131,
-    2,0,100,3,0,25,125,3,0,124,1,0,106,3,0,100,
-    2,0,131,1,0,100,4,0,25,125,4,0,124,3,0,100,
-    5,0,107,2,0,111,87,0,124,4,0,100,5,0,107,3,
-    0,83,41,6,122,141,67,111,110,99,114,101,116,101,32,105,
-    109,112,108,101,109,101,110,116,97,116,105,111,110,32,111,102,
-    32,73,110,115,112,101,99,116,76,111,97,100,101,114,46,105,
-    115,95,112,97,99,107,97,103,101,32,98,121,32,99,104,101,
-    99,107,105,110,103,32,105,102,10,32,32,32,32,32,32,32,
-    32,116,104,101,32,112,97,116,104,32,114,101,116,117,114,110,
-    101,100,32,98,121,32,103,101,116,95,102,105,108,101,110,97,
-    109,101,32,104,97,115,32,97,32,102,105,108,101,110,97,109,
-    101,32,111,102,32,39,95,95,105,110,105,116,95,95,46,112,
-    121,39,46,114,29,0,0,0,114,58,0,0,0,114,59,0,
-    0,0,114,56,0,0,0,218,8,95,95,105,110,105,116,95,
-    95,41,4,114,38,0,0,0,114,157,0,0,0,114,34,0,
-    0,0,114,32,0,0,0,41,5,114,108,0,0,0,114,126,
-    0,0,0,114,94,0,0,0,90,13,102,105,108,101,110,97,
-    109,101,95,98,97,115,101,90,9,116,97,105,108,95,110,97,
-    109,101,114,4,0,0,0,114,4,0,0,0,114,5,0,0,
-    0,114,159,0,0,0,136,2,0,0,115,8,0,0,0,0,
-    3,25,1,22,1,19,1,122,24,95,76,111,97,100,101,114,
-    66,97,115,105,99,115,46,105,115,95,112,97,99,107,97,103,
-    101,99,2,0,0,0,0,0,0,0,2,0,0,0,1,0,
-    0,0,67,0,0,0,115,4,0,0,0,100,1,0,83,41,
-    2,122,42,85,115,101,32,100,101,102,97,117,108,116,32,115,
-    101,109,97,110,116,105,99,115,32,102,111,114,32,109,111,100,
-    117,108,101,32,99,114,101,97,116,105,111,110,46,78,114,4,
-    0,0,0,41,2,114,108,0,0,0,114,164,0,0,0,114,
-    4,0,0,0,114,4,0,0,0,114,5,0,0,0,218,13,
-    99,114,101,97,116,101,95,109,111,100,117,108,101,144,2,0,
-    0,115,0,0,0,0,122,27,95,76,111,97,100,101,114,66,
-    97,115,105,99,115,46,99,114,101,97,116,101,95,109,111,100,
-    117,108,101,99,2,0,0,0,0,0,0,0,3,0,0,0,
-    4,0,0,0,67,0,0,0,115,80,0,0,0,124,0,0,
-    106,0,0,124,1,0,106,1,0,131,1,0,125,2,0,124,
-    2,0,100,1,0,107,8,0,114,54,0,116,2,0,100,2,
-    0,106,3,0,124,1,0,106,1,0,131,1,0,131,1,0,
-    130,1,0,116,4,0,106,5,0,116,6,0,124,2,0,124,
-    1,0,106,7,0,131,3,0,1,100,1,0,83,41,3,122,
-    19,69,120,101,99,117,116,101,32,116,104,101,32,109,111,100,
-    117,108,101,46,78,122,52,99,97,110,110,111,116,32,108,111,
-    97,100,32,109,111,100,117,108,101,32,123,33,114,125,32,119,
-    104,101,110,32,103,101,116,95,99,111,100,101,40,41,32,114,
-    101,116,117,114,110,115,32,78,111,110,101,41,8,218,8,103,
-    101,116,95,99,111,100,101,114,112,0,0,0,114,107,0,0,
-    0,114,47,0,0,0,114,121,0,0,0,218,25,95,99,97,
-    108,108,95,119,105,116,104,95,102,114,97,109,101,115,95,114,
-    101,109,111,118,101,100,218,4,101,120,101,99,114,118,0,0,
-    0,41,3,114,108,0,0,0,218,6,109,111,100,117,108,101,
-    114,146,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,218,11,101,120,101,99,95,109,111,100,117,108,
-    101,147,2,0,0,115,10,0,0,0,0,2,18,1,12,1,
-    9,1,15,1,122,25,95,76,111,97,100,101,114,66,97,115,
-    105,99,115,46,101,120,101,99,95,109,111,100,117,108,101,99,
-    2,0,0,0,0,0,0,0,2,0,0,0,3,0,0,0,
-    67,0,0,0,115,16,0,0,0,116,0,0,106,1,0,124,
-    0,0,124,1,0,131,2,0,83,41,1,78,41,2,114,121,
-    0,0,0,218,17,95,108,111,97,100,95,109,111,100,117,108,
-    101,95,115,104,105,109,41,2,114,108,0,0,0,114,126,0,
-    0,0,114,4,0,0,0,114,4,0,0,0,114,5,0,0,
-    0,218,11,108,111,97,100,95,109,111,100,117,108,101,155,2,
-    0,0,115,2,0,0,0,0,1,122,25,95,76,111,97,100,
-    101,114,66,97,115,105,99,115,46,108,111,97,100,95,109,111,
-    100,117,108,101,78,41,8,114,112,0,0,0,114,111,0,0,
-    0,114,113,0,0,0,114,114,0,0,0,114,159,0,0,0,
-    114,186,0,0,0,114,191,0,0,0,114,193,0,0,0,114,
-    4,0,0,0,114,4,0,0,0,114,4,0,0,0,114,5,
-    0,0,0,114,184,0,0,0,131,2,0,0,115,10,0,0,
-    0,12,3,6,2,12,8,12,3,12,8,114,184,0,0,0,
-    99,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,
-    0,64,0,0,0,115,106,0,0,0,101,0,0,90,1,0,
-    100,0,0,90,2,0,100,1,0,100,2,0,132,0,0,90,
-    3,0,100,3,0,100,4,0,132,0,0,90,4,0,100,5,
-    0,100,6,0,132,0,0,90,5,0,100,7,0,100,8,0,
-    132,0,0,90,6,0,100,9,0,100,10,0,132,0,0,90,
-    7,0,100,11,0,100,18,0,100,13,0,100,14,0,132,0,
-    1,90,8,0,100,15,0,100,16,0,132,0,0,90,9,0,
-    100,17,0,83,41,19,218,12,83,111,117,114,99,101,76,111,
-    97,100,101,114,99,2,0,0,0,0,0,0,0,2,0,0,
-    0,1,0,0,0,67,0,0,0,115,10,0,0,0,116,0,
-    0,130,1,0,100,1,0,83,41,2,122,178,79,112,116,105,
-    111,110,97,108,32,109,101,116,104,111,100,32,116,104,97,116,
-    32,114,101,116,117,114,110,115,32,116,104,101,32,109,111,100,
-    105,102,105,99,97,116,105,111,110,32,116,105,109,101,32,40,
-    97,110,32,105,110,116,41,32,102,111,114,32,116,104,101,10,
-    32,32,32,32,32,32,32,32,115,112,101,99,105,102,105,101,
-    100,32,112,97,116,104,44,32,119,104,101,114,101,32,112,97,
-    116,104,32,105,115,32,97,32,115,116,114,46,10,10,32,32,
-    32,32,32,32,32,32,82,97,105,115,101,115,32,73,79,69,
-    114,114,111,114,32,119,104,101,110,32,116,104,101,32,112,97,
-    116,104,32,99,97,110,110,111,116,32,98,101,32,104,97,110,
-    100,108,101,100,46,10,32,32,32,32,32,32,32,32,78,41,
-    1,218,7,73,79,69,114,114,111,114,41,2,114,108,0,0,
-    0,114,35,0,0,0,114,4,0,0,0,114,4,0,0,0,
-    114,5,0,0,0,218,10,112,97,116,104,95,109,116,105,109,
-    101,161,2,0,0,115,2,0,0,0,0,6,122,23,83,111,
-    117,114,99,101,76,111,97,100,101,114,46,112,97,116,104,95,
-    109,116,105,109,101,99,2,0,0,0,0,0,0,0,2,0,
-    0,0,3,0,0,0,67,0,0,0,115,19,0,0,0,100,
-    1,0,124,0,0,106,0,0,124,1,0,131,1,0,105,1,
-    0,83,41,2,97,170,1,0,0,79,112,116,105,111,110,97,
-    108,32,109,101,116,104,111,100,32,114,101,116,117,114,110,105,
-    110,103,32,97,32,109,101,116,97,100,97,116,97,32,100,105,
-    99,116,32,102,111,114,32,116,104,101,32,115,112,101,99,105,
-    102,105,101,100,32,112,97,116,104,10,32,32,32,32,32,32,
-    32,32,116,111,32,98,121,32,116,104,101,32,112,97,116,104,
-    32,40,115,116,114,41,46,10,32,32,32,32,32,32,32,32,
-    80,111,115,115,105,98,108,101,32,107,101,121,115,58,10,32,
-    32,32,32,32,32,32,32,45,32,39,109,116,105,109,101,39,
-    32,40,109,97,110,100,97,116,111,114,121,41,32,105,115,32,
-    116,104,101,32,110,117,109,101,114,105,99,32,116,105,109,101,
-    115,116,97,109,112,32,111,102,32,108,97,115,116,32,115,111,
-    117,114,99,101,10,32,32,32,32,32,32,32,32,32,32,99,
-    111,100,101,32,109,111,100,105,102,105,99,97,116,105,111,110,
-    59,10,32,32,32,32,32,32,32,32,45,32,39,115,105,122,
-    101,39,32,40,111,112,116,105,111,110,97,108,41,32,105,115,
-    32,116,104,101,32,115,105,122,101,32,105,110,32,98,121,116,
-    101,115,32,111,102,32,116,104,101,32,115,111,117,114,99,101,
-    32,99,111,100,101,46,10,10,32,32,32,32,32,32,32,32,
-    73,109,112,108,101,109,101,110,116,105,110,103,32,116,104,105,
-    115,32,109,101,116,104,111,100,32,97,108,108,111,119,115,32,
-    116,104,101,32,108,111,97,100,101,114,32,116,111,32,114,101,
-    97,100,32,98,121,116,101,99,111,100,101,32,102,105,108,101,
-    115,46,10,32,32,32,32,32,32,32,32,82,97,105,115,101,
-    115,32,73,79,69,114,114,111,114,32,119,104,101,110,32,116,
-    104,101,32,112,97,116,104,32,99,97,110,110,111,116,32,98,
-    101,32,104,97,110,100,108,101,100,46,10,32,32,32,32,32,
-    32,32,32,114,133,0,0,0,41,1,114,196,0,0,0,41,
-    2,114,108,0,0,0,114,35,0,0,0,114,4,0,0,0,
-    114,4,0,0,0,114,5,0,0,0,218,10,112,97,116,104,
-    95,115,116,97,116,115,169,2,0,0,115,2,0,0,0,0,
-    11,122,23,83,111,117,114,99,101,76,111,97,100,101,114,46,
-    112,97,116,104,95,115,116,97,116,115,99,4,0,0,0,0,
-    0,0,0,4,0,0,0,3,0,0,0,67,0,0,0,115,
-    16,0,0,0,124,0,0,106,0,0,124,2,0,124,3,0,
-    131,2,0,83,41,1,122,228,79,112,116,105,111,110,97,108,
-    32,109,101,116,104,111,100,32,119,104,105,99,104,32,119,114,
-    105,116,101,115,32,100,97,116,97,32,40,98,121,116,101,115,
-    41,32,116,111,32,97,32,102,105,108,101,32,112,97,116,104,
-    32,40,97,32,115,116,114,41,46,10,10,32,32,32,32,32,
-    32,32,32,73,109,112,108,101,109,101,110,116,105,110,103,32,
-    116,104,105,115,32,109,101,116,104,111,100,32,97,108,108,111,
-    119,115,32,102,111,114,32,116,104,101,32,119,114,105,116,105,
-    110,103,32,111,102,32,98,121,116,101,99,111,100,101,32,102,
-    105,108,101,115,46,10,10,32,32,32,32,32,32,32,32,84,
-    104,101,32,115,111,117,114,99,101,32,112,97,116,104,32,105,
-    115,32,110,101,101,100,101,100,32,105,110,32,111,114,100,101,
-    114,32,116,111,32,99,111,114,114,101,99,116,108,121,32,116,
-    114,97,110,115,102,101,114,32,112,101,114,109,105,115,115,105,
-    111,110,115,10,32,32,32,32,32,32,32,32,41,1,218,8,
-    115,101,116,95,100,97,116,97,41,4,114,108,0,0,0,114,
-    90,0,0,0,90,10,99,97,99,104,101,95,112,97,116,104,
-    114,53,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,218,15,95,99,97,99,104,101,95,98,121,116,
-    101,99,111,100,101,182,2,0,0,115,2,0,0,0,0,8,
-    122,28,83,111,117,114,99,101,76,111,97,100,101,114,46,95,
-    99,97,99,104,101,95,98,121,116,101,99,111,100,101,99,3,
-    0,0,0,0,0,0,0,3,0,0,0,1,0,0,0,67,
-    0,0,0,115,4,0,0,0,100,1,0,83,41,2,122,150,
+    95,115,101,97,114,99,104,95,114,101,103,105,115,116,114,121,
+    78,99,4,0,0,0,0,0,0,0,8,0,0,0,14,0,
+    0,0,67,0,0,0,115,158,0,0,0,124,0,0,106,0,
+    0,124,1,0,131,1,0,125,4,0,124,4,0,100,0,0,
+    107,8,0,114,31,0,100,0,0,83,121,14,0,116,1,0,
+    124,4,0,131,1,0,1,87,110,22,0,4,116,2,0,107,
+    10,0,114,69,0,1,1,1,100,0,0,83,89,110,1,0,
+    88,120,81,0,116,3,0,131,0,0,68,93,70,0,92,2,
+    0,125,5,0,125,6,0,124,4,0,106,4,0,116,5,0,
+    124,6,0,131,1,0,131,1,0,114,80,0,116,6,0,106,
+    7,0,124,1,0,124,5,0,124,1,0,124,4,0,131,2,
+    0,100,1,0,124,4,0,131,2,1,125,7,0,124,7,0,
+    83,113,80,0,87,100,0,0,83,41,2,78,114,160,0,0,
+    0,41,8,114,179,0,0,0,114,41,0,0,0,114,42,0,
+    0,0,114,163,0,0,0,114,94,0,0,0,114,95,0,0,
+    0,114,123,0,0,0,218,16,115,112,101,99,95,102,114,111,
+    109,95,108,111,97,100,101,114,41,8,114,172,0,0,0,114,
+    128,0,0,0,114,37,0,0,0,218,6,116,97,114,103,101,
+    116,114,178,0,0,0,114,129,0,0,0,114,168,0,0,0,
+    114,166,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
+    6,0,0,0,218,9,102,105,110,100,95,115,112,101,99,109,
+    2,0,0,115,26,0,0,0,0,2,15,1,12,1,4,1,
+    3,1,14,1,13,1,9,1,22,1,21,1,9,1,15,1,
+    9,1,122,31,87,105,110,100,111,119,115,82,101,103,105,115,
+    116,114,121,70,105,110,100,101,114,46,102,105,110,100,95,115,
+    112,101,99,99,3,0,0,0,0,0,0,0,4,0,0,0,
+    3,0,0,0,67,0,0,0,115,45,0,0,0,124,0,0,
+    106,0,0,124,1,0,124,2,0,131,2,0,125,3,0,124,
+    3,0,100,1,0,107,9,0,114,37,0,124,3,0,106,1,
+    0,83,100,1,0,83,100,1,0,83,41,2,122,108,70,105,
+    110,100,32,109,111,100,117,108,101,32,110,97,109,101,100,32,
+    105,110,32,116,104,101,32,114,101,103,105,115,116,114,121,46,
+    10,10,32,32,32,32,32,32,32,32,84,104,105,115,32,109,
+    101,116,104,111,100,32,105,115,32,100,101,112,114,101,99,97,
+    116,101,100,46,32,32,85,115,101,32,101,120,101,99,95,109,
+    111,100,117,108,101,40,41,32,105,110,115,116,101,97,100,46,
+    10,10,32,32,32,32,32,32,32,32,78,41,2,114,182,0,
+    0,0,114,129,0,0,0,41,4,114,172,0,0,0,114,128,
+    0,0,0,114,37,0,0,0,114,166,0,0,0,114,4,0,
+    0,0,114,4,0,0,0,114,6,0,0,0,218,11,102,105,
+    110,100,95,109,111,100,117,108,101,125,2,0,0,115,8,0,
+    0,0,0,7,18,1,12,1,7,2,122,33,87,105,110,100,
+    111,119,115,82,101,103,105,115,116,114,121,70,105,110,100,101,
+    114,46,102,105,110,100,95,109,111,100,117,108,101,41,12,114,
+    114,0,0,0,114,113,0,0,0,114,115,0,0,0,114,116,
+    0,0,0,114,176,0,0,0,114,175,0,0,0,114,174,0,
+    0,0,218,11,99,108,97,115,115,109,101,116,104,111,100,114,
+    173,0,0,0,114,179,0,0,0,114,182,0,0,0,114,183,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,114,4,0,
+    0,0,114,6,0,0,0,114,170,0,0,0,75,2,0,0,
+    115,20,0,0,0,12,2,6,3,6,3,6,2,6,2,18,
+    7,18,15,3,1,21,15,3,1,114,170,0,0,0,99,0,
+    0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,64,
+    0,0,0,115,70,0,0,0,101,0,0,90,1,0,100,0,
+    0,90,2,0,100,1,0,90,3,0,100,2,0,100,3,0,
+    132,0,0,90,4,0,100,4,0,100,5,0,132,0,0,90,
+    5,0,100,6,0,100,7,0,132,0,0,90,6,0,100,8,
+    0,100,9,0,132,0,0,90,7,0,100,10,0,83,41,11,
+    218,13,95,76,111,97,100,101,114,66,97,115,105,99,115,122,
+    83,66,97,115,101,32,99,108,97,115,115,32,111,102,32,99,
+    111,109,109,111,110,32,99,111,100,101,32,110,101,101,100,101,
+    100,32,98,121,32,98,111,116,104,32,83,111,117,114,99,101,
+    76,111,97,100,101,114,32,97,110,100,10,32,32,32,32,83,
+    111,117,114,99,101,108,101,115,115,70,105,108,101,76,111,97,
+    100,101,114,46,99,2,0,0,0,0,0,0,0,5,0,0,
+    0,3,0,0,0,67,0,0,0,115,88,0,0,0,116,0,
+    0,124,0,0,106,1,0,124,1,0,131,1,0,131,1,0,
+    100,1,0,25,125,2,0,124,2,0,106,2,0,100,2,0,
+    100,1,0,131,2,0,100,3,0,25,125,3,0,124,1,0,
+    106,3,0,100,2,0,131,1,0,100,4,0,25,125,4,0,
+    124,3,0,100,5,0,107,2,0,111,87,0,124,4,0,100,
+    5,0,107,3,0,83,41,6,122,141,67,111,110,99,114,101,
+    116,101,32,105,109,112,108,101,109,101,110,116,97,116,105,111,
+    110,32,111,102,32,73,110,115,112,101,99,116,76,111,97,100,
+    101,114,46,105,115,95,112,97,99,107,97,103,101,32,98,121,
+    32,99,104,101,99,107,105,110,103,32,105,102,10,32,32,32,
+    32,32,32,32,32,116,104,101,32,112,97,116,104,32,114,101,
+    116,117,114,110,101,100,32,98,121,32,103,101,116,95,102,105,
+    108,101,110,97,109,101,32,104,97,115,32,97,32,102,105,108,
+    101,110,97,109,101,32,111,102,32,39,95,95,105,110,105,116,
+    95,95,46,112,121,39,46,114,31,0,0,0,114,60,0,0,
+    0,114,61,0,0,0,114,58,0,0,0,218,8,95,95,105,
+    110,105,116,95,95,41,4,114,40,0,0,0,114,159,0,0,
+    0,114,36,0,0,0,114,34,0,0,0,41,5,114,110,0,
+    0,0,114,128,0,0,0,114,96,0,0,0,90,13,102,105,
+    108,101,110,97,109,101,95,98,97,115,101,90,9,116,97,105,
+    108,95,110,97,109,101,114,4,0,0,0,114,4,0,0,0,
+    114,6,0,0,0,114,161,0,0,0,144,2,0,0,115,8,
+    0,0,0,0,3,25,1,22,1,19,1,122,24,95,76,111,
+    97,100,101,114,66,97,115,105,99,115,46,105,115,95,112,97,
+    99,107,97,103,101,99,2,0,0,0,0,0,0,0,2,0,
+    0,0,1,0,0,0,67,0,0,0,115,4,0,0,0,100,
+    1,0,83,41,2,122,42,85,115,101,32,100,101,102,97,117,
+    108,116,32,115,101,109,97,110,116,105,99,115,32,102,111,114,
+    32,109,111,100,117,108,101,32,99,114,101,97,116,105,111,110,
+    46,78,114,4,0,0,0,41,2,114,110,0,0,0,114,166,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,218,13,99,114,101,97,116,101,95,109,111,100,117,108,
+    101,152,2,0,0,115,0,0,0,0,122,27,95,76,111,97,
+    100,101,114,66,97,115,105,99,115,46,99,114,101,97,116,101,
+    95,109,111,100,117,108,101,99,2,0,0,0,0,0,0,0,
+    3,0,0,0,4,0,0,0,67,0,0,0,115,80,0,0,
+    0,124,0,0,106,0,0,124,1,0,106,1,0,131,1,0,
+    125,2,0,124,2,0,100,1,0,107,8,0,114,54,0,116,
+    2,0,100,2,0,106,3,0,124,1,0,106,1,0,131,1,
+    0,131,1,0,130,1,0,116,4,0,106,5,0,116,6,0,
+    124,2,0,124,1,0,106,7,0,131,3,0,1,100,1,0,
+    83,41,3,122,19,69,120,101,99,117,116,101,32,116,104,101,
+    32,109,111,100,117,108,101,46,78,122,52,99,97,110,110,111,
+    116,32,108,111,97,100,32,109,111,100,117,108,101,32,123,33,
+    114,125,32,119,104,101,110,32,103,101,116,95,99,111,100,101,
+    40,41,32,114,101,116,117,114,110,115,32,78,111,110,101,41,
+    8,218,8,103,101,116,95,99,111,100,101,114,114,0,0,0,
+    114,109,0,0,0,114,49,0,0,0,114,123,0,0,0,218,
+    25,95,99,97,108,108,95,119,105,116,104,95,102,114,97,109,
+    101,115,95,114,101,109,111,118,101,100,218,4,101,120,101,99,
+    114,120,0,0,0,41,3,114,110,0,0,0,218,6,109,111,
+    100,117,108,101,114,148,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,11,101,120,101,99,95,109,
+    111,100,117,108,101,155,2,0,0,115,10,0,0,0,0,2,
+    18,1,12,1,9,1,15,1,122,25,95,76,111,97,100,101,
+    114,66,97,115,105,99,115,46,101,120,101,99,95,109,111,100,
+    117,108,101,99,2,0,0,0,0,0,0,0,2,0,0,0,
+    3,0,0,0,67,0,0,0,115,16,0,0,0,116,0,0,
+    106,1,0,124,0,0,124,1,0,131,2,0,83,41,1,78,
+    41,2,114,123,0,0,0,218,17,95,108,111,97,100,95,109,
+    111,100,117,108,101,95,115,104,105,109,41,2,114,110,0,0,
+    0,114,128,0,0,0,114,4,0,0,0,114,4,0,0,0,
+    114,6,0,0,0,218,11,108,111,97,100,95,109,111,100,117,
+    108,101,163,2,0,0,115,2,0,0,0,0,1,122,25,95,
+    76,111,97,100,101,114,66,97,115,105,99,115,46,108,111,97,
+    100,95,109,111,100,117,108,101,78,41,8,114,114,0,0,0,
+    114,113,0,0,0,114,115,0,0,0,114,116,0,0,0,114,
+    161,0,0,0,114,187,0,0,0,114,192,0,0,0,114,194,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,114,4,0,
+    0,0,114,6,0,0,0,114,185,0,0,0,139,2,0,0,
+    115,10,0,0,0,12,3,6,2,12,8,12,3,12,8,114,
+    185,0,0,0,99,0,0,0,0,0,0,0,0,0,0,0,
+    0,4,0,0,0,64,0,0,0,115,106,0,0,0,101,0,
+    0,90,1,0,100,0,0,90,2,0,100,1,0,100,2,0,
+    132,0,0,90,3,0,100,3,0,100,4,0,132,0,0,90,
+    4,0,100,5,0,100,6,0,132,0,0,90,5,0,100,7,
+    0,100,8,0,132,0,0,90,6,0,100,9,0,100,10,0,
+    132,0,0,90,7,0,100,11,0,100,18,0,100,13,0,100,
+    14,0,132,0,1,90,8,0,100,15,0,100,16,0,132,0,
+    0,90,9,0,100,17,0,83,41,19,218,12,83,111,117,114,
+    99,101,76,111,97,100,101,114,99,2,0,0,0,0,0,0,
+    0,2,0,0,0,1,0,0,0,67,0,0,0,115,10,0,
+    0,0,116,0,0,130,1,0,100,1,0,83,41,2,122,178,
     79,112,116,105,111,110,97,108,32,109,101,116,104,111,100,32,
-    119,104,105,99,104,32,119,114,105,116,101,115,32,100,97,116,
-    97,32,40,98,121,116,101,115,41,32,116,111,32,97,32,102,
-    105,108,101,32,112,97,116,104,32,40,97,32,115,116,114,41,
-    46,10,10,32,32,32,32,32,32,32,32,73,109,112,108,101,
-    109,101,110,116,105,110,103,32,116,104,105,115,32,109,101,116,
-    104,111,100,32,97,108,108,111,119,115,32,102,111,114,32,116,
-    104,101,32,119,114,105,116,105,110,103,32,111,102,32,98,121,
-    116,101,99,111,100,101,32,102,105,108,101,115,46,10,32,32,
-    32,32,32,32,32,32,78,114,4,0,0,0,41,3,114,108,
-    0,0,0,114,35,0,0,0,114,53,0,0,0,114,4,0,
-    0,0,114,4,0,0,0,114,5,0,0,0,114,198,0,0,
-    0,192,2,0,0,115,0,0,0,0,122,21,83,111,117,114,
-    99,101,76,111,97,100,101,114,46,115,101,116,95,100,97,116,
-    97,99,2,0,0,0,0,0,0,0,5,0,0,0,16,0,
-    0,0,67,0,0,0,115,105,0,0,0,124,0,0,106,0,
-    0,124,1,0,131,1,0,125,2,0,121,19,0,124,0,0,
-    106,1,0,124,2,0,131,1,0,125,3,0,87,110,58,0,
-    4,116,2,0,107,10,0,114,94,0,1,125,4,0,1,122,
-    26,0,116,3,0,100,1,0,100,2,0,124,1,0,131,1,
-    1,124,4,0,130,2,0,87,89,100,3,0,100,3,0,125,
-    4,0,126,4,0,88,110,1,0,88,116,4,0,124,3,0,
-    131,1,0,83,41,4,122,52,67,111,110,99,114,101,116,101,
-    32,105,109,112,108,101,109,101,110,116,97,116,105,111,110,32,
-    111,102,32,73,110,115,112,101,99,116,76,111,97,100,101,114,
-    46,103,101,116,95,115,111,117,114,99,101,46,122,39,115,111,
-    117,114,99,101,32,110,111,116,32,97,118,97,105,108,97,98,
-    108,101,32,116,104,114,111,117,103,104,32,103,101,116,95,100,
-    97,116,97,40,41,114,106,0,0,0,78,41,5,114,157,0,
-    0,0,218,8,103,101,116,95,100,97,116,97,114,40,0,0,
-    0,114,107,0,0,0,114,155,0,0,0,41,5,114,108,0,
-    0,0,114,126,0,0,0,114,35,0,0,0,114,153,0,0,
-    0,218,3,101,120,99,114,4,0,0,0,114,4,0,0,0,
-    114,5,0,0,0,218,10,103,101,116,95,115,111,117,114,99,
-    101,199,2,0,0,115,14,0,0,0,0,2,15,1,3,1,
-    19,1,18,1,9,1,31,1,122,23,83,111,117,114,99,101,
-    76,111,97,100,101,114,46,103,101,116,95,115,111,117,114,99,
-    101,218,9,95,111,112,116,105,109,105,122,101,114,29,0,0,
-    0,99,3,0,0,0,1,0,0,0,4,0,0,0,9,0,
-    0,0,67,0,0,0,115,34,0,0,0,116,0,0,106,1,
-    0,116,2,0,124,1,0,124,2,0,100,1,0,100,2,0,
-    100,3,0,100,4,0,124,3,0,131,4,2,83,41,5,122,
-    130,82,101,116,117,114,110,32,116,104,101,32,99,111,100,101,
-    32,111,98,106,101,99,116,32,99,111,109,112,105,108,101,100,
-    32,102,114,111,109,32,115,111,117,114,99,101,46,10,10,32,
-    32,32,32,32,32,32,32,84,104,101,32,39,100,97,116,97,
-    39,32,97,114,103,117,109,101,110,116,32,99,97,110,32,98,
-    101,32,97,110,121,32,111,98,106,101,99,116,32,116,121,112,
-    101,32,116,104,97,116,32,99,111,109,112,105,108,101,40,41,
-    32,115,117,112,112,111,114,116,115,46,10,32,32,32,32,32,
-    32,32,32,114,189,0,0,0,218,12,100,111,110,116,95,105,
-    110,104,101,114,105,116,84,114,68,0,0,0,41,3,114,121,
-    0,0,0,114,188,0,0,0,218,7,99,111,109,112,105,108,
-    101,41,4,114,108,0,0,0,114,53,0,0,0,114,35,0,
-    0,0,114,203,0,0,0,114,4,0,0,0,114,4,0,0,
-    0,114,5,0,0,0,218,14,115,111,117,114,99,101,95,116,
-    111,95,99,111,100,101,209,2,0,0,115,4,0,0,0,0,
-    5,21,1,122,27,83,111,117,114,99,101,76,111,97,100,101,
-    114,46,115,111,117,114,99,101,95,116,111,95,99,111,100,101,
-    99,2,0,0,0,0,0,0,0,10,0,0,0,43,0,0,
-    0,67,0,0,0,115,174,1,0,0,124,0,0,106,0,0,
-    124,1,0,131,1,0,125,2,0,100,1,0,125,3,0,121,
-    16,0,116,1,0,124,2,0,131,1,0,125,4,0,87,110,
-    24,0,4,116,2,0,107,10,0,114,63,0,1,1,1,100,
-    1,0,125,4,0,89,110,202,0,88,121,19,0,124,0,0,
-    106,3,0,124,2,0,131,1,0,125,5,0,87,110,18,0,
-    4,116,4,0,107,10,0,114,103,0,1,1,1,89,110,162,
-    0,88,116,5,0,124,5,0,100,2,0,25,131,1,0,125,
-    3,0,121,19,0,124,0,0,106,6,0,124,4,0,131,1,
-    0,125,6,0,87,110,18,0,4,116,7,0,107,10,0,114,
-    159,0,1,1,1,89,110,106,0,88,121,34,0,116,8,0,
-    124,6,0,100,3,0,124,5,0,100,4,0,124,1,0,100,
-    5,0,124,4,0,131,1,3,125,7,0,87,110,24,0,4,
-    116,9,0,116,10,0,102,2,0,107,10,0,114,220,0,1,
-    1,1,89,110,45,0,88,116,11,0,100,6,0,124,4,0,
-    124,2,0,131,3,0,1,116,12,0,124,7,0,100,4,0,
-    124,1,0,100,7,0,124,4,0,100,8,0,124,2,0,131,
-    1,3,83,124,0,0,106,6,0,124,2,0,131,1,0,125,
-    8,0,124,0,0,106,13,0,124,8,0,124,2,0,131,2,
-    0,125,9,0,116,11,0,100,9,0,124,2,0,131,2,0,
-    1,116,14,0,106,15,0,12,114,170,1,124,4,0,100,1,
-    0,107,9,0,114,170,1,124,3,0,100,1,0,107,9,0,
-    114,170,1,116,16,0,124,9,0,124,3,0,116,17,0,124,
-    8,0,131,1,0,131,3,0,125,6,0,121,36,0,124,0,
-    0,106,18,0,124,2,0,124,4,0,124,6,0,131,3,0,
-    1,116,11,0,100,10,0,124,4,0,131,2,0,1,87,110,
-    18,0,4,116,2,0,107,10,0,114,169,1,1,1,1,89,
-    110,1,0,88,124,9,0,83,41,11,122,190,67,111,110,99,
+    116,104,97,116,32,114,101,116,117,114,110,115,32,116,104,101,
+    32,109,111,100,105,102,105,99,97,116,105,111,110,32,116,105,
+    109,101,32,40,97,110,32,105,110,116,41,32,102,111,114,32,
+    116,104,101,10,32,32,32,32,32,32,32,32,115,112,101,99,
+    105,102,105,101,100,32,112,97,116,104,44,32,119,104,101,114,
+    101,32,112,97,116,104,32,105,115,32,97,32,115,116,114,46,
+    10,10,32,32,32,32,32,32,32,32,82,97,105,115,101,115,
+    32,73,79,69,114,114,111,114,32,119,104,101,110,32,116,104,
+    101,32,112,97,116,104,32,99,97,110,110,111,116,32,98,101,
+    32,104,97,110,100,108,101,100,46,10,32,32,32,32,32,32,
+    32,32,78,41,1,218,7,73,79,69,114,114,111,114,41,2,
+    114,110,0,0,0,114,37,0,0,0,114,4,0,0,0,114,
+    4,0,0,0,114,6,0,0,0,218,10,112,97,116,104,95,
+    109,116,105,109,101,169,2,0,0,115,2,0,0,0,0,6,
+    122,23,83,111,117,114,99,101,76,111,97,100,101,114,46,112,
+    97,116,104,95,109,116,105,109,101,99,2,0,0,0,0,0,
+    0,0,2,0,0,0,3,0,0,0,67,0,0,0,115,19,
+    0,0,0,100,1,0,124,0,0,106,0,0,124,1,0,131,
+    1,0,105,1,0,83,41,2,97,170,1,0,0,79,112,116,
+    105,111,110,97,108,32,109,101,116,104,111,100,32,114,101,116,
+    117,114,110,105,110,103,32,97,32,109,101,116,97,100,97,116,
+    97,32,100,105,99,116,32,102,111,114,32,116,104,101,32,115,
+    112,101,99,105,102,105,101,100,32,112,97,116,104,10,32,32,
+    32,32,32,32,32,32,116,111,32,98,121,32,116,104,101,32,
+    112,97,116,104,32,40,115,116,114,41,46,10,32,32,32,32,
+    32,32,32,32,80,111,115,115,105,98,108,101,32,107,101,121,
+    115,58,10,32,32,32,32,32,32,32,32,45,32,39,109,116,
+    105,109,101,39,32,40,109,97,110,100,97,116,111,114,121,41,
+    32,105,115,32,116,104,101,32,110,117,109,101,114,105,99,32,
+    116,105,109,101,115,116,97,109,112,32,111,102,32,108,97,115,
+    116,32,115,111,117,114,99,101,10,32,32,32,32,32,32,32,
+    32,32,32,99,111,100,101,32,109,111,100,105,102,105,99,97,
+    116,105,111,110,59,10,32,32,32,32,32,32,32,32,45,32,
+    39,115,105,122,101,39,32,40,111,112,116,105,111,110,97,108,
+    41,32,105,115,32,116,104,101,32,115,105,122,101,32,105,110,
+    32,98,121,116,101,115,32,111,102,32,116,104,101,32,115,111,
+    117,114,99,101,32,99,111,100,101,46,10,10,32,32,32,32,
+    32,32,32,32,73,109,112,108,101,109,101,110,116,105,110,103,
+    32,116,104,105,115,32,109,101,116,104,111,100,32,97,108,108,
+    111,119,115,32,116,104,101,32,108,111,97,100,101,114,32,116,
+    111,32,114,101,97,100,32,98,121,116,101,99,111,100,101,32,
+    102,105,108,101,115,46,10,32,32,32,32,32,32,32,32,82,
+    97,105,115,101,115,32,73,79,69,114,114,111,114,32,119,104,
+    101,110,32,116,104,101,32,112,97,116,104,32,99,97,110,110,
+    111,116,32,98,101,32,104,97,110,100,108,101,100,46,10,32,
+    32,32,32,32,32,32,32,114,135,0,0,0,41,1,114,197,
+    0,0,0,41,2,114,110,0,0,0,114,37,0,0,0,114,
+    4,0,0,0,114,4,0,0,0,114,6,0,0,0,218,10,
+    112,97,116,104,95,115,116,97,116,115,177,2,0,0,115,2,
+    0,0,0,0,11,122,23,83,111,117,114,99,101,76,111,97,
+    100,101,114,46,112,97,116,104,95,115,116,97,116,115,99,4,
+    0,0,0,0,0,0,0,4,0,0,0,3,0,0,0,67,
+    0,0,0,115,16,0,0,0,124,0,0,106,0,0,124,2,
+    0,124,3,0,131,2,0,83,41,1,122,228,79,112,116,105,
+    111,110,97,108,32,109,101,116,104,111,100,32,119,104,105,99,
+    104,32,119,114,105,116,101,115,32,100,97,116,97,32,40,98,
+    121,116,101,115,41,32,116,111,32,97,32,102,105,108,101,32,
+    112,97,116,104,32,40,97,32,115,116,114,41,46,10,10,32,
+    32,32,32,32,32,32,32,73,109,112,108,101,109,101,110,116,
+    105,110,103,32,116,104,105,115,32,109,101,116,104,111,100,32,
+    97,108,108,111,119,115,32,102,111,114,32,116,104,101,32,119,
+    114,105,116,105,110,103,32,111,102,32,98,121,116,101,99,111,
+    100,101,32,102,105,108,101,115,46,10,10,32,32,32,32,32,
+    32,32,32,84,104,101,32,115,111,117,114,99,101,32,112,97,
+    116,104,32,105,115,32,110,101,101,100,101,100,32,105,110,32,
+    111,114,100,101,114,32,116,111,32,99,111,114,114,101,99,116,
+    108,121,32,116,114,97,110,115,102,101,114,32,112,101,114,109,
+    105,115,115,105,111,110,115,10,32,32,32,32,32,32,32,32,
+    41,1,218,8,115,101,116,95,100,97,116,97,41,4,114,110,
+    0,0,0,114,92,0,0,0,90,10,99,97,99,104,101,95,
+    112,97,116,104,114,55,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,15,95,99,97,99,104,101,
+    95,98,121,116,101,99,111,100,101,190,2,0,0,115,2,0,
+    0,0,0,8,122,28,83,111,117,114,99,101,76,111,97,100,
+    101,114,46,95,99,97,99,104,101,95,98,121,116,101,99,111,
+    100,101,99,3,0,0,0,0,0,0,0,3,0,0,0,1,
+    0,0,0,67,0,0,0,115,4,0,0,0,100,1,0,83,
+    41,2,122,150,79,112,116,105,111,110,97,108,32,109,101,116,
+    104,111,100,32,119,104,105,99,104,32,119,114,105,116,101,115,
+    32,100,97,116,97,32,40,98,121,116,101,115,41,32,116,111,
+    32,97,32,102,105,108,101,32,112,97,116,104,32,40,97,32,
+    115,116,114,41,46,10,10,32,32,32,32,32,32,32,32,73,
+    109,112,108,101,109,101,110,116,105,110,103,32,116,104,105,115,
+    32,109,101,116,104,111,100,32,97,108,108,111,119,115,32,102,
+    111,114,32,116,104,101,32,119,114,105,116,105,110,103,32,111,
+    102,32,98,121,116,101,99,111,100,101,32,102,105,108,101,115,
+    46,10,32,32,32,32,32,32,32,32,78,114,4,0,0,0,
+    41,3,114,110,0,0,0,114,37,0,0,0,114,55,0,0,
+    0,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    114,199,0,0,0,200,2,0,0,115,0,0,0,0,122,21,
+    83,111,117,114,99,101,76,111,97,100,101,114,46,115,101,116,
+    95,100,97,116,97,99,2,0,0,0,0,0,0,0,5,0,
+    0,0,16,0,0,0,67,0,0,0,115,105,0,0,0,124,
+    0,0,106,0,0,124,1,0,131,1,0,125,2,0,121,19,
+    0,124,0,0,106,1,0,124,2,0,131,1,0,125,3,0,
+    87,110,58,0,4,116,2,0,107,10,0,114,94,0,1,125,
+    4,0,1,122,26,0,116,3,0,100,1,0,100,2,0,124,
+    1,0,131,1,1,124,4,0,130,2,0,87,89,100,3,0,
+    100,3,0,125,4,0,126,4,0,88,110,1,0,88,116,4,
+    0,124,3,0,131,1,0,83,41,4,122,52,67,111,110,99,
     114,101,116,101,32,105,109,112,108,101,109,101,110,116,97,116,
     105,111,110,32,111,102,32,73,110,115,112,101,99,116,76,111,
-    97,100,101,114,46,103,101,116,95,99,111,100,101,46,10,10,
-    32,32,32,32,32,32,32,32,82,101,97,100,105,110,103,32,
-    111,102,32,98,121,116,101,99,111,100,101,32,114,101,113,117,
-    105,114,101,115,32,112,97,116,104,95,115,116,97,116,115,32,
-    116,111,32,98,101,32,105,109,112,108,101,109,101,110,116,101,
-    100,46,32,84,111,32,119,114,105,116,101,10,32,32,32,32,
-    32,32,32,32,98,121,116,101,99,111,100,101,44,32,115,101,
-    116,95,100,97,116,97,32,109,117,115,116,32,97,108,115,111,
-    32,98,101,32,105,109,112,108,101,109,101,110,116,101,100,46,
-    10,10,32,32,32,32,32,32,32,32,78,114,133,0,0,0,
-    114,138,0,0,0,114,106,0,0,0,114,35,0,0,0,122,
-    13,123,125,32,109,97,116,99,104,101,115,32,123,125,114,89,
-    0,0,0,114,90,0,0,0,122,19,99,111,100,101,32,111,
-    98,106,101,99,116,32,102,114,111,109,32,123,125,122,10,119,
-    114,111,116,101,32,123,33,114,125,41,19,114,157,0,0,0,
-    114,79,0,0,0,114,66,0,0,0,114,197,0,0,0,114,
-    195,0,0,0,114,14,0,0,0,114,200,0,0,0,114,40,
-    0,0,0,114,141,0,0,0,114,107,0,0,0,114,136,0,
-    0,0,114,105,0,0,0,114,147,0,0,0,114,206,0,0,
-    0,114,7,0,0,0,218,19,100,111,110,116,95,119,114,105,
-    116,101,95,98,121,116,101,99,111,100,101,114,150,0,0,0,
-    114,31,0,0,0,114,199,0,0,0,41,10,114,108,0,0,
-    0,114,126,0,0,0,114,90,0,0,0,114,139,0,0,0,
-    114,89,0,0,0,218,2,115,116,114,53,0,0,0,218,10,
-    98,121,116,101,115,95,100,97,116,97,114,153,0,0,0,90,
-    11,99,111,100,101,95,111,98,106,101,99,116,114,4,0,0,
-    0,114,4,0,0,0,114,5,0,0,0,114,187,0,0,0,
-    217,2,0,0,115,78,0,0,0,0,7,15,1,6,1,3,
-    1,16,1,13,1,11,2,3,1,19,1,13,1,5,2,16,
-    1,3,1,19,1,13,1,5,2,3,1,9,1,12,1,13,
-    1,19,1,5,2,9,1,7,1,15,1,6,1,7,1,15,
-    1,18,1,13,1,22,1,12,1,9,1,15,1,3,1,19,
-    1,17,1,13,1,5,1,122,21,83,111,117,114,99,101,76,
-    111,97,100,101,114,46,103,101,116,95,99,111,100,101,78,114,
-    87,0,0,0,41,10,114,112,0,0,0,114,111,0,0,0,
-    114,113,0,0,0,114,196,0,0,0,114,197,0,0,0,114,
-    199,0,0,0,114,198,0,0,0,114,202,0,0,0,114,206,
-    0,0,0,114,187,0,0,0,114,4,0,0,0,114,4,0,
-    0,0,114,4,0,0,0,114,5,0,0,0,114,194,0,0,
-    0,159,2,0,0,115,14,0,0,0,12,2,12,8,12,13,
-    12,10,12,7,12,10,18,8,114,194,0,0,0,99,0,0,
-    0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,
-    0,0,115,112,0,0,0,101,0,0,90,1,0,100,0,0,
-    90,2,0,100,1,0,90,3,0,100,2,0,100,3,0,132,
-    0,0,90,4,0,100,4,0,100,5,0,132,0,0,90,5,
-    0,100,6,0,100,7,0,132,0,0,90,6,0,101,7,0,
-    135,0,0,102,1,0,100,8,0,100,9,0,134,0,0,131,
-    1,0,90,8,0,101,7,0,100,10,0,100,11,0,132,0,
-    0,131,1,0,90,9,0,100,12,0,100,13,0,132,0,0,
-    90,10,0,135,0,0,83,41,14,218,10,70,105,108,101,76,
-    111,97,100,101,114,122,103,66,97,115,101,32,102,105,108,101,
-    32,108,111,97,100,101,114,32,99,108,97,115,115,32,119,104,
-    105,99,104,32,105,109,112,108,101,109,101,110,116,115,32,116,
-    104,101,32,108,111,97,100,101,114,32,112,114,111,116,111,99,
-    111,108,32,109,101,116,104,111,100,115,32,116,104,97,116,10,
-    32,32,32,32,114,101,113,117,105,114,101,32,102,105,108,101,
-    32,115,121,115,116,101,109,32,117,115,97,103,101,46,99,3,
-    0,0,0,0,0,0,0,3,0,0,0,2,0,0,0,67,
-    0,0,0,115,22,0,0,0,124,1,0,124,0,0,95,0,
-    0,124,2,0,124,0,0,95,1,0,100,1,0,83,41,2,
-    122,75,67,97,99,104,101,32,116,104,101,32,109,111,100,117,
-    108,101,32,110,97,109,101,32,97,110,100,32,116,104,101,32,
-    112,97,116,104,32,116,111,32,116,104,101,32,102,105,108,101,
-    32,102,111,117,110,100,32,98,121,32,116,104,101,10,32,32,
-    32,32,32,32,32,32,102,105,110,100,101,114,46,78,41,2,
-    114,106,0,0,0,114,35,0,0,0,41,3,114,108,0,0,
-    0,114,126,0,0,0,114,35,0,0,0,114,4,0,0,0,
-    114,4,0,0,0,114,5,0,0,0,114,185,0,0,0,18,
-    3,0,0,115,4,0,0,0,0,3,9,1,122,19,70,105,
-    108,101,76,111,97,100,101,114,46,95,95,105,110,105,116,95,
-    95,99,2,0,0,0,0,0,0,0,2,0,0,0,2,0,
-    0,0,67,0,0,0,115,34,0,0,0,124,0,0,106,0,
-    0,124,1,0,106,0,0,107,2,0,111,33,0,124,0,0,
-    106,1,0,124,1,0,106,1,0,107,2,0,83,41,1,78,
-    41,2,218,9,95,95,99,108,97,115,115,95,95,114,118,0,
-    0,0,41,2,114,108,0,0,0,218,5,111,116,104,101,114,
-    114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,218,
-    6,95,95,101,113,95,95,24,3,0,0,115,4,0,0,0,
-    0,1,18,1,122,17,70,105,108,101,76,111,97,100,101,114,
-    46,95,95,101,113,95,95,99,1,0,0,0,0,0,0,0,
-    1,0,0,0,3,0,0,0,67,0,0,0,115,26,0,0,
-    0,116,0,0,124,0,0,106,1,0,131,1,0,116,0,0,
-    124,0,0,106,2,0,131,1,0,65,83,41,1,78,41,3,
-    218,4,104,97,115,104,114,106,0,0,0,114,35,0,0,0,
-    41,1,114,108,0,0,0,114,4,0,0,0,114,4,0,0,
-    0,114,5,0,0,0,218,8,95,95,104,97,115,104,95,95,
-    28,3,0,0,115,2,0,0,0,0,1,122,19,70,105,108,
-    101,76,111,97,100,101,114,46,95,95,104,97,115,104,95,95,
-    99,2,0,0,0,0,0,0,0,2,0,0,0,3,0,0,
-    0,3,0,0,0,115,22,0,0,0,116,0,0,116,1,0,
-    124,0,0,131,2,0,106,2,0,124,1,0,131,1,0,83,
-    41,1,122,100,76,111,97,100,32,97,32,109,111,100,117,108,
-    101,32,102,114,111,109,32,97,32,102,105,108,101,46,10,10,
-    32,32,32,32,32,32,32,32,84,104,105,115,32,109,101,116,
-    104,111,100,32,105,115,32,100,101,112,114,101,99,97,116,101,
-    100,46,32,32,85,115,101,32,101,120,101,99,95,109,111,100,
-    117,108,101,40,41,32,105,110,115,116,101,97,100,46,10,10,
-    32,32,32,32,32,32,32,32,41,3,218,5,115,117,112,101,
-    114,114,210,0,0,0,114,193,0,0,0,41,2,114,108,0,
-    0,0,114,126,0,0,0,41,1,114,211,0,0,0,114,4,
-    0,0,0,114,5,0,0,0,114,193,0,0,0,31,3,0,
-    0,115,2,0,0,0,0,10,122,22,70,105,108,101,76,111,
-    97,100,101,114,46,108,111,97,100,95,109,111,100,117,108,101,
-    99,2,0,0,0,0,0,0,0,2,0,0,0,1,0,0,
-    0,67,0,0,0,115,7,0,0,0,124,0,0,106,0,0,
-    83,41,1,122,58,82,101,116,117,114,110,32,116,104,101,32,
-    112,97,116,104,32,116,111,32,116,104,101,32,115,111,117,114,
-    99,101,32,102,105,108,101,32,97,115,32,102,111,117,110,100,
-    32,98,121,32,116,104,101,32,102,105,110,100,101,114,46,41,
-    1,114,35,0,0,0,41,2,114,108,0,0,0,114,126,0,
-    0,0,114,4,0,0,0,114,4,0,0,0,114,5,0,0,
-    0,114,157,0,0,0,43,3,0,0,115,2,0,0,0,0,
-    3,122,23,70,105,108,101,76,111,97,100,101,114,46,103,101,
-    116,95,102,105,108,101,110,97,109,101,99,2,0,0,0,0,
-    0,0,0,3,0,0,0,9,0,0,0,67,0,0,0,115,
-    42,0,0,0,116,0,0,106,1,0,124,1,0,100,1,0,
-    131,2,0,143,17,0,125,2,0,124,2,0,106,2,0,131,
-    0,0,83,87,100,2,0,81,82,88,100,2,0,83,41,3,
-    122,39,82,101,116,117,114,110,32,116,104,101,32,100,97,116,
-    97,32,102,114,111,109,32,112,97,116,104,32,97,115,32,114,
-    97,119,32,98,121,116,101,115,46,218,1,114,78,41,3,114,
-    49,0,0,0,114,50,0,0,0,90,4,114,101,97,100,41,
-    3,114,108,0,0,0,114,35,0,0,0,114,54,0,0,0,
-    114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,114,
-    200,0,0,0,48,3,0,0,115,4,0,0,0,0,2,21,
-    1,122,19,70,105,108,101,76,111,97,100,101,114,46,103,101,
-    116,95,100,97,116,97,41,11,114,112,0,0,0,114,111,0,
-    0,0,114,113,0,0,0,114,114,0,0,0,114,185,0,0,
-    0,114,213,0,0,0,114,215,0,0,0,114,123,0,0,0,
-    114,193,0,0,0,114,157,0,0,0,114,200,0,0,0,114,
-    4,0,0,0,114,4,0,0,0,41,1,114,211,0,0,0,
-    114,5,0,0,0,114,210,0,0,0,13,3,0,0,115,14,
-    0,0,0,12,3,6,2,12,6,12,4,12,3,24,12,18,
-    5,114,210,0,0,0,99,0,0,0,0,0,0,0,0,0,
-    0,0,0,4,0,0,0,64,0,0,0,115,64,0,0,0,
-    101,0,0,90,1,0,100,0,0,90,2,0,100,1,0,90,
-    3,0,100,2,0,100,3,0,132,0,0,90,4,0,100,4,
-    0,100,5,0,132,0,0,90,5,0,100,6,0,100,7,0,
-    100,8,0,100,9,0,132,0,1,90,6,0,100,10,0,83,
-    41,11,218,16,83,111,117,114,99,101,70,105,108,101,76,111,
-    97,100,101,114,122,62,67,111,110,99,114,101,116,101,32,105,
-    109,112,108,101,109,101,110,116,97,116,105,111,110,32,111,102,
-    32,83,111,117,114,99,101,76,111,97,100,101,114,32,117,115,
-    105,110,103,32,116,104,101,32,102,105,108,101,32,115,121,115,
-    116,101,109,46,99,2,0,0,0,0,0,0,0,3,0,0,
-    0,4,0,0,0,67,0,0,0,115,34,0,0,0,116,0,
-    0,124,1,0,131,1,0,125,2,0,100,1,0,124,2,0,
-    106,1,0,100,2,0,124,2,0,106,2,0,105,2,0,83,
-    41,3,122,33,82,101,116,117,114,110,32,116,104,101,32,109,
-    101,116,97,100,97,116,97,32,102,111,114,32,116,104,101,32,
-    112,97,116,104,46,114,133,0,0,0,114,134,0,0,0,41,
-    3,114,39,0,0,0,218,8,115,116,95,109,116,105,109,101,
-    90,7,115,116,95,115,105,122,101,41,3,114,108,0,0,0,
-    114,35,0,0,0,114,208,0,0,0,114,4,0,0,0,114,
-    4,0,0,0,114,5,0,0,0,114,197,0,0,0,58,3,
-    0,0,115,4,0,0,0,0,2,12,1,122,27,83,111,117,
-    114,99,101,70,105,108,101,76,111,97,100,101,114,46,112,97,
-    116,104,95,115,116,97,116,115,99,4,0,0,0,0,0,0,
-    0,5,0,0,0,5,0,0,0,67,0,0,0,115,34,0,
-    0,0,116,0,0,124,1,0,131,1,0,125,4,0,124,0,
-    0,106,1,0,124,2,0,124,3,0,100,1,0,124,4,0,
-    131,2,1,83,41,2,78,218,5,95,109,111,100,101,41,2,
-    114,97,0,0,0,114,198,0,0,0,41,5,114,108,0,0,
-    0,114,90,0,0,0,114,89,0,0,0,114,53,0,0,0,
-    114,42,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,114,199,0,0,0,63,3,0,0,115,4,0,
-    0,0,0,2,12,1,122,32,83,111,117,114,99,101,70,105,
-    108,101,76,111,97,100,101,114,46,95,99,97,99,104,101,95,
-    98,121,116,101,99,111,100,101,114,220,0,0,0,105,182,1,
-    0,0,99,3,0,0,0,1,0,0,0,9,0,0,0,17,
-    0,0,0,67,0,0,0,115,53,1,0,0,116,0,0,124,
-    1,0,131,1,0,92,2,0,125,4,0,125,5,0,103,0,
-    0,125,6,0,120,54,0,124,4,0,114,80,0,116,1,0,
-    124,4,0,131,1,0,12,114,80,0,116,0,0,124,4,0,
-    131,1,0,92,2,0,125,4,0,125,7,0,124,6,0,106,
-    2,0,124,7,0,131,1,0,1,113,27,0,87,120,132,0,
-    116,3,0,124,6,0,131,1,0,68,93,118,0,125,7,0,
-    116,4,0,124,4,0,124,7,0,131,2,0,125,4,0,121,
-    17,0,116,5,0,106,6,0,124,4,0,131,1,0,1,87,
-    113,94,0,4,116,7,0,107,10,0,114,155,0,1,1,1,
-    119,94,0,89,113,94,0,4,116,8,0,107,10,0,114,211,
-    0,1,125,8,0,1,122,25,0,116,9,0,100,1,0,124,
-    4,0,124,8,0,131,3,0,1,100,2,0,83,87,89,100,
-    2,0,100,2,0,125,8,0,126,8,0,88,113,94,0,88,
-    113,94,0,87,121,33,0,116,10,0,124,1,0,124,2,0,
-    124,3,0,131,3,0,1,116,9,0,100,3,0,124,1,0,
-    131,2,0,1,87,110,53,0,4,116,8,0,107,10,0,114,
-    48,1,1,125,8,0,1,122,21,0,116,9,0,100,1,0,
-    124,1,0,124,8,0,131,3,0,1,87,89,100,2,0,100,
-    2,0,125,8,0,126,8,0,88,110,1,0,88,100,2,0,
-    83,41,4,122,27,87,114,105,116,101,32,98,121,116,101,115,
-    32,100,97,116,97,32,116,111,32,97,32,102,105,108,101,46,
-    122,27,99,111,117,108,100,32,110,111,116,32,99,114,101,97,
-    116,101,32,123,33,114,125,58,32,123,33,114,125,78,122,12,
-    99,114,101,97,116,101,100,32,123,33,114,125,41,11,114,38,
-    0,0,0,114,46,0,0,0,114,163,0,0,0,114,33,0,
-    0,0,114,28,0,0,0,114,3,0,0,0,90,5,109,107,
-    100,105,114,218,15,70,105,108,101,69,120,105,115,116,115,69,
-    114,114,111,114,114,40,0,0,0,114,105,0,0,0,114,55,
-    0,0,0,41,9,114,108,0,0,0,114,35,0,0,0,114,
-    53,0,0,0,114,220,0,0,0,218,6,112,97,114,101,110,
-    116,114,94,0,0,0,114,27,0,0,0,114,23,0,0,0,
-    114,201,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,114,198,0,0,0,68,3,0,0,115,38,0,
-    0,0,0,2,18,1,6,2,22,1,18,1,17,2,19,1,
-    15,1,3,1,17,1,13,2,7,1,18,3,16,1,27,1,
-    3,1,16,1,17,1,18,2,122,25,83,111,117,114,99,101,
-    70,105,108,101,76,111,97,100,101,114,46,115,101,116,95,100,
-    97,116,97,78,41,7,114,112,0,0,0,114,111,0,0,0,
-    114,113,0,0,0,114,114,0,0,0,114,197,0,0,0,114,
-    199,0,0,0,114,198,0,0,0,114,4,0,0,0,114,4,
-    0,0,0,114,4,0,0,0,114,5,0,0,0,114,218,0,
-    0,0,54,3,0,0,115,8,0,0,0,12,2,6,2,12,
-    5,12,5,114,218,0,0,0,99,0,0,0,0,0,0,0,
-    0,0,0,0,0,2,0,0,0,64,0,0,0,115,46,0,
-    0,0,101,0,0,90,1,0,100,0,0,90,2,0,100,1,
-    0,90,3,0,100,2,0,100,3,0,132,0,0,90,4,0,
-    100,4,0,100,5,0,132,0,0,90,5,0,100,6,0,83,
-    41,7,218,20,83,111,117,114,99,101,108,101,115,115,70,105,
-    108,101,76,111,97,100,101,114,122,45,76,111,97,100,101,114,
-    32,119,104,105,99,104,32,104,97,110,100,108,101,115,32,115,
-    111,117,114,99,101,108,101,115,115,32,102,105,108,101,32,105,
-    109,112,111,114,116,115,46,99,2,0,0,0,0,0,0,0,
-    5,0,0,0,6,0,0,0,67,0,0,0,115,76,0,0,
-    0,124,0,0,106,0,0,124,1,0,131,1,0,125,2,0,
-    124,0,0,106,1,0,124,2,0,131,1,0,125,3,0,116,
-    2,0,124,3,0,100,1,0,124,1,0,100,2,0,124,2,
-    0,131,1,2,125,4,0,116,3,0,124,4,0,100,1,0,
-    124,1,0,100,3,0,124,2,0,131,1,2,83,41,4,78,
-    114,106,0,0,0,114,35,0,0,0,114,89,0,0,0,41,
-    4,114,157,0,0,0,114,200,0,0,0,114,141,0,0,0,
-    114,147,0,0,0,41,5,114,108,0,0,0,114,126,0,0,
-    0,114,35,0,0,0,114,53,0,0,0,114,209,0,0,0,
-    114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,114,
-    187,0,0,0,101,3,0,0,115,8,0,0,0,0,1,15,
-    1,15,1,24,1,122,29,83,111,117,114,99,101,108,101,115,
-    115,70,105,108,101,76,111,97,100,101,114,46,103,101,116,95,
-    99,111,100,101,99,2,0,0,0,0,0,0,0,2,0,0,
-    0,1,0,0,0,67,0,0,0,115,4,0,0,0,100,1,
-    0,83,41,2,122,39,82,101,116,117,114,110,32,78,111,110,
-    101,32,97,115,32,116,104,101,114,101,32,105,115,32,110,111,
-    32,115,111,117,114,99,101,32,99,111,100,101,46,78,114,4,
-    0,0,0,41,2,114,108,0,0,0,114,126,0,0,0,114,
-    4,0,0,0,114,4,0,0,0,114,5,0,0,0,114,202,
-    0,0,0,107,3,0,0,115,2,0,0,0,0,2,122,31,
-    83,111,117,114,99,101,108,101,115,115,70,105,108,101,76,111,
-    97,100,101,114,46,103,101,116,95,115,111,117,114,99,101,78,
-    41,6,114,112,0,0,0,114,111,0,0,0,114,113,0,0,
-    0,114,114,0,0,0,114,187,0,0,0,114,202,0,0,0,
-    114,4,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,114,223,0,0,0,97,3,0,0,115,6,0,
-    0,0,12,2,6,2,12,6,114,223,0,0,0,99,0,0,
-    0,0,0,0,0,0,0,0,0,0,3,0,0,0,64,0,
-    0,0,115,136,0,0,0,101,0,0,90,1,0,100,0,0,
-    90,2,0,100,1,0,90,3,0,100,2,0,100,3,0,132,
-    0,0,90,4,0,100,4,0,100,5,0,132,0,0,90,5,
-    0,100,6,0,100,7,0,132,0,0,90,6,0,100,8,0,
-    100,9,0,132,0,0,90,7,0,100,10,0,100,11,0,132,
-    0,0,90,8,0,100,12,0,100,13,0,132,0,0,90,9,
-    0,100,14,0,100,15,0,132,0,0,90,10,0,100,16,0,
-    100,17,0,132,0,0,90,11,0,101,12,0,100,18,0,100,
-    19,0,132,0,0,131,1,0,90,13,0,100,20,0,83,41,
-    21,218,19,69,120,116,101,110,115,105,111,110,70,105,108,101,
-    76,111,97,100,101,114,122,93,76,111,97,100,101,114,32,102,
-    111,114,32,101,120,116,101,110,115,105,111,110,32,109,111,100,
-    117,108,101,115,46,10,10,32,32,32,32,84,104,101,32,99,
-    111,110,115,116,114,117,99,116,111,114,32,105,115,32,100,101,
-    115,105,103,110,101,100,32,116,111,32,119,111,114,107,32,119,
-    105,116,104,32,70,105,108,101,70,105,110,100,101,114,46,10,
-    10,32,32,32,32,99,3,0,0,0,0,0,0,0,3,0,
-    0,0,2,0,0,0,67,0,0,0,115,22,0,0,0,124,
-    1,0,124,0,0,95,0,0,124,2,0,124,0,0,95,1,
-    0,100,0,0,83,41,1,78,41,2,114,106,0,0,0,114,
-    35,0,0,0,41,3,114,108,0,0,0,114,106,0,0,0,
-    114,35,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,114,185,0,0,0,124,3,0,0,115,4,0,
-    0,0,0,1,9,1,122,28,69,120,116,101,110,115,105,111,
-    110,70,105,108,101,76,111,97,100,101,114,46,95,95,105,110,
-    105,116,95,95,99,2,0,0,0,0,0,0,0,2,0,0,
-    0,2,0,0,0,67,0,0,0,115,34,0,0,0,124,0,
-    0,106,0,0,124,1,0,106,0,0,107,2,0,111,33,0,
-    124,0,0,106,1,0,124,1,0,106,1,0,107,2,0,83,
-    41,1,78,41,2,114,211,0,0,0,114,118,0,0,0,41,
-    2,114,108,0,0,0,114,212,0,0,0,114,4,0,0,0,
-    114,4,0,0,0,114,5,0,0,0,114,213,0,0,0,128,
-    3,0,0,115,4,0,0,0,0,1,18,1,122,26,69,120,
-    116,101,110,115,105,111,110,70,105,108,101,76,111,97,100,101,
-    114,46,95,95,101,113,95,95,99,1,0,0,0,0,0,0,
-    0,1,0,0,0,3,0,0,0,67,0,0,0,115,26,0,
-    0,0,116,0,0,124,0,0,106,1,0,131,1,0,116,0,
-    0,124,0,0,106,2,0,131,1,0,65,83,41,1,78,41,
-    3,114,214,0,0,0,114,106,0,0,0,114,35,0,0,0,
-    41,1,114,108,0,0,0,114,4,0,0,0,114,4,0,0,
-    0,114,5,0,0,0,114,215,0,0,0,132,3,0,0,115,
-    2,0,0,0,0,1,122,28,69,120,116,101,110,115,105,111,
-    110,70,105,108,101,76,111,97,100,101,114,46,95,95,104,97,
-    115,104,95,95,99,2,0,0,0,0,0,0,0,3,0,0,
-    0,4,0,0,0,67,0,0,0,115,47,0,0,0,116,0,
-    0,106,1,0,116,2,0,106,3,0,124,1,0,131,2,0,
-    125,2,0,116,4,0,100,1,0,124,1,0,106,5,0,124,
-    0,0,106,6,0,131,3,0,1,124,2,0,83,41,2,122,
-    38,67,114,101,97,116,101,32,97,110,32,117,110,105,116,105,
-    97,108,105,122,101,100,32,101,120,116,101,110,115,105,111,110,
-    32,109,111,100,117,108,101,122,38,101,120,116,101,110,115,105,
-    111,110,32,109,111,100,117,108,101,32,123,33,114,125,32,108,
-    111,97,100,101,100,32,102,114,111,109,32,123,33,114,125,41,
-    7,114,121,0,0,0,114,188,0,0,0,114,145,0,0,0,
-    90,14,99,114,101,97,116,101,95,100,121,110,97,109,105,99,
-    114,105,0,0,0,114,106,0,0,0,114,35,0,0,0,41,
-    3,114,108,0,0,0,114,164,0,0,0,114,190,0,0,0,
-    114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,114,
-    186,0,0,0,135,3,0,0,115,10,0,0,0,0,2,6,
-    1,15,1,6,1,16,1,122,33,69,120,116,101,110,115,105,
-    111,110,70,105,108,101,76,111,97,100,101,114,46,99,114,101,
-    97,116,101,95,109,111,100,117,108,101,99,2,0,0,0,0,
-    0,0,0,2,0,0,0,4,0,0,0,67,0,0,0,115,
-    45,0,0,0,116,0,0,106,1,0,116,2,0,106,3,0,
-    124,1,0,131,2,0,1,116,4,0,100,1,0,124,0,0,
-    106,5,0,124,0,0,106,6,0,131,3,0,1,100,2,0,
-    83,41,3,122,30,73,110,105,116,105,97,108,105,122,101,32,
-    97,110,32,101,120,116,101,110,115,105,111,110,32,109,111,100,
-    117,108,101,122,40,101,120,116,101,110,115,105,111,110,32,109,
-    111,100,117,108,101,32,123,33,114,125,32,101,120,101,99,117,
-    116,101,100,32,102,114,111,109,32,123,33,114,125,78,41,7,
-    114,121,0,0,0,114,188,0,0,0,114,145,0,0,0,90,
-    12,101,120,101,99,95,100,121,110,97,109,105,99,114,105,0,
-    0,0,114,106,0,0,0,114,35,0,0,0,41,2,114,108,
-    0,0,0,114,190,0,0,0,114,4,0,0,0,114,4,0,
-    0,0,114,5,0,0,0,114,191,0,0,0,143,3,0,0,
-    115,6,0,0,0,0,2,19,1,6,1,122,31,69,120,116,
-    101,110,115,105,111,110,70,105,108,101,76,111,97,100,101,114,
-    46,101,120,101,99,95,109,111,100,117,108,101,99,2,0,0,
-    0,0,0,0,0,2,0,0,0,4,0,0,0,3,0,0,
-    0,115,48,0,0,0,116,0,0,124,0,0,106,1,0,131,
-    1,0,100,1,0,25,137,0,0,116,2,0,135,0,0,102,
-    1,0,100,2,0,100,3,0,134,0,0,116,3,0,68,131,
-    1,0,131,1,0,83,41,4,122,49,82,101,116,117,114,110,
-    32,84,114,117,101,32,105,102,32,116,104,101,32,101,120,116,
-    101,110,115,105,111,110,32,109,111,100,117,108,101,32,105,115,
-    32,97,32,112,97,99,107,97,103,101,46,114,29,0,0,0,
-    99,1,0,0,0,0,0,0,0,2,0,0,0,4,0,0,
-    0,51,0,0,0,115,31,0,0,0,124,0,0,93,21,0,
-    125,1,0,136,0,0,100,0,0,124,1,0,23,107,2,0,
-    86,1,113,3,0,100,1,0,83,41,2,114,185,0,0,0,
-    78,114,4,0,0,0,41,2,114,22,0,0,0,218,6,115,
-    117,102,102,105,120,41,1,218,9,102,105,108,101,95,110,97,
-    109,101,114,4,0,0,0,114,5,0,0,0,250,9,60,103,
-    101,110,101,120,112,114,62,152,3,0,0,115,2,0,0,0,
-    6,1,122,49,69,120,116,101,110,115,105,111,110,70,105,108,
-    101,76,111,97,100,101,114,46,105,115,95,112,97,99,107,97,
-    103,101,46,60,108,111,99,97,108,115,62,46,60,103,101,110,
-    101,120,112,114,62,41,4,114,38,0,0,0,114,35,0,0,
-    0,218,3,97,110,121,218,18,69,88,84,69,78,83,73,79,
-    78,95,83,85,70,70,73,88,69,83,41,2,114,108,0,0,
-    0,114,126,0,0,0,114,4,0,0,0,41,1,114,226,0,
-    0,0,114,5,0,0,0,114,159,0,0,0,149,3,0,0,
-    115,6,0,0,0,0,2,19,1,18,1,122,30,69,120,116,
-    101,110,115,105,111,110,70,105,108,101,76,111,97,100,101,114,
-    46,105,115,95,112,97,99,107,97,103,101,99,2,0,0,0,
-    0,0,0,0,2,0,0,0,1,0,0,0,67,0,0,0,
-    115,4,0,0,0,100,1,0,83,41,2,122,63,82,101,116,
-    117,114,110,32,78,111,110,101,32,97,115,32,97,110,32,101,
-    120,116,101,110,115,105,111,110,32,109,111,100,117,108,101,32,
-    99,97,110,110,111,116,32,99,114,101,97,116,101,32,97,32,
-    99,111,100,101,32,111,98,106,101,99,116,46,78,114,4,0,
-    0,0,41,2,114,108,0,0,0,114,126,0,0,0,114,4,
-    0,0,0,114,4,0,0,0,114,5,0,0,0,114,187,0,
-    0,0,155,3,0,0,115,2,0,0,0,0,2,122,28,69,
-    120,116,101,110,115,105,111,110,70,105,108,101,76,111,97,100,
-    101,114,46,103,101,116,95,99,111,100,101,99,2,0,0,0,
-    0,0,0,0,2,0,0,0,1,0,0,0,67,0,0,0,
-    115,4,0,0,0,100,1,0,83,41,2,122,53,82,101,116,
-    117,114,110,32,78,111,110,101,32,97,115,32,101,120,116,101,
-    110,115,105,111,110,32,109,111,100,117,108,101,115,32,104,97,
-    118,101,32,110,111,32,115,111,117,114,99,101,32,99,111,100,
-    101,46,78,114,4,0,0,0,41,2,114,108,0,0,0,114,
-    126,0,0,0,114,4,0,0,0,114,4,0,0,0,114,5,
-    0,0,0,114,202,0,0,0,159,3,0,0,115,2,0,0,
-    0,0,2,122,30,69,120,116,101,110,115,105,111,110,70,105,
-    108,101,76,111,97,100,101,114,46,103,101,116,95,115,111,117,
-    114,99,101,99,2,0,0,0,0,0,0,0,2,0,0,0,
-    1,0,0,0,67,0,0,0,115,7,0,0,0,124,0,0,
-    106,0,0,83,41,1,122,58,82,101,116,117,114,110,32,116,
-    104,101,32,112,97,116,104,32,116,111,32,116,104,101,32,115,
-    111,117,114,99,101,32,102,105,108,101,32,97,115,32,102,111,
-    117,110,100,32,98,121,32,116,104,101,32,102,105,110,100,101,
-    114,46,41,1,114,35,0,0,0,41,2,114,108,0,0,0,
-    114,126,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,114,157,0,0,0,163,3,0,0,115,2,0,
-    0,0,0,3,122,32,69,120,116,101,110,115,105,111,110,70,
-    105,108,101,76,111,97,100,101,114,46,103,101,116,95,102,105,
-    108,101,110,97,109,101,78,41,14,114,112,0,0,0,114,111,
-    0,0,0,114,113,0,0,0,114,114,0,0,0,114,185,0,
-    0,0,114,213,0,0,0,114,215,0,0,0,114,186,0,0,
-    0,114,191,0,0,0,114,159,0,0,0,114,187,0,0,0,
-    114,202,0,0,0,114,123,0,0,0,114,157,0,0,0,114,
-    4,0,0,0,114,4,0,0,0,114,4,0,0,0,114,5,
-    0,0,0,114,224,0,0,0,116,3,0,0,115,20,0,0,
-    0,12,6,6,2,12,4,12,4,12,3,12,8,12,6,12,
-    6,12,4,12,4,114,224,0,0,0,99,0,0,0,0,0,
-    0,0,0,0,0,0,0,2,0,0,0,64,0,0,0,115,
-    130,0,0,0,101,0,0,90,1,0,100,0,0,90,2,0,
+    97,100,101,114,46,103,101,116,95,115,111,117,114,99,101,46,
+    122,39,115,111,117,114,99,101,32,110,111,116,32,97,118,97,
+    105,108,97,98,108,101,32,116,104,114,111,117,103,104,32,103,
+    101,116,95,100,97,116,97,40,41,114,108,0,0,0,78,41,
+    5,114,159,0,0,0,218,8,103,101,116,95,100,97,116,97,
+    114,42,0,0,0,114,109,0,0,0,114,157,0,0,0,41,
+    5,114,110,0,0,0,114,128,0,0,0,114,37,0,0,0,
+    114,155,0,0,0,218,3,101,120,99,114,4,0,0,0,114,
+    4,0,0,0,114,6,0,0,0,218,10,103,101,116,95,115,
+    111,117,114,99,101,207,2,0,0,115,14,0,0,0,0,2,
+    15,1,3,1,19,1,18,1,9,1,31,1,122,23,83,111,
+    117,114,99,101,76,111,97,100,101,114,46,103,101,116,95,115,
+    111,117,114,99,101,218,9,95,111,112,116,105,109,105,122,101,
+    114,31,0,0,0,99,3,0,0,0,1,0,0,0,4,0,
+    0,0,9,0,0,0,67,0,0,0,115,34,0,0,0,116,
+    0,0,106,1,0,116,2,0,124,1,0,124,2,0,100,1,
+    0,100,2,0,100,3,0,100,4,0,124,3,0,131,4,2,
+    83,41,5,122,130,82,101,116,117,114,110,32,116,104,101,32,
+    99,111,100,101,32,111,98,106,101,99,116,32,99,111,109,112,
+    105,108,101,100,32,102,114,111,109,32,115,111,117,114,99,101,
+    46,10,10,32,32,32,32,32,32,32,32,84,104,101,32,39,
+    100,97,116,97,39,32,97,114,103,117,109,101,110,116,32,99,
+    97,110,32,98,101,32,97,110,121,32,111,98,106,101,99,116,
+    32,116,121,112,101,32,116,104,97,116,32,99,111,109,112,105,
+    108,101,40,41,32,115,117,112,112,111,114,116,115,46,10,32,
+    32,32,32,32,32,32,32,114,190,0,0,0,218,12,100,111,
+    110,116,95,105,110,104,101,114,105,116,84,114,70,0,0,0,
+    41,3,114,123,0,0,0,114,189,0,0,0,218,7,99,111,
+    109,112,105,108,101,41,4,114,110,0,0,0,114,55,0,0,
+    0,114,37,0,0,0,114,204,0,0,0,114,4,0,0,0,
+    114,4,0,0,0,114,6,0,0,0,218,14,115,111,117,114,
+    99,101,95,116,111,95,99,111,100,101,217,2,0,0,115,4,
+    0,0,0,0,5,21,1,122,27,83,111,117,114,99,101,76,
+    111,97,100,101,114,46,115,111,117,114,99,101,95,116,111,95,
+    99,111,100,101,99,2,0,0,0,0,0,0,0,10,0,0,
+    0,43,0,0,0,67,0,0,0,115,174,1,0,0,124,0,
+    0,106,0,0,124,1,0,131,1,0,125,2,0,100,1,0,
+    125,3,0,121,16,0,116,1,0,124,2,0,131,1,0,125,
+    4,0,87,110,24,0,4,116,2,0,107,10,0,114,63,0,
+    1,1,1,100,1,0,125,4,0,89,110,202,0,88,121,19,
+    0,124,0,0,106,3,0,124,2,0,131,1,0,125,5,0,
+    87,110,18,0,4,116,4,0,107,10,0,114,103,0,1,1,
+    1,89,110,162,0,88,116,5,0,124,5,0,100,2,0,25,
+    131,1,0,125,3,0,121,19,0,124,0,0,106,6,0,124,
+    4,0,131,1,0,125,6,0,87,110,18,0,4,116,7,0,
+    107,10,0,114,159,0,1,1,1,89,110,106,0,88,121,34,
+    0,116,8,0,124,6,0,100,3,0,124,5,0,100,4,0,
+    124,1,0,100,5,0,124,4,0,131,1,3,125,7,0,87,
+    110,24,0,4,116,9,0,116,10,0,102,2,0,107,10,0,
+    114,220,0,1,1,1,89,110,45,0,88,116,11,0,100,6,
+    0,124,4,0,124,2,0,131,3,0,1,116,12,0,124,7,
+    0,100,4,0,124,1,0,100,7,0,124,4,0,100,8,0,
+    124,2,0,131,1,3,83,124,0,0,106,6,0,124,2,0,
+    131,1,0,125,8,0,124,0,0,106,13,0,124,8,0,124,
+    2,0,131,2,0,125,9,0,116,11,0,100,9,0,124,2,
+    0,131,2,0,1,116,14,0,106,15,0,12,114,170,1,124,
+    4,0,100,1,0,107,9,0,114,170,1,124,3,0,100,1,
+    0,107,9,0,114,170,1,116,16,0,124,9,0,124,3,0,
+    116,17,0,124,8,0,131,1,0,131,3,0,125,6,0,121,
+    36,0,124,0,0,106,18,0,124,2,0,124,4,0,124,6,
+    0,131,3,0,1,116,11,0,100,10,0,124,4,0,131,2,
+    0,1,87,110,18,0,4,116,2,0,107,10,0,114,169,1,
+    1,1,1,89,110,1,0,88,124,9,0,83,41,11,122,190,
+    67,111,110,99,114,101,116,101,32,105,109,112,108,101,109,101,
+    110,116,97,116,105,111,110,32,111,102,32,73,110,115,112,101,
+    99,116,76,111,97,100,101,114,46,103,101,116,95,99,111,100,
+    101,46,10,10,32,32,32,32,32,32,32,32,82,101,97,100,
+    105,110,103,32,111,102,32,98,121,116,101,99,111,100,101,32,
+    114,101,113,117,105,114,101,115,32,112,97,116,104,95,115,116,
+    97,116,115,32,116,111,32,98,101,32,105,109,112,108,101,109,
+    101,110,116,101,100,46,32,84,111,32,119,114,105,116,101,10,
+    32,32,32,32,32,32,32,32,98,121,116,101,99,111,100,101,
+    44,32,115,101,116,95,100,97,116,97,32,109,117,115,116,32,
+    97,108,115,111,32,98,101,32,105,109,112,108,101,109,101,110,
+    116,101,100,46,10,10,32,32,32,32,32,32,32,32,78,114,
+    135,0,0,0,114,140,0,0,0,114,108,0,0,0,114,37,
+    0,0,0,122,13,123,125,32,109,97,116,99,104,101,115,32,
+    123,125,114,91,0,0,0,114,92,0,0,0,122,19,99,111,
+    100,101,32,111,98,106,101,99,116,32,102,114,111,109,32,123,
+    125,122,10,119,114,111,116,101,32,123,33,114,125,41,19,114,
+    159,0,0,0,114,81,0,0,0,114,68,0,0,0,114,198,
+    0,0,0,114,196,0,0,0,114,16,0,0,0,114,201,0,
+    0,0,114,42,0,0,0,114,143,0,0,0,114,109,0,0,
+    0,114,138,0,0,0,114,107,0,0,0,114,149,0,0,0,
+    114,207,0,0,0,114,8,0,0,0,218,19,100,111,110,116,
+    95,119,114,105,116,101,95,98,121,116,101,99,111,100,101,114,
+    152,0,0,0,114,33,0,0,0,114,200,0,0,0,41,10,
+    114,110,0,0,0,114,128,0,0,0,114,92,0,0,0,114,
+    141,0,0,0,114,91,0,0,0,218,2,115,116,114,55,0,
+    0,0,218,10,98,121,116,101,115,95,100,97,116,97,114,155,
+    0,0,0,90,11,99,111,100,101,95,111,98,106,101,99,116,
+    114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,114,
+    188,0,0,0,225,2,0,0,115,78,0,0,0,0,7,15,
+    1,6,1,3,1,16,1,13,1,11,2,3,1,19,1,13,
+    1,5,2,16,1,3,1,19,1,13,1,5,2,3,1,9,
+    1,12,1,13,1,19,1,5,2,9,1,7,1,15,1,6,
+    1,7,1,15,1,18,1,13,1,22,1,12,1,9,1,15,
+    1,3,1,19,1,17,1,13,1,5,1,122,21,83,111,117,
+    114,99,101,76,111,97,100,101,114,46,103,101,116,95,99,111,
+    100,101,78,114,89,0,0,0,41,10,114,114,0,0,0,114,
+    113,0,0,0,114,115,0,0,0,114,197,0,0,0,114,198,
+    0,0,0,114,200,0,0,0,114,199,0,0,0,114,203,0,
+    0,0,114,207,0,0,0,114,188,0,0,0,114,4,0,0,
+    0,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    114,195,0,0,0,167,2,0,0,115,14,0,0,0,12,2,
+    12,8,12,13,12,10,12,7,12,10,18,8,114,195,0,0,
+    0,99,0,0,0,0,0,0,0,0,0,0,0,0,4,0,
+    0,0,0,0,0,0,115,112,0,0,0,101,0,0,90,1,
+    0,100,0,0,90,2,0,100,1,0,90,3,0,100,2,0,
+    100,3,0,132,0,0,90,4,0,100,4,0,100,5,0,132,
+    0,0,90,5,0,100,6,0,100,7,0,132,0,0,90,6,
+    0,101,7,0,135,0,0,102,1,0,100,8,0,100,9,0,
+    134,0,0,131,1,0,90,8,0,101,7,0,100,10,0,100,
+    11,0,132,0,0,131,1,0,90,9,0,100,12,0,100,13,
+    0,132,0,0,90,10,0,135,0,0,83,41,14,218,10,70,
+    105,108,101,76,111,97,100,101,114,122,103,66,97,115,101,32,
+    102,105,108,101,32,108,111,97,100,101,114,32,99,108,97,115,
+    115,32,119,104,105,99,104,32,105,109,112,108,101,109,101,110,
+    116,115,32,116,104,101,32,108,111,97,100,101,114,32,112,114,
+    111,116,111,99,111,108,32,109,101,116,104,111,100,115,32,116,
+    104,97,116,10,32,32,32,32,114,101,113,117,105,114,101,32,
+    102,105,108,101,32,115,121,115,116,101,109,32,117,115,97,103,
+    101,46,99,3,0,0,0,0,0,0,0,3,0,0,0,2,
+    0,0,0,67,0,0,0,115,22,0,0,0,124,1,0,124,
+    0,0,95,0,0,124,2,0,124,0,0,95,1,0,100,1,
+    0,83,41,2,122,75,67,97,99,104,101,32,116,104,101,32,
+    109,111,100,117,108,101,32,110,97,109,101,32,97,110,100,32,
+    116,104,101,32,112,97,116,104,32,116,111,32,116,104,101,32,
+    102,105,108,101,32,102,111,117,110,100,32,98,121,32,116,104,
+    101,10,32,32,32,32,32,32,32,32,102,105,110,100,101,114,
+    46,78,41,2,114,108,0,0,0,114,37,0,0,0,41,3,
+    114,110,0,0,0,114,128,0,0,0,114,37,0,0,0,114,
+    4,0,0,0,114,4,0,0,0,114,6,0,0,0,114,186,
+    0,0,0,26,3,0,0,115,4,0,0,0,0,3,9,1,
+    122,19,70,105,108,101,76,111,97,100,101,114,46,95,95,105,
+    110,105,116,95,95,99,2,0,0,0,0,0,0,0,2,0,
+    0,0,2,0,0,0,67,0,0,0,115,34,0,0,0,124,
+    0,0,106,0,0,124,1,0,106,0,0,107,2,0,111,33,
+    0,124,0,0,106,1,0,124,1,0,106,1,0,107,2,0,
+    83,41,1,78,41,2,218,9,95,95,99,108,97,115,115,95,
+    95,114,120,0,0,0,41,2,114,110,0,0,0,218,5,111,
+    116,104,101,114,114,4,0,0,0,114,4,0,0,0,114,6,
+    0,0,0,218,6,95,95,101,113,95,95,32,3,0,0,115,
+    4,0,0,0,0,1,18,1,122,17,70,105,108,101,76,111,
+    97,100,101,114,46,95,95,101,113,95,95,99,1,0,0,0,
+    0,0,0,0,1,0,0,0,3,0,0,0,67,0,0,0,
+    115,26,0,0,0,116,0,0,124,0,0,106,1,0,131,1,
+    0,116,0,0,124,0,0,106,2,0,131,1,0,65,83,41,
+    1,78,41,3,218,4,104,97,115,104,114,108,0,0,0,114,
+    37,0,0,0,41,1,114,110,0,0,0,114,4,0,0,0,
+    114,4,0,0,0,114,6,0,0,0,218,8,95,95,104,97,
+    115,104,95,95,36,3,0,0,115,2,0,0,0,0,1,122,
+    19,70,105,108,101,76,111,97,100,101,114,46,95,95,104,97,
+    115,104,95,95,99,2,0,0,0,0,0,0,0,2,0,0,
+    0,3,0,0,0,3,0,0,0,115,22,0,0,0,116,0,
+    0,116,1,0,124,0,0,131,2,0,106,2,0,124,1,0,
+    131,1,0,83,41,1,122,100,76,111,97,100,32,97,32,109,
+    111,100,117,108,101,32,102,114,111,109,32,97,32,102,105,108,
+    101,46,10,10,32,32,32,32,32,32,32,32,84,104,105,115,
+    32,109,101,116,104,111,100,32,105,115,32,100,101,112,114,101,
+    99,97,116,101,100,46,32,32,85,115,101,32,101,120,101,99,
+    95,109,111,100,117,108,101,40,41,32,105,110,115,116,101,97,
+    100,46,10,10,32,32,32,32,32,32,32,32,41,3,218,5,
+    115,117,112,101,114,114,211,0,0,0,114,194,0,0,0,41,
+    2,114,110,0,0,0,114,128,0,0,0,41,1,114,212,0,
+    0,0,114,4,0,0,0,114,6,0,0,0,114,194,0,0,
+    0,39,3,0,0,115,2,0,0,0,0,10,122,22,70,105,
+    108,101,76,111,97,100,101,114,46,108,111,97,100,95,109,111,
+    100,117,108,101,99,2,0,0,0,0,0,0,0,2,0,0,
+    0,1,0,0,0,67,0,0,0,115,7,0,0,0,124,0,
+    0,106,0,0,83,41,1,122,58,82,101,116,117,114,110,32,
+    116,104,101,32,112,97,116,104,32,116,111,32,116,104,101,32,
+    115,111,117,114,99,101,32,102,105,108,101,32,97,115,32,102,
+    111,117,110,100,32,98,121,32,116,104,101,32,102,105,110,100,
+    101,114,46,41,1,114,37,0,0,0,41,2,114,110,0,0,
+    0,114,128,0,0,0,114,4,0,0,0,114,4,0,0,0,
+    114,6,0,0,0,114,159,0,0,0,51,3,0,0,115,2,
+    0,0,0,0,3,122,23,70,105,108,101,76,111,97,100,101,
+    114,46,103,101,116,95,102,105,108,101,110,97,109,101,99,2,
+    0,0,0,0,0,0,0,3,0,0,0,9,0,0,0,67,
+    0,0,0,115,42,0,0,0,116,0,0,106,1,0,124,1,
+    0,100,1,0,131,2,0,143,17,0,125,2,0,124,2,0,
+    106,2,0,131,0,0,83,87,100,2,0,81,82,88,100,2,
+    0,83,41,3,122,39,82,101,116,117,114,110,32,116,104,101,
+    32,100,97,116,97,32,102,114,111,109,32,112,97,116,104,32,
+    97,115,32,114,97,119,32,98,121,116,101,115,46,218,1,114,
+    78,41,3,114,51,0,0,0,114,52,0,0,0,90,4,114,
+    101,97,100,41,3,114,110,0,0,0,114,37,0,0,0,114,
+    56,0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,
+    0,0,0,114,201,0,0,0,56,3,0,0,115,4,0,0,
+    0,0,2,21,1,122,19,70,105,108,101,76,111,97,100,101,
+    114,46,103,101,116,95,100,97,116,97,41,11,114,114,0,0,
+    0,114,113,0,0,0,114,115,0,0,0,114,116,0,0,0,
+    114,186,0,0,0,114,214,0,0,0,114,216,0,0,0,114,
+    125,0,0,0,114,194,0,0,0,114,159,0,0,0,114,201,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,41,1,114,
+    212,0,0,0,114,6,0,0,0,114,211,0,0,0,21,3,
+    0,0,115,14,0,0,0,12,3,6,2,12,6,12,4,12,
+    3,24,12,18,5,114,211,0,0,0,99,0,0,0,0,0,
+    0,0,0,0,0,0,0,4,0,0,0,64,0,0,0,115,
+    64,0,0,0,101,0,0,90,1,0,100,0,0,90,2,0,
     100,1,0,90,3,0,100,2,0,100,3,0,132,0,0,90,
     4,0,100,4,0,100,5,0,132,0,0,90,5,0,100,6,
-    0,100,7,0,132,0,0,90,6,0,100,8,0,100,9,0,
-    132,0,0,90,7,0,100,10,0,100,11,0,132,0,0,90,
-    8,0,100,12,0,100,13,0,132,0,0,90,9,0,100,14,
-    0,100,15,0,132,0,0,90,10,0,100,16,0,100,17,0,
-    132,0,0,90,11,0,100,18,0,100,19,0,132,0,0,90,
-    12,0,100,20,0,83,41,21,218,14,95,78,97,109,101,115,
-    112,97,99,101,80,97,116,104,97,38,1,0,0,82,101,112,
-    114,101,115,101,110,116,115,32,97,32,110,97,109,101,115,112,
-    97,99,101,32,112,97,99,107,97,103,101,39,115,32,112,97,
-    116,104,46,32,32,73,116,32,117,115,101,115,32,116,104,101,
-    32,109,111,100,117,108,101,32,110,97,109,101,10,32,32,32,
-    32,116,111,32,102,105,110,100,32,105,116,115,32,112,97,114,
-    101,110,116,32,109,111,100,117,108,101,44,32,97,110,100,32,
-    102,114,111,109,32,116,104,101,114,101,32,105,116,32,108,111,
-    111,107,115,32,117,112,32,116,104,101,32,112,97,114,101,110,
-    116,39,115,10,32,32,32,32,95,95,112,97,116,104,95,95,
-    46,32,32,87,104,101,110,32,116,104,105,115,32,99,104,97,
-    110,103,101,115,44,32,116,104,101,32,109,111,100,117,108,101,
-    39,115,32,111,119,110,32,112,97,116,104,32,105,115,32,114,
-    101,99,111,109,112,117,116,101,100,44,10,32,32,32,32,117,
-    115,105,110,103,32,112,97,116,104,95,102,105,110,100,101,114,
-    46,32,32,70,111,114,32,116,111,112,45,108,101,118,101,108,
-    32,109,111,100,117,108,101,115,44,32,116,104,101,32,112,97,
-    114,101,110,116,32,109,111,100,117,108,101,39,115,32,112,97,
-    116,104,10,32,32,32,32,105,115,32,115,121,115,46,112,97,
-    116,104,46,99,4,0,0,0,0,0,0,0,4,0,0,0,
-    2,0,0,0,67,0,0,0,115,52,0,0,0,124,1,0,
-    124,0,0,95,0,0,124,2,0,124,0,0,95,1,0,116,
-    2,0,124,0,0,106,3,0,131,0,0,131,1,0,124,0,
-    0,95,4,0,124,3,0,124,0,0,95,5,0,100,0,0,
-    83,41,1,78,41,6,218,5,95,110,97,109,101,218,5,95,
-    112,97,116,104,114,93,0,0,0,218,16,95,103,101,116,95,
-    112,97,114,101,110,116,95,112,97,116,104,218,17,95,108,97,
-    115,116,95,112,97,114,101,110,116,95,112,97,116,104,218,12,
-    95,112,97,116,104,95,102,105,110,100,101,114,41,4,114,108,
-    0,0,0,114,106,0,0,0,114,35,0,0,0,218,11,112,
-    97,116,104,95,102,105,110,100,101,114,114,4,0,0,0,114,
-    4,0,0,0,114,5,0,0,0,114,185,0,0,0,176,3,
-    0,0,115,8,0,0,0,0,1,9,1,9,1,21,1,122,
-    23,95,78,97,109,101,115,112,97,99,101,80,97,116,104,46,
-    95,95,105,110,105,116,95,95,99,1,0,0,0,0,0,0,
-    0,4,0,0,0,3,0,0,0,67,0,0,0,115,53,0,
-    0,0,124,0,0,106,0,0,106,1,0,100,1,0,131,1,
-    0,92,3,0,125,1,0,125,2,0,125,3,0,124,2,0,
-    100,2,0,107,2,0,114,43,0,100,6,0,83,124,1,0,
-    100,5,0,102,2,0,83,41,7,122,62,82,101,116,117,114,
-    110,115,32,97,32,116,117,112,108,101,32,111,102,32,40,112,
-    97,114,101,110,116,45,109,111,100,117,108,101,45,110,97,109,
-    101,44,32,112,97,114,101,110,116,45,112,97,116,104,45,97,
-    116,116,114,45,110,97,109,101,41,114,58,0,0,0,114,30,
-    0,0,0,114,7,0,0,0,114,35,0,0,0,90,8,95,
-    95,112,97,116,104,95,95,41,2,122,3,115,121,115,122,4,
-    112,97,116,104,41,2,114,231,0,0,0,114,32,0,0,0,
-    41,4,114,108,0,0,0,114,222,0,0,0,218,3,100,111,
-    116,90,2,109,101,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,218,23,95,102,105,110,100,95,112,97,114,101,
-    110,116,95,112,97,116,104,95,110,97,109,101,115,182,3,0,
-    0,115,8,0,0,0,0,2,27,1,12,2,4,3,122,38,
-    95,78,97,109,101,115,112,97,99,101,80,97,116,104,46,95,
-    102,105,110,100,95,112,97,114,101,110,116,95,112,97,116,104,
-    95,110,97,109,101,115,99,1,0,0,0,0,0,0,0,3,
-    0,0,0,3,0,0,0,67,0,0,0,115,38,0,0,0,
-    124,0,0,106,0,0,131,0,0,92,2,0,125,1,0,125,
-    2,0,116,1,0,116,2,0,106,3,0,124,1,0,25,124,
-    2,0,131,2,0,83,41,1,78,41,4,114,238,0,0,0,
-    114,117,0,0,0,114,7,0,0,0,218,7,109,111,100,117,
-    108,101,115,41,3,114,108,0,0,0,90,18,112,97,114,101,
-    110,116,95,109,111,100,117,108,101,95,110,97,109,101,90,14,
-    112,97,116,104,95,97,116,116,114,95,110,97,109,101,114,4,
-    0,0,0,114,4,0,0,0,114,5,0,0,0,114,233,0,
-    0,0,192,3,0,0,115,4,0,0,0,0,1,18,1,122,
-    31,95,78,97,109,101,115,112,97,99,101,80,97,116,104,46,
-    95,103,101,116,95,112,97,114,101,110,116,95,112,97,116,104,
-    99,1,0,0,0,0,0,0,0,3,0,0,0,3,0,0,
-    0,67,0,0,0,115,118,0,0,0,116,0,0,124,0,0,
-    106,1,0,131,0,0,131,1,0,125,1,0,124,1,0,124,
-    0,0,106,2,0,107,3,0,114,111,0,124,0,0,106,3,
-    0,124,0,0,106,4,0,124,1,0,131,2,0,125,2,0,
-    124,2,0,100,0,0,107,9,0,114,102,0,124,2,0,106,
-    5,0,100,0,0,107,8,0,114,102,0,124,2,0,106,6,
-    0,114,102,0,124,2,0,106,6,0,124,0,0,95,7,0,
-    124,1,0,124,0,0,95,2,0,124,0,0,106,7,0,83,
-    41,1,78,41,8,114,93,0,0,0,114,233,0,0,0,114,
-    234,0,0,0,114,235,0,0,0,114,231,0,0,0,114,127,
-    0,0,0,114,156,0,0,0,114,232,0,0,0,41,3,114,
-    108,0,0,0,90,11,112,97,114,101,110,116,95,112,97,116,
-    104,114,164,0,0,0,114,4,0,0,0,114,4,0,0,0,
-    114,5,0,0,0,218,12,95,114,101,99,97,108,99,117,108,
-    97,116,101,196,3,0,0,115,16,0,0,0,0,2,18,1,
-    15,1,21,3,27,1,9,1,12,1,9,1,122,27,95,78,
-    97,109,101,115,112,97,99,101,80,97,116,104,46,95,114,101,
-    99,97,108,99,117,108,97,116,101,99,1,0,0,0,0,0,
-    0,0,1,0,0,0,2,0,0,0,67,0,0,0,115,16,
-    0,0,0,116,0,0,124,0,0,106,1,0,131,0,0,131,
-    1,0,83,41,1,78,41,2,218,4,105,116,101,114,114,240,
-    0,0,0,41,1,114,108,0,0,0,114,4,0,0,0,114,
-    4,0,0,0,114,5,0,0,0,218,8,95,95,105,116,101,
-    114,95,95,209,3,0,0,115,2,0,0,0,0,1,122,23,
-    95,78,97,109,101,115,112,97,99,101,80,97,116,104,46,95,
-    95,105,116,101,114,95,95,99,1,0,0,0,0,0,0,0,
-    1,0,0,0,2,0,0,0,67,0,0,0,115,16,0,0,
-    0,116,0,0,124,0,0,106,1,0,131,0,0,131,1,0,
-    83,41,1,78,41,2,114,31,0,0,0,114,240,0,0,0,
-    41,1,114,108,0,0,0,114,4,0,0,0,114,4,0,0,
-    0,114,5,0,0,0,218,7,95,95,108,101,110,95,95,212,
-    3,0,0,115,2,0,0,0,0,1,122,22,95,78,97,109,
-    101,115,112,97,99,101,80,97,116,104,46,95,95,108,101,110,
-    95,95,99,1,0,0,0,0,0,0,0,1,0,0,0,2,
-    0,0,0,67,0,0,0,115,16,0,0,0,100,1,0,106,
-    0,0,124,0,0,106,1,0,131,1,0,83,41,2,78,122,
-    20,95,78,97,109,101,115,112,97,99,101,80,97,116,104,40,
-    123,33,114,125,41,41,2,114,47,0,0,0,114,232,0,0,
-    0,41,1,114,108,0,0,0,114,4,0,0,0,114,4,0,
-    0,0,114,5,0,0,0,218,8,95,95,114,101,112,114,95,
-    95,215,3,0,0,115,2,0,0,0,0,1,122,23,95,78,
-    97,109,101,115,112,97,99,101,80,97,116,104,46,95,95,114,
-    101,112,114,95,95,99,2,0,0,0,0,0,0,0,2,0,
-    0,0,2,0,0,0,67,0,0,0,115,16,0,0,0,124,
-    1,0,124,0,0,106,0,0,131,0,0,107,6,0,83,41,
-    1,78,41,1,114,240,0,0,0,41,2,114,108,0,0,0,
-    218,4,105,116,101,109,114,4,0,0,0,114,4,0,0,0,
-    114,5,0,0,0,218,12,95,95,99,111,110,116,97,105,110,
-    115,95,95,218,3,0,0,115,2,0,0,0,0,1,122,27,
-    95,78,97,109,101,115,112,97,99,101,80,97,116,104,46,95,
-    95,99,111,110,116,97,105,110,115,95,95,99,2,0,0,0,
-    0,0,0,0,2,0,0,0,2,0,0,0,67,0,0,0,
-    115,20,0,0,0,124,0,0,106,0,0,106,1,0,124,1,
-    0,131,1,0,1,100,0,0,83,41,1,78,41,2,114,232,
-    0,0,0,114,163,0,0,0,41,2,114,108,0,0,0,114,
-    245,0,0,0,114,4,0,0,0,114,4,0,0,0,114,5,
-    0,0,0,114,163,0,0,0,221,3,0,0,115,2,0,0,
-    0,0,1,122,21,95,78,97,109,101,115,112,97,99,101,80,
-    97,116,104,46,97,112,112,101,110,100,78,41,13,114,112,0,
-    0,0,114,111,0,0,0,114,113,0,0,0,114,114,0,0,
-    0,114,185,0,0,0,114,238,0,0,0,114,233,0,0,0,
-    114,240,0,0,0,114,242,0,0,0,114,243,0,0,0,114,
-    244,0,0,0,114,246,0,0,0,114,163,0,0,0,114,4,
-    0,0,0,114,4,0,0,0,114,4,0,0,0,114,5,0,
-    0,0,114,230,0,0,0,169,3,0,0,115,20,0,0,0,
-    12,5,6,2,12,6,12,10,12,4,12,13,12,3,12,3,
-    12,3,12,3,114,230,0,0,0,99,0,0,0,0,0,0,
-    0,0,0,0,0,0,3,0,0,0,64,0,0,0,115,118,
-    0,0,0,101,0,0,90,1,0,100,0,0,90,2,0,100,
-    1,0,100,2,0,132,0,0,90,3,0,101,4,0,100,3,
-    0,100,4,0,132,0,0,131,1,0,90,5,0,100,5,0,
-    100,6,0,132,0,0,90,6,0,100,7,0,100,8,0,132,
-    0,0,90,7,0,100,9,0,100,10,0,132,0,0,90,8,
-    0,100,11,0,100,12,0,132,0,0,90,9,0,100,13,0,
-    100,14,0,132,0,0,90,10,0,100,15,0,100,16,0,132,
-    0,0,90,11,0,100,17,0,83,41,18,218,16,95,78,97,
-    109,101,115,112,97,99,101,76,111,97,100,101,114,99,4,0,
-    0,0,0,0,0,0,4,0,0,0,4,0,0,0,67,0,
-    0,0,115,25,0,0,0,116,0,0,124,1,0,124,2,0,
-    124,3,0,131,3,0,124,0,0,95,1,0,100,0,0,83,
-    41,1,78,41,2,114,230,0,0,0,114,232,0,0,0,41,
-    4,114,108,0,0,0,114,106,0,0,0,114,35,0,0,0,
-    114,236,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
-    5,0,0,0,114,185,0,0,0,227,3,0,0,115,2,0,
-    0,0,0,1,122,25,95,78,97,109,101,115,112,97,99,101,
-    76,111,97,100,101,114,46,95,95,105,110,105,116,95,95,99,
-    2,0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,
-    67,0,0,0,115,16,0,0,0,100,1,0,106,0,0,124,
-    1,0,106,1,0,131,1,0,83,41,2,122,115,82,101,116,
-    117,114,110,32,114,101,112,114,32,102,111,114,32,116,104,101,
-    32,109,111,100,117,108,101,46,10,10,32,32,32,32,32,32,
-    32,32,84,104,101,32,109,101,116,104,111,100,32,105,115,32,
-    100,101,112,114,101,99,97,116,101,100,46,32,32,84,104,101,
-    32,105,109,112,111,114,116,32,109,97,99,104,105,110,101,114,
-    121,32,100,111,101,115,32,116,104,101,32,106,111,98,32,105,
-    116,115,101,108,102,46,10,10,32,32,32,32,32,32,32,32,
-    122,25,60,109,111,100,117,108,101,32,123,33,114,125,32,40,
-    110,97,109,101,115,112,97,99,101,41,62,41,2,114,47,0,
-    0,0,114,112,0,0,0,41,2,114,170,0,0,0,114,190,
-    0,0,0,114,4,0,0,0,114,4,0,0,0,114,5,0,
-    0,0,218,11,109,111,100,117,108,101,95,114,101,112,114,230,
-    3,0,0,115,2,0,0,0,0,7,122,28,95,78,97,109,
-    101,115,112,97,99,101,76,111,97,100,101,114,46,109,111,100,
-    117,108,101,95,114,101,112,114,99,2,0,0,0,0,0,0,
+    0,100,7,0,100,8,0,100,9,0,132,0,1,90,6,0,
+    100,10,0,83,41,11,218,16,83,111,117,114,99,101,70,105,
+    108,101,76,111,97,100,101,114,122,62,67,111,110,99,114,101,
+    116,101,32,105,109,112,108,101,109,101,110,116,97,116,105,111,
+    110,32,111,102,32,83,111,117,114,99,101,76,111,97,100,101,
+    114,32,117,115,105,110,103,32,116,104,101,32,102,105,108,101,
+    32,115,121,115,116,101,109,46,99,2,0,0,0,0,0,0,
+    0,3,0,0,0,4,0,0,0,67,0,0,0,115,34,0,
+    0,0,116,0,0,124,1,0,131,1,0,125,2,0,100,1,
+    0,124,2,0,106,1,0,100,2,0,124,2,0,106,2,0,
+    105,2,0,83,41,3,122,33,82,101,116,117,114,110,32,116,
+    104,101,32,109,101,116,97,100,97,116,97,32,102,111,114,32,
+    116,104,101,32,112,97,116,104,46,114,135,0,0,0,114,136,
+    0,0,0,41,3,114,41,0,0,0,218,8,115,116,95,109,
+    116,105,109,101,90,7,115,116,95,115,105,122,101,41,3,114,
+    110,0,0,0,114,37,0,0,0,114,209,0,0,0,114,4,
+    0,0,0,114,4,0,0,0,114,6,0,0,0,114,198,0,
+    0,0,66,3,0,0,115,4,0,0,0,0,2,12,1,122,
+    27,83,111,117,114,99,101,70,105,108,101,76,111,97,100,101,
+    114,46,112,97,116,104,95,115,116,97,116,115,99,4,0,0,
+    0,0,0,0,0,5,0,0,0,5,0,0,0,67,0,0,
+    0,115,34,0,0,0,116,0,0,124,1,0,131,1,0,125,
+    4,0,124,0,0,106,1,0,124,2,0,124,3,0,100,1,
+    0,124,4,0,131,2,1,83,41,2,78,218,5,95,109,111,
+    100,101,41,2,114,99,0,0,0,114,199,0,0,0,41,5,
+    114,110,0,0,0,114,92,0,0,0,114,91,0,0,0,114,
+    55,0,0,0,114,44,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,114,200,0,0,0,71,3,0,
+    0,115,4,0,0,0,0,2,12,1,122,32,83,111,117,114,
+    99,101,70,105,108,101,76,111,97,100,101,114,46,95,99,97,
+    99,104,101,95,98,121,116,101,99,111,100,101,114,221,0,0,
+    0,105,182,1,0,0,99,3,0,0,0,1,0,0,0,9,
+    0,0,0,17,0,0,0,67,0,0,0,115,53,1,0,0,
+    116,0,0,124,1,0,131,1,0,92,2,0,125,4,0,125,
+    5,0,103,0,0,125,6,0,120,54,0,124,4,0,114,80,
+    0,116,1,0,124,4,0,131,1,0,12,114,80,0,116,0,
+    0,124,4,0,131,1,0,92,2,0,125,4,0,125,7,0,
+    124,6,0,106,2,0,124,7,0,131,1,0,1,113,27,0,
+    87,120,132,0,116,3,0,124,6,0,131,1,0,68,93,118,
+    0,125,7,0,116,4,0,124,4,0,124,7,0,131,2,0,
+    125,4,0,121,17,0,116,5,0,106,6,0,124,4,0,131,
+    1,0,1,87,113,94,0,4,116,7,0,107,10,0,114,155,
+    0,1,1,1,119,94,0,89,113,94,0,4,116,8,0,107,
+    10,0,114,211,0,1,125,8,0,1,122,25,0,116,9,0,
+    100,1,0,124,4,0,124,8,0,131,3,0,1,100,2,0,
+    83,87,89,100,2,0,100,2,0,125,8,0,126,8,0,88,
+    113,94,0,88,113,94,0,87,121,33,0,116,10,0,124,1,
+    0,124,2,0,124,3,0,131,3,0,1,116,9,0,100,3,
+    0,124,1,0,131,2,0,1,87,110,53,0,4,116,8,0,
+    107,10,0,114,48,1,1,125,8,0,1,122,21,0,116,9,
+    0,100,1,0,124,1,0,124,8,0,131,3,0,1,87,89,
+    100,2,0,100,2,0,125,8,0,126,8,0,88,110,1,0,
+    88,100,2,0,83,41,4,122,27,87,114,105,116,101,32,98,
+    121,116,101,115,32,100,97,116,97,32,116,111,32,97,32,102,
+    105,108,101,46,122,27,99,111,117,108,100,32,110,111,116,32,
+    99,114,101,97,116,101,32,123,33,114,125,58,32,123,33,114,
+    125,78,122,12,99,114,101,97,116,101,100,32,123,33,114,125,
+    41,11,114,40,0,0,0,114,48,0,0,0,114,165,0,0,
+    0,114,35,0,0,0,114,30,0,0,0,114,3,0,0,0,
+    90,5,109,107,100,105,114,218,15,70,105,108,101,69,120,105,
+    115,116,115,69,114,114,111,114,114,42,0,0,0,114,107,0,
+    0,0,114,57,0,0,0,41,9,114,110,0,0,0,114,37,
+    0,0,0,114,55,0,0,0,114,221,0,0,0,218,6,112,
+    97,114,101,110,116,114,96,0,0,0,114,29,0,0,0,114,
+    25,0,0,0,114,202,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,114,199,0,0,0,76,3,0,
+    0,115,38,0,0,0,0,2,18,1,6,2,22,1,18,1,
+    17,2,19,1,15,1,3,1,17,1,13,2,7,1,18,3,
+    16,1,27,1,3,1,16,1,17,1,18,2,122,25,83,111,
+    117,114,99,101,70,105,108,101,76,111,97,100,101,114,46,115,
+    101,116,95,100,97,116,97,78,41,7,114,114,0,0,0,114,
+    113,0,0,0,114,115,0,0,0,114,116,0,0,0,114,198,
+    0,0,0,114,200,0,0,0,114,199,0,0,0,114,4,0,
+    0,0,114,4,0,0,0,114,4,0,0,0,114,6,0,0,
+    0,114,219,0,0,0,62,3,0,0,115,8,0,0,0,12,
+    2,6,2,12,5,12,5,114,219,0,0,0,99,0,0,0,
+    0,0,0,0,0,0,0,0,0,2,0,0,0,64,0,0,
+    0,115,46,0,0,0,101,0,0,90,1,0,100,0,0,90,
+    2,0,100,1,0,90,3,0,100,2,0,100,3,0,132,0,
+    0,90,4,0,100,4,0,100,5,0,132,0,0,90,5,0,
+    100,6,0,83,41,7,218,20,83,111,117,114,99,101,108,101,
+    115,115,70,105,108,101,76,111,97,100,101,114,122,45,76,111,
+    97,100,101,114,32,119,104,105,99,104,32,104,97,110,100,108,
+    101,115,32,115,111,117,114,99,101,108,101,115,115,32,102,105,
+    108,101,32,105,109,112,111,114,116,115,46,99,2,0,0,0,
+    0,0,0,0,5,0,0,0,6,0,0,0,67,0,0,0,
+    115,76,0,0,0,124,0,0,106,0,0,124,1,0,131,1,
+    0,125,2,0,124,0,0,106,1,0,124,2,0,131,1,0,
+    125,3,0,116,2,0,124,3,0,100,1,0,124,1,0,100,
+    2,0,124,2,0,131,1,2,125,4,0,116,3,0,124,4,
+    0,100,1,0,124,1,0,100,3,0,124,2,0,131,1,2,
+    83,41,4,78,114,108,0,0,0,114,37,0,0,0,114,91,
+    0,0,0,41,4,114,159,0,0,0,114,201,0,0,0,114,
+    143,0,0,0,114,149,0,0,0,41,5,114,110,0,0,0,
+    114,128,0,0,0,114,37,0,0,0,114,55,0,0,0,114,
+    210,0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,
+    0,0,0,114,188,0,0,0,109,3,0,0,115,8,0,0,
+    0,0,1,15,1,15,1,24,1,122,29,83,111,117,114,99,
+    101,108,101,115,115,70,105,108,101,76,111,97,100,101,114,46,
+    103,101,116,95,99,111,100,101,99,2,0,0,0,0,0,0,
     0,2,0,0,0,1,0,0,0,67,0,0,0,115,4,0,
-    0,0,100,1,0,83,41,2,78,84,114,4,0,0,0,41,
-    2,114,108,0,0,0,114,126,0,0,0,114,4,0,0,0,
-    114,4,0,0,0,114,5,0,0,0,114,159,0,0,0,239,
-    3,0,0,115,2,0,0,0,0,1,122,27,95,78,97,109,
-    101,115,112,97,99,101,76,111,97,100,101,114,46,105,115,95,
-    112,97,99,107,97,103,101,99,2,0,0,0,0,0,0,0,
-    2,0,0,0,1,0,0,0,67,0,0,0,115,4,0,0,
-    0,100,1,0,83,41,2,78,114,30,0,0,0,114,4,0,
-    0,0,41,2,114,108,0,0,0,114,126,0,0,0,114,4,
-    0,0,0,114,4,0,0,0,114,5,0,0,0,114,202,0,
-    0,0,242,3,0,0,115,2,0,0,0,0,1,122,27,95,
-    78,97,109,101,115,112,97,99,101,76,111,97,100,101,114,46,
-    103,101,116,95,115,111,117,114,99,101,99,2,0,0,0,0,
-    0,0,0,2,0,0,0,6,0,0,0,67,0,0,0,115,
-    22,0,0,0,116,0,0,100,1,0,100,2,0,100,3,0,
-    100,4,0,100,5,0,131,3,1,83,41,6,78,114,30,0,
-    0,0,122,8,60,115,116,114,105,110,103,62,114,189,0,0,
-    0,114,204,0,0,0,84,41,1,114,205,0,0,0,41,2,
-    114,108,0,0,0,114,126,0,0,0,114,4,0,0,0,114,
-    4,0,0,0,114,5,0,0,0,114,187,0,0,0,245,3,
-    0,0,115,2,0,0,0,0,1,122,25,95,78,97,109,101,
-    115,112,97,99,101,76,111,97,100,101,114,46,103,101,116,95,
-    99,111,100,101,99,2,0,0,0,0,0,0,0,2,0,0,
-    0,1,0,0,0,67,0,0,0,115,4,0,0,0,100,1,
-    0,83,41,2,122,42,85,115,101,32,100,101,102,97,117,108,
-    116,32,115,101,109,97,110,116,105,99,115,32,102,111,114,32,
-    109,111,100,117,108,101,32,99,114,101,97,116,105,111,110,46,
-    78,114,4,0,0,0,41,2,114,108,0,0,0,114,164,0,
-    0,0,114,4,0,0,0,114,4,0,0,0,114,5,0,0,
-    0,114,186,0,0,0,248,3,0,0,115,0,0,0,0,122,
-    30,95,78,97,109,101,115,112,97,99,101,76,111,97,100,101,
-    114,46,99,114,101,97,116,101,95,109,111,100,117,108,101,99,
+    0,0,100,1,0,83,41,2,122,39,82,101,116,117,114,110,
+    32,78,111,110,101,32,97,115,32,116,104,101,114,101,32,105,
+    115,32,110,111,32,115,111,117,114,99,101,32,99,111,100,101,
+    46,78,114,4,0,0,0,41,2,114,110,0,0,0,114,128,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,114,203,0,0,0,115,3,0,0,115,2,0,0,0,
+    0,2,122,31,83,111,117,114,99,101,108,101,115,115,70,105,
+    108,101,76,111,97,100,101,114,46,103,101,116,95,115,111,117,
+    114,99,101,78,41,6,114,114,0,0,0,114,113,0,0,0,
+    114,115,0,0,0,114,116,0,0,0,114,188,0,0,0,114,
+    203,0,0,0,114,4,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,114,224,0,0,0,105,3,0,
+    0,115,6,0,0,0,12,2,6,2,12,6,114,224,0,0,
+    0,99,0,0,0,0,0,0,0,0,0,0,0,0,3,0,
+    0,0,64,0,0,0,115,136,0,0,0,101,0,0,90,1,
+    0,100,0,0,90,2,0,100,1,0,90,3,0,100,2,0,
+    100,3,0,132,0,0,90,4,0,100,4,0,100,5,0,132,
+    0,0,90,5,0,100,6,0,100,7,0,132,0,0,90,6,
+    0,100,8,0,100,9,0,132,0,0,90,7,0,100,10,0,
+    100,11,0,132,0,0,90,8,0,100,12,0,100,13,0,132,
+    0,0,90,9,0,100,14,0,100,15,0,132,0,0,90,10,
+    0,100,16,0,100,17,0,132,0,0,90,11,0,101,12,0,
+    100,18,0,100,19,0,132,0,0,131,1,0,90,13,0,100,
+    20,0,83,41,21,218,19,69,120,116,101,110,115,105,111,110,
+    70,105,108,101,76,111,97,100,101,114,122,93,76,111,97,100,
+    101,114,32,102,111,114,32,101,120,116,101,110,115,105,111,110,
+    32,109,111,100,117,108,101,115,46,10,10,32,32,32,32,84,
+    104,101,32,99,111,110,115,116,114,117,99,116,111,114,32,105,
+    115,32,100,101,115,105,103,110,101,100,32,116,111,32,119,111,
+    114,107,32,119,105,116,104,32,70,105,108,101,70,105,110,100,
+    101,114,46,10,10,32,32,32,32,99,3,0,0,0,0,0,
+    0,0,3,0,0,0,2,0,0,0,67,0,0,0,115,22,
+    0,0,0,124,1,0,124,0,0,95,0,0,124,2,0,124,
+    0,0,95,1,0,100,0,0,83,41,1,78,41,2,114,108,
+    0,0,0,114,37,0,0,0,41,3,114,110,0,0,0,114,
+    108,0,0,0,114,37,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,114,186,0,0,0,132,3,0,
+    0,115,4,0,0,0,0,1,9,1,122,28,69,120,116,101,
+    110,115,105,111,110,70,105,108,101,76,111,97,100,101,114,46,
+    95,95,105,110,105,116,95,95,99,2,0,0,0,0,0,0,
+    0,2,0,0,0,2,0,0,0,67,0,0,0,115,34,0,
+    0,0,124,0,0,106,0,0,124,1,0,106,0,0,107,2,
+    0,111,33,0,124,0,0,106,1,0,124,1,0,106,1,0,
+    107,2,0,83,41,1,78,41,2,114,212,0,0,0,114,120,
+    0,0,0,41,2,114,110,0,0,0,114,213,0,0,0,114,
+    4,0,0,0,114,4,0,0,0,114,6,0,0,0,114,214,
+    0,0,0,136,3,0,0,115,4,0,0,0,0,1,18,1,
+    122,26,69,120,116,101,110,115,105,111,110,70,105,108,101,76,
+    111,97,100,101,114,46,95,95,101,113,95,95,99,1,0,0,
+    0,0,0,0,0,1,0,0,0,3,0,0,0,67,0,0,
+    0,115,26,0,0,0,116,0,0,124,0,0,106,1,0,131,
+    1,0,116,0,0,124,0,0,106,2,0,131,1,0,65,83,
+    41,1,78,41,3,114,215,0,0,0,114,108,0,0,0,114,
+    37,0,0,0,41,1,114,110,0,0,0,114,4,0,0,0,
+    114,4,0,0,0,114,6,0,0,0,114,216,0,0,0,140,
+    3,0,0,115,2,0,0,0,0,1,122,28,69,120,116,101,
+    110,115,105,111,110,70,105,108,101,76,111,97,100,101,114,46,
+    95,95,104,97,115,104,95,95,99,2,0,0,0,0,0,0,
+    0,3,0,0,0,4,0,0,0,67,0,0,0,115,47,0,
+    0,0,116,0,0,106,1,0,116,2,0,106,3,0,124,1,
+    0,131,2,0,125,2,0,116,4,0,100,1,0,124,1,0,
+    106,5,0,124,0,0,106,6,0,131,3,0,1,124,2,0,
+    83,41,2,122,38,67,114,101,97,116,101,32,97,110,32,117,
+    110,105,116,105,97,108,105,122,101,100,32,101,120,116,101,110,
+    115,105,111,110,32,109,111,100,117,108,101,122,38,101,120,116,
+    101,110,115,105,111,110,32,109,111,100,117,108,101,32,123,33,
+    114,125,32,108,111,97,100,101,100,32,102,114,111,109,32,123,
+    33,114,125,41,7,114,123,0,0,0,114,189,0,0,0,114,
+    147,0,0,0,90,14,99,114,101,97,116,101,95,100,121,110,
+    97,109,105,99,114,107,0,0,0,114,108,0,0,0,114,37,
+    0,0,0,41,3,114,110,0,0,0,114,166,0,0,0,114,
+    191,0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,
+    0,0,0,114,187,0,0,0,143,3,0,0,115,10,0,0,
+    0,0,2,6,1,15,1,6,1,16,1,122,33,69,120,116,
+    101,110,115,105,111,110,70,105,108,101,76,111,97,100,101,114,
+    46,99,114,101,97,116,101,95,109,111,100,117,108,101,99,2,
+    0,0,0,0,0,0,0,2,0,0,0,4,0,0,0,67,
+    0,0,0,115,45,0,0,0,116,0,0,106,1,0,116,2,
+    0,106,3,0,124,1,0,131,2,0,1,116,4,0,100,1,
+    0,124,0,0,106,5,0,124,0,0,106,6,0,131,3,0,
+    1,100,2,0,83,41,3,122,30,73,110,105,116,105,97,108,
+    105,122,101,32,97,110,32,101,120,116,101,110,115,105,111,110,
+    32,109,111,100,117,108,101,122,40,101,120,116,101,110,115,105,
+    111,110,32,109,111,100,117,108,101,32,123,33,114,125,32,101,
+    120,101,99,117,116,101,100,32,102,114,111,109,32,123,33,114,
+    125,78,41,7,114,123,0,0,0,114,189,0,0,0,114,147,
+    0,0,0,90,12,101,120,101,99,95,100,121,110,97,109,105,
+    99,114,107,0,0,0,114,108,0,0,0,114,37,0,0,0,
+    41,2,114,110,0,0,0,114,191,0,0,0,114,4,0,0,
+    0,114,4,0,0,0,114,6,0,0,0,114,192,0,0,0,
+    151,3,0,0,115,6,0,0,0,0,2,19,1,6,1,122,
+    31,69,120,116,101,110,115,105,111,110,70,105,108,101,76,111,
+    97,100,101,114,46,101,120,101,99,95,109,111,100,117,108,101,
+    99,2,0,0,0,0,0,0,0,2,0,0,0,4,0,0,
+    0,3,0,0,0,115,48,0,0,0,116,0,0,124,0,0,
+    106,1,0,131,1,0,100,1,0,25,137,0,0,116,2,0,
+    135,0,0,102,1,0,100,2,0,100,3,0,134,0,0,116,
+    3,0,68,131,1,0,131,1,0,83,41,4,122,49,82,101,
+    116,117,114,110,32,84,114,117,101,32,105,102,32,116,104,101,
+    32,101,120,116,101,110,115,105,111,110,32,109,111,100,117,108,
+    101,32,105,115,32,97,32,112,97,99,107,97,103,101,46,114,
+    31,0,0,0,99,1,0,0,0,0,0,0,0,2,0,0,
+    0,4,0,0,0,51,0,0,0,115,31,0,0,0,124,0,
+    0,93,21,0,125,1,0,136,0,0,100,0,0,124,1,0,
+    23,107,2,0,86,1,113,3,0,100,1,0,83,41,2,114,
+    186,0,0,0,78,114,4,0,0,0,41,2,114,24,0,0,
+    0,218,6,115,117,102,102,105,120,41,1,218,9,102,105,108,
+    101,95,110,97,109,101,114,4,0,0,0,114,6,0,0,0,
+    250,9,60,103,101,110,101,120,112,114,62,160,3,0,0,115,
+    2,0,0,0,6,1,122,49,69,120,116,101,110,115,105,111,
+    110,70,105,108,101,76,111,97,100,101,114,46,105,115,95,112,
+    97,99,107,97,103,101,46,60,108,111,99,97,108,115,62,46,
+    60,103,101,110,101,120,112,114,62,41,4,114,40,0,0,0,
+    114,37,0,0,0,218,3,97,110,121,218,18,69,88,84,69,
+    78,83,73,79,78,95,83,85,70,70,73,88,69,83,41,2,
+    114,110,0,0,0,114,128,0,0,0,114,4,0,0,0,41,
+    1,114,227,0,0,0,114,6,0,0,0,114,161,0,0,0,
+    157,3,0,0,115,6,0,0,0,0,2,19,1,18,1,122,
+    30,69,120,116,101,110,115,105,111,110,70,105,108,101,76,111,
+    97,100,101,114,46,105,115,95,112,97,99,107,97,103,101,99,
+    2,0,0,0,0,0,0,0,2,0,0,0,1,0,0,0,
+    67,0,0,0,115,4,0,0,0,100,1,0,83,41,2,122,
+    63,82,101,116,117,114,110,32,78,111,110,101,32,97,115,32,
+    97,110,32,101,120,116,101,110,115,105,111,110,32,109,111,100,
+    117,108,101,32,99,97,110,110,111,116,32,99,114,101,97,116,
+    101,32,97,32,99,111,100,101,32,111,98,106,101,99,116,46,
+    78,114,4,0,0,0,41,2,114,110,0,0,0,114,128,0,
+    0,0,114,4,0,0,0,114,4,0,0,0,114,6,0,0,
+    0,114,188,0,0,0,163,3,0,0,115,2,0,0,0,0,
+    2,122,28,69,120,116,101,110,115,105,111,110,70,105,108,101,
+    76,111,97,100,101,114,46,103,101,116,95,99,111,100,101,99,
     2,0,0,0,0,0,0,0,2,0,0,0,1,0,0,0,
-    67,0,0,0,115,4,0,0,0,100,0,0,83,41,1,78,
-    114,4,0,0,0,41,2,114,108,0,0,0,114,190,0,0,
-    0,114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,
-    114,191,0,0,0,251,3,0,0,115,2,0,0,0,0,1,
-    122,28,95,78,97,109,101,115,112,97,99,101,76,111,97,100,
-    101,114,46,101,120,101,99,95,109,111,100,117,108,101,99,2,
-    0,0,0,0,0,0,0,2,0,0,0,3,0,0,0,67,
-    0,0,0,115,32,0,0,0,116,0,0,100,1,0,124,0,
-    0,106,1,0,131,2,0,1,116,2,0,106,3,0,124,0,
-    0,124,1,0,131,2,0,83,41,2,122,98,76,111,97,100,
-    32,97,32,110,97,109,101,115,112,97,99,101,32,109,111,100,
-    117,108,101,46,10,10,32,32,32,32,32,32,32,32,84,104,
-    105,115,32,109,101,116,104,111,100,32,105,115,32,100,101,112,
-    114,101,99,97,116,101,100,46,32,32,85,115,101,32,101,120,
-    101,99,95,109,111,100,117,108,101,40,41,32,105,110,115,116,
-    101,97,100,46,10,10,32,32,32,32,32,32,32,32,122,38,
-    110,97,109,101,115,112,97,99,101,32,109,111,100,117,108,101,
-    32,108,111,97,100,101,100,32,119,105,116,104,32,112,97,116,
-    104,32,123,33,114,125,41,4,114,105,0,0,0,114,232,0,
-    0,0,114,121,0,0,0,114,192,0,0,0,41,2,114,108,
-    0,0,0,114,126,0,0,0,114,4,0,0,0,114,4,0,
-    0,0,114,5,0,0,0,114,193,0,0,0,254,3,0,0,
-    115,4,0,0,0,0,7,16,1,122,28,95,78,97,109,101,
-    115,112,97,99,101,76,111,97,100,101,114,46,108,111,97,100,
-    95,109,111,100,117,108,101,78,41,12,114,112,0,0,0,114,
-    111,0,0,0,114,113,0,0,0,114,185,0,0,0,114,183,
-    0,0,0,114,248,0,0,0,114,159,0,0,0,114,202,0,
-    0,0,114,187,0,0,0,114,186,0,0,0,114,191,0,0,
-    0,114,193,0,0,0,114,4,0,0,0,114,4,0,0,0,
-    114,4,0,0,0,114,5,0,0,0,114,247,0,0,0,226,
-    3,0,0,115,16,0,0,0,12,1,12,3,18,9,12,3,
-    12,3,12,3,12,3,12,3,114,247,0,0,0,99,0,0,
-    0,0,0,0,0,0,0,0,0,0,5,0,0,0,64,0,
-    0,0,115,160,0,0,0,101,0,0,90,1,0,100,0,0,
-    90,2,0,100,1,0,90,3,0,101,4,0,100,2,0,100,
-    3,0,132,0,0,131,1,0,90,5,0,101,4,0,100,4,
-    0,100,5,0,132,0,0,131,1,0,90,6,0,101,4,0,
-    100,6,0,100,7,0,132,0,0,131,1,0,90,7,0,101,
-    4,0,100,8,0,100,9,0,132,0,0,131,1,0,90,8,
-    0,101,4,0,100,10,0,100,11,0,100,12,0,132,1,0,
-    131,1,0,90,9,0,101,4,0,100,10,0,100,10,0,100,
-    13,0,100,14,0,132,2,0,131,1,0,90,10,0,101,4,
-    0,100,10,0,100,15,0,100,16,0,132,1,0,131,1,0,
-    90,11,0,100,10,0,83,41,17,218,10,80,97,116,104,70,
-    105,110,100,101,114,122,62,77,101,116,97,32,112,97,116,104,
-    32,102,105,110,100,101,114,32,102,111,114,32,115,121,115,46,
-    112,97,116,104,32,97,110,100,32,112,97,99,107,97,103,101,
-    32,95,95,112,97,116,104,95,95,32,97,116,116,114,105,98,
-    117,116,101,115,46,99,1,0,0,0,0,0,0,0,2,0,
-    0,0,4,0,0,0,67,0,0,0,115,55,0,0,0,120,
-    48,0,116,0,0,106,1,0,106,2,0,131,0,0,68,93,
-    31,0,125,1,0,116,3,0,124,1,0,100,1,0,131,2,
-    0,114,16,0,124,1,0,106,4,0,131,0,0,1,113,16,
-    0,87,100,2,0,83,41,3,122,125,67,97,108,108,32,116,
-    104,101,32,105,110,118,97,108,105,100,97,116,101,95,99,97,
-    99,104,101,115,40,41,32,109,101,116,104,111,100,32,111,110,
-    32,97,108,108,32,112,97,116,104,32,101,110,116,114,121,32,
-    102,105,110,100,101,114,115,10,32,32,32,32,32,32,32,32,
-    115,116,111,114,101,100,32,105,110,32,115,121,115,46,112,97,
-    116,104,95,105,109,112,111,114,116,101,114,95,99,97,99,104,
-    101,115,32,40,119,104,101,114,101,32,105,109,112,108,101,109,
-    101,110,116,101,100,41,46,218,17,105,110,118,97,108,105,100,
-    97,116,101,95,99,97,99,104,101,115,78,41,5,114,7,0,
-    0,0,218,19,112,97,116,104,95,105,109,112,111,114,116,101,
-    114,95,99,97,99,104,101,218,6,118,97,108,117,101,115,114,
-    115,0,0,0,114,250,0,0,0,41,2,114,170,0,0,0,
-    218,6,102,105,110,100,101,114,114,4,0,0,0,114,4,0,
-    0,0,114,5,0,0,0,114,250,0,0,0,15,4,0,0,
-    115,6,0,0,0,0,4,22,1,15,1,122,28,80,97,116,
-    104,70,105,110,100,101,114,46,105,110,118,97,108,105,100,97,
-    116,101,95,99,97,99,104,101,115,99,2,0,0,0,0,0,
-    0,0,3,0,0,0,12,0,0,0,67,0,0,0,115,107,
-    0,0,0,116,0,0,106,1,0,100,1,0,107,9,0,114,
-    41,0,116,0,0,106,1,0,12,114,41,0,116,2,0,106,
-    3,0,100,2,0,116,4,0,131,2,0,1,120,59,0,116,
-    0,0,106,1,0,68,93,44,0,125,2,0,121,14,0,124,
-    2,0,124,1,0,131,1,0,83,87,113,51,0,4,116,5,
-    0,107,10,0,114,94,0,1,1,1,119,51,0,89,113,51,
-    0,88,113,51,0,87,100,1,0,83,100,1,0,83,41,3,
-    122,113,83,101,97,114,99,104,32,115,101,113,117,101,110,99,
-    101,32,111,102,32,104,111,111,107,115,32,102,111,114,32,97,
-    32,102,105,110,100,101,114,32,102,111,114,32,39,112,97,116,
-    104,39,46,10,10,32,32,32,32,32,32,32,32,73,102,32,
-    39,104,111,111,107,115,39,32,105,115,32,102,97,108,115,101,
-    32,116,104,101,110,32,117,115,101,32,115,121,115,46,112,97,
-    116,104,95,104,111,111,107,115,46,10,10,32,32,32,32,32,
-    32,32,32,78,122,23,115,121,115,46,112,97,116,104,95,104,
-    111,111,107,115,32,105,115,32,101,109,112,116,121,41,6,114,
-    7,0,0,0,218,10,112,97,116,104,95,104,111,111,107,115,
-    114,60,0,0,0,114,61,0,0,0,114,125,0,0,0,114,
-    107,0,0,0,41,3,114,170,0,0,0,114,35,0,0,0,
-    90,4,104,111,111,107,114,4,0,0,0,114,4,0,0,0,
-    114,5,0,0,0,218,11,95,112,97,116,104,95,104,111,111,
-    107,115,23,4,0,0,115,16,0,0,0,0,7,25,1,16,
-    1,16,1,3,1,14,1,13,1,12,2,122,22,80,97,116,
-    104,70,105,110,100,101,114,46,95,112,97,116,104,95,104,111,
-    111,107,115,99,2,0,0,0,0,0,0,0,3,0,0,0,
-    19,0,0,0,67,0,0,0,115,123,0,0,0,124,1,0,
-    100,1,0,107,2,0,114,53,0,121,16,0,116,0,0,106,
-    1,0,131,0,0,125,1,0,87,110,22,0,4,116,2,0,
-    107,10,0,114,52,0,1,1,1,100,2,0,83,89,110,1,
-    0,88,121,17,0,116,3,0,106,4,0,124,1,0,25,125,
-    2,0,87,110,46,0,4,116,5,0,107,10,0,114,118,0,
-    1,1,1,124,0,0,106,6,0,124,1,0,131,1,0,125,
-    2,0,124,2,0,116,3,0,106,4,0,124,1,0,60,89,
-    110,1,0,88,124,2,0,83,41,3,122,210,71,101,116,32,
-    116,104,101,32,102,105,110,100,101,114,32,102,111,114,32,116,
-    104,101,32,112,97,116,104,32,101,110,116,114,121,32,102,114,
-    111,109,32,115,121,115,46,112,97,116,104,95,105,109,112,111,
-    114,116,101,114,95,99,97,99,104,101,46,10,10,32,32,32,
-    32,32,32,32,32,73,102,32,116,104,101,32,112,97,116,104,
-    32,101,110,116,114,121,32,105,115,32,110,111,116,32,105,110,
-    32,116,104,101,32,99,97,99,104,101,44,32,102,105,110,100,
-    32,116,104,101,32,97,112,112,114,111,112,114,105,97,116,101,
-    32,102,105,110,100,101,114,10,32,32,32,32,32,32,32,32,
-    97,110,100,32,99,97,99,104,101,32,105,116,46,32,73,102,
-    32,110,111,32,102,105,110,100,101,114,32,105,115,32,97,118,
-    97,105,108,97,98,108,101,44,32,115,116,111,114,101,32,78,
-    111,110,101,46,10,10,32,32,32,32,32,32,32,32,114,30,
-    0,0,0,78,41,7,114,3,0,0,0,114,45,0,0,0,
-    218,17,70,105,108,101,78,111,116,70,111,117,110,100,69,114,
-    114,111,114,114,7,0,0,0,114,251,0,0,0,114,137,0,
-    0,0,114,255,0,0,0,41,3,114,170,0,0,0,114,35,
-    0,0,0,114,253,0,0,0,114,4,0,0,0,114,4,0,
-    0,0,114,5,0,0,0,218,20,95,112,97,116,104,95,105,
-    109,112,111,114,116,101,114,95,99,97,99,104,101,40,4,0,
-    0,115,22,0,0,0,0,8,12,1,3,1,16,1,13,3,
-    9,1,3,1,17,1,13,1,15,1,18,1,122,31,80,97,
-    116,104,70,105,110,100,101,114,46,95,112,97,116,104,95,105,
-    109,112,111,114,116,101,114,95,99,97,99,104,101,99,3,0,
-    0,0,0,0,0,0,6,0,0,0,3,0,0,0,67,0,
-    0,0,115,119,0,0,0,116,0,0,124,2,0,100,1,0,
-    131,2,0,114,39,0,124,2,0,106,1,0,124,1,0,131,
-    1,0,92,2,0,125,3,0,125,4,0,110,21,0,124,2,
-    0,106,2,0,124,1,0,131,1,0,125,3,0,103,0,0,
-    125,4,0,124,3,0,100,0,0,107,9,0,114,88,0,116,
-    3,0,106,4,0,124,1,0,124,3,0,131,2,0,83,116,
-    3,0,106,5,0,124,1,0,100,0,0,131,2,0,125,5,
-    0,124,4,0,124,5,0,95,6,0,124,5,0,83,41,2,
-    78,114,124,0,0,0,41,7,114,115,0,0,0,114,124,0,
-    0,0,114,182,0,0,0,114,121,0,0,0,114,179,0,0,
-    0,114,160,0,0,0,114,156,0,0,0,41,6,114,170,0,
-    0,0,114,126,0,0,0,114,253,0,0,0,114,127,0,0,
-    0,114,128,0,0,0,114,164,0,0,0,114,4,0,0,0,
-    114,4,0,0,0,114,5,0,0,0,218,16,95,108,101,103,
-    97,99,121,95,103,101,116,95,115,112,101,99,62,4,0,0,
-    115,18,0,0,0,0,4,15,1,24,2,15,1,6,1,12,
-    1,16,1,18,1,9,1,122,27,80,97,116,104,70,105,110,
-    100,101,114,46,95,108,101,103,97,99,121,95,103,101,116,95,
-    115,112,101,99,78,99,4,0,0,0,0,0,0,0,9,0,
-    0,0,5,0,0,0,67,0,0,0,115,243,0,0,0,103,
-    0,0,125,4,0,120,230,0,124,2,0,68,93,191,0,125,
-    5,0,116,0,0,124,5,0,116,1,0,116,2,0,102,2,
-    0,131,2,0,115,43,0,113,13,0,124,0,0,106,3,0,
-    124,5,0,131,1,0,125,6,0,124,6,0,100,1,0,107,
-    9,0,114,13,0,116,4,0,124,6,0,100,2,0,131,2,
-    0,114,106,0,124,6,0,106,5,0,124,1,0,124,3,0,
-    131,2,0,125,7,0,110,18,0,124,0,0,106,6,0,124,
-    1,0,124,6,0,131,2,0,125,7,0,124,7,0,100,1,
-    0,107,8,0,114,139,0,113,13,0,124,7,0,106,7,0,
-    100,1,0,107,9,0,114,158,0,124,7,0,83,124,7,0,
-    106,8,0,125,8,0,124,8,0,100,1,0,107,8,0,114,
-    191,0,116,9,0,100,3,0,131,1,0,130,1,0,124,4,
-    0,106,10,0,124,8,0,131,1,0,1,113,13,0,87,116,
-    11,0,106,12,0,124,1,0,100,1,0,131,2,0,125,7,
-    0,124,4,0,124,7,0,95,8,0,124,7,0,83,100,1,
-    0,83,41,4,122,63,70,105,110,100,32,116,104,101,32,108,
-    111,97,100,101,114,32,111,114,32,110,97,109,101,115,112,97,
-    99,101,95,112,97,116,104,32,102,111,114,32,116,104,105,115,
-    32,109,111,100,117,108,101,47,112,97,99,107,97,103,101,32,
-    110,97,109,101,46,78,114,181,0,0,0,122,19,115,112,101,
-    99,32,109,105,115,115,105,110,103,32,108,111,97,100,101,114,
-    41,13,114,143,0,0,0,114,69,0,0,0,218,5,98,121,
-    116,101,115,114,1,1,0,0,114,115,0,0,0,114,181,0,
-    0,0,114,2,1,0,0,114,127,0,0,0,114,156,0,0,
-    0,114,107,0,0,0,114,149,0,0,0,114,121,0,0,0,
-    114,160,0,0,0,41,9,114,170,0,0,0,114,126,0,0,
-    0,114,35,0,0,0,114,180,0,0,0,218,14,110,97,109,
-    101,115,112,97,99,101,95,112,97,116,104,90,5,101,110,116,
-    114,121,114,253,0,0,0,114,164,0,0,0,114,128,0,0,
-    0,114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,
-    218,9,95,103,101,116,95,115,112,101,99,77,4,0,0,115,
-    40,0,0,0,0,5,6,1,13,1,21,1,3,1,15,1,
-    12,1,15,1,21,2,18,1,12,1,3,1,15,1,4,1,
-    9,1,12,1,12,5,17,2,18,1,9,1,122,20,80,97,
-    116,104,70,105,110,100,101,114,46,95,103,101,116,95,115,112,
-    101,99,99,4,0,0,0,0,0,0,0,6,0,0,0,4,
-    0,0,0,67,0,0,0,115,140,0,0,0,124,2,0,100,
-    1,0,107,8,0,114,21,0,116,0,0,106,1,0,125,2,
-    0,124,0,0,106,2,0,124,1,0,124,2,0,124,3,0,
-    131,3,0,125,4,0,124,4,0,100,1,0,107,8,0,114,
-    58,0,100,1,0,83,124,4,0,106,3,0,100,1,0,107,
-    8,0,114,132,0,124,4,0,106,4,0,125,5,0,124,5,
-    0,114,125,0,100,2,0,124,4,0,95,5,0,116,6,0,
-    124,1,0,124,5,0,124,0,0,106,2,0,131,3,0,124,
-    4,0,95,4,0,124,4,0,83,100,1,0,83,110,4,0,
-    124,4,0,83,100,1,0,83,41,3,122,98,102,105,110,100,
-    32,116,104,101,32,109,111,100,117,108,101,32,111,110,32,115,
-    121,115,46,112,97,116,104,32,111,114,32,39,112,97,116,104,
-    39,32,98,97,115,101,100,32,111,110,32,115,121,115,46,112,
-    97,116,104,95,104,111,111,107,115,32,97,110,100,10,32,32,
-    32,32,32,32,32,32,115,121,115,46,112,97,116,104,95,105,
-    109,112,111,114,116,101,114,95,99,97,99,104,101,46,78,90,
-    9,110,97,109,101,115,112,97,99,101,41,7,114,7,0,0,
-    0,114,35,0,0,0,114,5,1,0,0,114,127,0,0,0,
-    114,156,0,0,0,114,158,0,0,0,114,230,0,0,0,41,
-    6,114,170,0,0,0,114,126,0,0,0,114,35,0,0,0,
-    114,180,0,0,0,114,164,0,0,0,114,4,1,0,0,114,
-    4,0,0,0,114,4,0,0,0,114,5,0,0,0,114,181,
-    0,0,0,109,4,0,0,115,26,0,0,0,0,4,12,1,
-    9,1,21,1,12,1,4,1,15,1,9,1,6,3,9,1,
-    24,1,4,2,7,2,122,20,80,97,116,104,70,105,110,100,
-    101,114,46,102,105,110,100,95,115,112,101,99,99,3,0,0,
+    67,0,0,0,115,4,0,0,0,100,1,0,83,41,2,122,
+    53,82,101,116,117,114,110,32,78,111,110,101,32,97,115,32,
+    101,120,116,101,110,115,105,111,110,32,109,111,100,117,108,101,
+    115,32,104,97,118,101,32,110,111,32,115,111,117,114,99,101,
+    32,99,111,100,101,46,78,114,4,0,0,0,41,2,114,110,
+    0,0,0,114,128,0,0,0,114,4,0,0,0,114,4,0,
+    0,0,114,6,0,0,0,114,203,0,0,0,167,3,0,0,
+    115,2,0,0,0,0,2,122,30,69,120,116,101,110,115,105,
+    111,110,70,105,108,101,76,111,97,100,101,114,46,103,101,116,
+    95,115,111,117,114,99,101,99,2,0,0,0,0,0,0,0,
+    2,0,0,0,1,0,0,0,67,0,0,0,115,7,0,0,
+    0,124,0,0,106,0,0,83,41,1,122,58,82,101,116,117,
+    114,110,32,116,104,101,32,112,97,116,104,32,116,111,32,116,
+    104,101,32,115,111,117,114,99,101,32,102,105,108,101,32,97,
+    115,32,102,111,117,110,100,32,98,121,32,116,104,101,32,102,
+    105,110,100,101,114,46,41,1,114,37,0,0,0,41,2,114,
+    110,0,0,0,114,128,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,114,159,0,0,0,171,3,0,
+    0,115,2,0,0,0,0,3,122,32,69,120,116,101,110,115,
+    105,111,110,70,105,108,101,76,111,97,100,101,114,46,103,101,
+    116,95,102,105,108,101,110,97,109,101,78,41,14,114,114,0,
+    0,0,114,113,0,0,0,114,115,0,0,0,114,116,0,0,
+    0,114,186,0,0,0,114,214,0,0,0,114,216,0,0,0,
+    114,187,0,0,0,114,192,0,0,0,114,161,0,0,0,114,
+    188,0,0,0,114,203,0,0,0,114,125,0,0,0,114,159,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,114,4,0,
+    0,0,114,6,0,0,0,114,225,0,0,0,124,3,0,0,
+    115,20,0,0,0,12,6,6,2,12,4,12,4,12,3,12,
+    8,12,6,12,6,12,4,12,4,114,225,0,0,0,99,0,
+    0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,64,
+    0,0,0,115,130,0,0,0,101,0,0,90,1,0,100,0,
+    0,90,2,0,100,1,0,90,3,0,100,2,0,100,3,0,
+    132,0,0,90,4,0,100,4,0,100,5,0,132,0,0,90,
+    5,0,100,6,0,100,7,0,132,0,0,90,6,0,100,8,
+    0,100,9,0,132,0,0,90,7,0,100,10,0,100,11,0,
+    132,0,0,90,8,0,100,12,0,100,13,0,132,0,0,90,
+    9,0,100,14,0,100,15,0,132,0,0,90,10,0,100,16,
+    0,100,17,0,132,0,0,90,11,0,100,18,0,100,19,0,
+    132,0,0,90,12,0,100,20,0,83,41,21,218,14,95,78,
+    97,109,101,115,112,97,99,101,80,97,116,104,97,38,1,0,
+    0,82,101,112,114,101,115,101,110,116,115,32,97,32,110,97,
+    109,101,115,112,97,99,101,32,112,97,99,107,97,103,101,39,
+    115,32,112,97,116,104,46,32,32,73,116,32,117,115,101,115,
+    32,116,104,101,32,109,111,100,117,108,101,32,110,97,109,101,
+    10,32,32,32,32,116,111,32,102,105,110,100,32,105,116,115,
+    32,112,97,114,101,110,116,32,109,111,100,117,108,101,44,32,
+    97,110,100,32,102,114,111,109,32,116,104,101,114,101,32,105,
+    116,32,108,111,111,107,115,32,117,112,32,116,104,101,32,112,
+    97,114,101,110,116,39,115,10,32,32,32,32,95,95,112,97,
+    116,104,95,95,46,32,32,87,104,101,110,32,116,104,105,115,
+    32,99,104,97,110,103,101,115,44,32,116,104,101,32,109,111,
+    100,117,108,101,39,115,32,111,119,110,32,112,97,116,104,32,
+    105,115,32,114,101,99,111,109,112,117,116,101,100,44,10,32,
+    32,32,32,117,115,105,110,103,32,112,97,116,104,95,102,105,
+    110,100,101,114,46,32,32,70,111,114,32,116,111,112,45,108,
+    101,118,101,108,32,109,111,100,117,108,101,115,44,32,116,104,
+    101,32,112,97,114,101,110,116,32,109,111,100,117,108,101,39,
+    115,32,112,97,116,104,10,32,32,32,32,105,115,32,115,121,
+    115,46,112,97,116,104,46,99,4,0,0,0,0,0,0,0,
+    4,0,0,0,2,0,0,0,67,0,0,0,115,52,0,0,
+    0,124,1,0,124,0,0,95,0,0,124,2,0,124,0,0,
+    95,1,0,116,2,0,124,0,0,106,3,0,131,0,0,131,
+    1,0,124,0,0,95,4,0,124,3,0,124,0,0,95,5,
+    0,100,0,0,83,41,1,78,41,6,218,5,95,110,97,109,
+    101,218,5,95,112,97,116,104,114,95,0,0,0,218,16,95,
+    103,101,116,95,112,97,114,101,110,116,95,112,97,116,104,218,
+    17,95,108,97,115,116,95,112,97,114,101,110,116,95,112,97,
+    116,104,218,12,95,112,97,116,104,95,102,105,110,100,101,114,
+    41,4,114,110,0,0,0,114,108,0,0,0,114,37,0,0,
+    0,218,11,112,97,116,104,95,102,105,110,100,101,114,114,4,
+    0,0,0,114,4,0,0,0,114,6,0,0,0,114,186,0,
+    0,0,184,3,0,0,115,8,0,0,0,0,1,9,1,9,
+    1,21,1,122,23,95,78,97,109,101,115,112,97,99,101,80,
+    97,116,104,46,95,95,105,110,105,116,95,95,99,1,0,0,
     0,0,0,0,0,4,0,0,0,3,0,0,0,67,0,0,
-    0,115,41,0,0,0,124,0,0,106,0,0,124,1,0,124,
-    2,0,131,2,0,125,3,0,124,3,0,100,1,0,107,8,
-    0,114,34,0,100,1,0,83,124,3,0,106,1,0,83,41,
-    2,122,170,102,105,110,100,32,116,104,101,32,109,111,100,117,
-    108,101,32,111,110,32,115,121,115,46,112,97,116,104,32,111,
-    114,32,39,112,97,116,104,39,32,98,97,115,101,100,32,111,
-    110,32,115,121,115,46,112,97,116,104,95,104,111,111,107,115,
-    32,97,110,100,10,32,32,32,32,32,32,32,32,115,121,115,
+    0,115,53,0,0,0,124,0,0,106,0,0,106,1,0,100,
+    1,0,131,1,0,92,3,0,125,1,0,125,2,0,125,3,
+    0,124,2,0,100,2,0,107,2,0,114,43,0,100,6,0,
+    83,124,1,0,100,5,0,102,2,0,83,41,7,122,62,82,
+    101,116,117,114,110,115,32,97,32,116,117,112,108,101,32,111,
+    102,32,40,112,97,114,101,110,116,45,109,111,100,117,108,101,
+    45,110,97,109,101,44,32,112,97,114,101,110,116,45,112,97,
+    116,104,45,97,116,116,114,45,110,97,109,101,41,114,60,0,
+    0,0,114,32,0,0,0,114,8,0,0,0,114,37,0,0,
+    0,90,8,95,95,112,97,116,104,95,95,41,2,114,8,0,
+    0,0,114,37,0,0,0,41,2,114,232,0,0,0,114,34,
+    0,0,0,41,4,114,110,0,0,0,114,223,0,0,0,218,
+    3,100,111,116,90,2,109,101,114,4,0,0,0,114,4,0,
+    0,0,114,6,0,0,0,218,23,95,102,105,110,100,95,112,
+    97,114,101,110,116,95,112,97,116,104,95,110,97,109,101,115,
+    190,3,0,0,115,8,0,0,0,0,2,27,1,12,2,4,
+    3,122,38,95,78,97,109,101,115,112,97,99,101,80,97,116,
+    104,46,95,102,105,110,100,95,112,97,114,101,110,116,95,112,
+    97,116,104,95,110,97,109,101,115,99,1,0,0,0,0,0,
+    0,0,3,0,0,0,3,0,0,0,67,0,0,0,115,38,
+    0,0,0,124,0,0,106,0,0,131,0,0,92,2,0,125,
+    1,0,125,2,0,116,1,0,116,2,0,106,3,0,124,1,
+    0,25,124,2,0,131,2,0,83,41,1,78,41,4,114,239,
+    0,0,0,114,119,0,0,0,114,8,0,0,0,218,7,109,
+    111,100,117,108,101,115,41,3,114,110,0,0,0,90,18,112,
+    97,114,101,110,116,95,109,111,100,117,108,101,95,110,97,109,
+    101,90,14,112,97,116,104,95,97,116,116,114,95,110,97,109,
+    101,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    114,234,0,0,0,200,3,0,0,115,4,0,0,0,0,1,
+    18,1,122,31,95,78,97,109,101,115,112,97,99,101,80,97,
+    116,104,46,95,103,101,116,95,112,97,114,101,110,116,95,112,
+    97,116,104,99,1,0,0,0,0,0,0,0,3,0,0,0,
+    3,0,0,0,67,0,0,0,115,118,0,0,0,116,0,0,
+    124,0,0,106,1,0,131,0,0,131,1,0,125,1,0,124,
+    1,0,124,0,0,106,2,0,107,3,0,114,111,0,124,0,
+    0,106,3,0,124,0,0,106,4,0,124,1,0,131,2,0,
+    125,2,0,124,2,0,100,0,0,107,9,0,114,102,0,124,
+    2,0,106,5,0,100,0,0,107,8,0,114,102,0,124,2,
+    0,106,6,0,114,102,0,124,2,0,106,6,0,124,0,0,
+    95,7,0,124,1,0,124,0,0,95,2,0,124,0,0,106,
+    7,0,83,41,1,78,41,8,114,95,0,0,0,114,234,0,
+    0,0,114,235,0,0,0,114,236,0,0,0,114,232,0,0,
+    0,114,129,0,0,0,114,158,0,0,0,114,233,0,0,0,
+    41,3,114,110,0,0,0,90,11,112,97,114,101,110,116,95,
+    112,97,116,104,114,166,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,12,95,114,101,99,97,108,
+    99,117,108,97,116,101,204,3,0,0,115,16,0,0,0,0,
+    2,18,1,15,1,21,3,27,1,9,1,12,1,9,1,122,
+    27,95,78,97,109,101,115,112,97,99,101,80,97,116,104,46,
+    95,114,101,99,97,108,99,117,108,97,116,101,99,1,0,0,
+    0,0,0,0,0,1,0,0,0,2,0,0,0,67,0,0,
+    0,115,16,0,0,0,116,0,0,124,0,0,106,1,0,131,
+    0,0,131,1,0,83,41,1,78,41,2,218,4,105,116,101,
+    114,114,241,0,0,0,41,1,114,110,0,0,0,114,4,0,
+    0,0,114,4,0,0,0,114,6,0,0,0,218,8,95,95,
+    105,116,101,114,95,95,217,3,0,0,115,2,0,0,0,0,
+    1,122,23,95,78,97,109,101,115,112,97,99,101,80,97,116,
+    104,46,95,95,105,116,101,114,95,95,99,1,0,0,0,0,
+    0,0,0,1,0,0,0,2,0,0,0,67,0,0,0,115,
+    16,0,0,0,116,0,0,124,0,0,106,1,0,131,0,0,
+    131,1,0,83,41,1,78,41,2,114,33,0,0,0,114,241,
+    0,0,0,41,1,114,110,0,0,0,114,4,0,0,0,114,
+    4,0,0,0,114,6,0,0,0,218,7,95,95,108,101,110,
+    95,95,220,3,0,0,115,2,0,0,0,0,1,122,22,95,
+    78,97,109,101,115,112,97,99,101,80,97,116,104,46,95,95,
+    108,101,110,95,95,99,1,0,0,0,0,0,0,0,1,0,
+    0,0,2,0,0,0,67,0,0,0,115,16,0,0,0,100,
+    1,0,106,0,0,124,0,0,106,1,0,131,1,0,83,41,
+    2,78,122,20,95,78,97,109,101,115,112,97,99,101,80,97,
+    116,104,40,123,33,114,125,41,41,2,114,49,0,0,0,114,
+    233,0,0,0,41,1,114,110,0,0,0,114,4,0,0,0,
+    114,4,0,0,0,114,6,0,0,0,218,8,95,95,114,101,
+    112,114,95,95,223,3,0,0,115,2,0,0,0,0,1,122,
+    23,95,78,97,109,101,115,112,97,99,101,80,97,116,104,46,
+    95,95,114,101,112,114,95,95,99,2,0,0,0,0,0,0,
+    0,2,0,0,0,2,0,0,0,67,0,0,0,115,16,0,
+    0,0,124,1,0,124,0,0,106,0,0,131,0,0,107,6,
+    0,83,41,1,78,41,1,114,241,0,0,0,41,2,114,110,
+    0,0,0,218,4,105,116,101,109,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,12,95,95,99,111,110,116,
+    97,105,110,115,95,95,226,3,0,0,115,2,0,0,0,0,
+    1,122,27,95,78,97,109,101,115,112,97,99,101,80,97,116,
+    104,46,95,95,99,111,110,116,97,105,110,115,95,95,99,2,
+    0,0,0,0,0,0,0,2,0,0,0,2,0,0,0,67,
+    0,0,0,115,20,0,0,0,124,0,0,106,0,0,106,1,
+    0,124,1,0,131,1,0,1,100,0,0,83,41,1,78,41,
+    2,114,233,0,0,0,114,165,0,0,0,41,2,114,110,0,
+    0,0,114,246,0,0,0,114,4,0,0,0,114,4,0,0,
+    0,114,6,0,0,0,114,165,0,0,0,229,3,0,0,115,
+    2,0,0,0,0,1,122,21,95,78,97,109,101,115,112,97,
+    99,101,80,97,116,104,46,97,112,112,101,110,100,78,41,13,
+    114,114,0,0,0,114,113,0,0,0,114,115,0,0,0,114,
+    116,0,0,0,114,186,0,0,0,114,239,0,0,0,114,234,
+    0,0,0,114,241,0,0,0,114,243,0,0,0,114,244,0,
+    0,0,114,245,0,0,0,114,247,0,0,0,114,165,0,0,
+    0,114,4,0,0,0,114,4,0,0,0,114,4,0,0,0,
+    114,6,0,0,0,114,231,0,0,0,177,3,0,0,115,20,
+    0,0,0,12,5,6,2,12,6,12,10,12,4,12,13,12,
+    3,12,3,12,3,12,3,114,231,0,0,0,99,0,0,0,
+    0,0,0,0,0,0,0,0,0,3,0,0,0,64,0,0,
+    0,115,118,0,0,0,101,0,0,90,1,0,100,0,0,90,
+    2,0,100,1,0,100,2,0,132,0,0,90,3,0,101,4,
+    0,100,3,0,100,4,0,132,0,0,131,1,0,90,5,0,
+    100,5,0,100,6,0,132,0,0,90,6,0,100,7,0,100,
+    8,0,132,0,0,90,7,0,100,9,0,100,10,0,132,0,
+    0,90,8,0,100,11,0,100,12,0,132,0,0,90,9,0,
+    100,13,0,100,14,0,132,0,0,90,10,0,100,15,0,100,
+    16,0,132,0,0,90,11,0,100,17,0,83,41,18,218,16,
+    95,78,97,109,101,115,112,97,99,101,76,111,97,100,101,114,
+    99,4,0,0,0,0,0,0,0,4,0,0,0,4,0,0,
+    0,67,0,0,0,115,25,0,0,0,116,0,0,124,1,0,
+    124,2,0,124,3,0,131,3,0,124,0,0,95,1,0,100,
+    0,0,83,41,1,78,41,2,114,231,0,0,0,114,233,0,
+    0,0,41,4,114,110,0,0,0,114,108,0,0,0,114,37,
+    0,0,0,114,237,0,0,0,114,4,0,0,0,114,4,0,
+    0,0,114,6,0,0,0,114,186,0,0,0,235,3,0,0,
+    115,2,0,0,0,0,1,122,25,95,78,97,109,101,115,112,
+    97,99,101,76,111,97,100,101,114,46,95,95,105,110,105,116,
+    95,95,99,2,0,0,0,0,0,0,0,2,0,0,0,2,
+    0,0,0,67,0,0,0,115,16,0,0,0,100,1,0,106,
+    0,0,124,1,0,106,1,0,131,1,0,83,41,2,122,115,
+    82,101,116,117,114,110,32,114,101,112,114,32,102,111,114,32,
+    116,104,101,32,109,111,100,117,108,101,46,10,10,32,32,32,
+    32,32,32,32,32,84,104,101,32,109,101,116,104,111,100,32,
+    105,115,32,100,101,112,114,101,99,97,116,101,100,46,32,32,
+    84,104,101,32,105,109,112,111,114,116,32,109,97,99,104,105,
+    110,101,114,121,32,100,111,101,115,32,116,104,101,32,106,111,
+    98,32,105,116,115,101,108,102,46,10,10,32,32,32,32,32,
+    32,32,32,122,25,60,109,111,100,117,108,101,32,123,33,114,
+    125,32,40,110,97,109,101,115,112,97,99,101,41,62,41,2,
+    114,49,0,0,0,114,114,0,0,0,41,2,114,172,0,0,
+    0,114,191,0,0,0,114,4,0,0,0,114,4,0,0,0,
+    114,6,0,0,0,218,11,109,111,100,117,108,101,95,114,101,
+    112,114,238,3,0,0,115,2,0,0,0,0,7,122,28,95,
+    78,97,109,101,115,112,97,99,101,76,111,97,100,101,114,46,
+    109,111,100,117,108,101,95,114,101,112,114,99,2,0,0,0,
+    0,0,0,0,2,0,0,0,1,0,0,0,67,0,0,0,
+    115,4,0,0,0,100,1,0,83,41,2,78,84,114,4,0,
+    0,0,41,2,114,110,0,0,0,114,128,0,0,0,114,4,
+    0,0,0,114,4,0,0,0,114,6,0,0,0,114,161,0,
+    0,0,247,3,0,0,115,2,0,0,0,0,1,122,27,95,
+    78,97,109,101,115,112,97,99,101,76,111,97,100,101,114,46,
+    105,115,95,112,97,99,107,97,103,101,99,2,0,0,0,0,
+    0,0,0,2,0,0,0,1,0,0,0,67,0,0,0,115,
+    4,0,0,0,100,1,0,83,41,2,78,114,32,0,0,0,
+    114,4,0,0,0,41,2,114,110,0,0,0,114,128,0,0,
+    0,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    114,203,0,0,0,250,3,0,0,115,2,0,0,0,0,1,
+    122,27,95,78,97,109,101,115,112,97,99,101,76,111,97,100,
+    101,114,46,103,101,116,95,115,111,117,114,99,101,99,2,0,
+    0,0,0,0,0,0,2,0,0,0,6,0,0,0,67,0,
+    0,0,115,22,0,0,0,116,0,0,100,1,0,100,2,0,
+    100,3,0,100,4,0,100,5,0,131,3,1,83,41,6,78,
+    114,32,0,0,0,122,8,60,115,116,114,105,110,103,62,114,
+    190,0,0,0,114,205,0,0,0,84,41,1,114,206,0,0,
+    0,41,2,114,110,0,0,0,114,128,0,0,0,114,4,0,
+    0,0,114,4,0,0,0,114,6,0,0,0,114,188,0,0,
+    0,253,3,0,0,115,2,0,0,0,0,1,122,25,95,78,
+    97,109,101,115,112,97,99,101,76,111,97,100,101,114,46,103,
+    101,116,95,99,111,100,101,99,2,0,0,0,0,0,0,0,
+    2,0,0,0,1,0,0,0,67,0,0,0,115,4,0,0,
+    0,100,1,0,83,41,2,122,42,85,115,101,32,100,101,102,
+    97,117,108,116,32,115,101,109,97,110,116,105,99,115,32,102,
+    111,114,32,109,111,100,117,108,101,32,99,114,101,97,116,105,
+    111,110,46,78,114,4,0,0,0,41,2,114,110,0,0,0,
+    114,166,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
+    6,0,0,0,114,187,0,0,0,0,4,0,0,115,0,0,
+    0,0,122,30,95,78,97,109,101,115,112,97,99,101,76,111,
+    97,100,101,114,46,99,114,101,97,116,101,95,109,111,100,117,
+    108,101,99,2,0,0,0,0,0,0,0,2,0,0,0,1,
+    0,0,0,67,0,0,0,115,4,0,0,0,100,0,0,83,
+    41,1,78,114,4,0,0,0,41,2,114,110,0,0,0,114,
+    191,0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,
+    0,0,0,114,192,0,0,0,3,4,0,0,115,2,0,0,
+    0,0,1,122,28,95,78,97,109,101,115,112,97,99,101,76,
+    111,97,100,101,114,46,101,120,101,99,95,109,111,100,117,108,
+    101,99,2,0,0,0,0,0,0,0,2,0,0,0,3,0,
+    0,0,67,0,0,0,115,32,0,0,0,116,0,0,100,1,
+    0,124,0,0,106,1,0,131,2,0,1,116,2,0,106,3,
+    0,124,0,0,124,1,0,131,2,0,83,41,2,122,98,76,
+    111,97,100,32,97,32,110,97,109,101,115,112,97,99,101,32,
+    109,111,100,117,108,101,46,10,10,32,32,32,32,32,32,32,
+    32,84,104,105,115,32,109,101,116,104,111,100,32,105,115,32,
+    100,101,112,114,101,99,97,116,101,100,46,32,32,85,115,101,
+    32,101,120,101,99,95,109,111,100,117,108,101,40,41,32,105,
+    110,115,116,101,97,100,46,10,10,32,32,32,32,32,32,32,
+    32,122,38,110,97,109,101,115,112,97,99,101,32,109,111,100,
+    117,108,101,32,108,111,97,100,101,100,32,119,105,116,104,32,
+    112,97,116,104,32,123,33,114,125,41,4,114,107,0,0,0,
+    114,233,0,0,0,114,123,0,0,0,114,193,0,0,0,41,
+    2,114,110,0,0,0,114,128,0,0,0,114,4,0,0,0,
+    114,4,0,0,0,114,6,0,0,0,114,194,0,0,0,6,
+    4,0,0,115,4,0,0,0,0,7,16,1,122,28,95,78,
+    97,109,101,115,112,97,99,101,76,111,97,100,101,114,46,108,
+    111,97,100,95,109,111,100,117,108,101,78,41,12,114,114,0,
+    0,0,114,113,0,0,0,114,115,0,0,0,114,186,0,0,
+    0,114,184,0,0,0,114,249,0,0,0,114,161,0,0,0,
+    114,203,0,0,0,114,188,0,0,0,114,187,0,0,0,114,
+    192,0,0,0,114,194,0,0,0,114,4,0,0,0,114,4,
+    0,0,0,114,4,0,0,0,114,6,0,0,0,114,248,0,
+    0,0,234,3,0,0,115,16,0,0,0,12,1,12,3,18,
+    9,12,3,12,3,12,3,12,3,12,3,114,248,0,0,0,
+    99,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,
+    0,64,0,0,0,115,160,0,0,0,101,0,0,90,1,0,
+    100,0,0,90,2,0,100,1,0,90,3,0,101,4,0,100,
+    2,0,100,3,0,132,0,0,131,1,0,90,5,0,101,4,
+    0,100,4,0,100,5,0,132,0,0,131,1,0,90,6,0,
+    101,4,0,100,6,0,100,7,0,132,0,0,131,1,0,90,
+    7,0,101,4,0,100,8,0,100,9,0,132,0,0,131,1,
+    0,90,8,0,101,4,0,100,10,0,100,11,0,100,12,0,
+    132,1,0,131,1,0,90,9,0,101,4,0,100,10,0,100,
+    10,0,100,13,0,100,14,0,132,2,0,131,1,0,90,10,
+    0,101,4,0,100,10,0,100,15,0,100,16,0,132,1,0,
+    131,1,0,90,11,0,100,10,0,83,41,17,218,10,80,97,
+    116,104,70,105,110,100,101,114,122,62,77,101,116,97,32,112,
+    97,116,104,32,102,105,110,100,101,114,32,102,111,114,32,115,
+    121,115,46,112,97,116,104,32,97,110,100,32,112,97,99,107,
+    97,103,101,32,95,95,112,97,116,104,95,95,32,97,116,116,
+    114,105,98,117,116,101,115,46,99,1,0,0,0,0,0,0,
+    0,2,0,0,0,4,0,0,0,67,0,0,0,115,55,0,
+    0,0,120,48,0,116,0,0,106,1,0,106,2,0,131,0,
+    0,68,93,31,0,125,1,0,116,3,0,124,1,0,100,1,
+    0,131,2,0,114,16,0,124,1,0,106,4,0,131,0,0,
+    1,113,16,0,87,100,2,0,83,41,3,122,125,67,97,108,
+    108,32,116,104,101,32,105,110,118,97,108,105,100,97,116,101,
+    95,99,97,99,104,101,115,40,41,32,109,101,116,104,111,100,
+    32,111,110,32,97,108,108,32,112,97,116,104,32,101,110,116,
+    114,121,32,102,105,110,100,101,114,115,10,32,32,32,32,32,
+    32,32,32,115,116,111,114,101,100,32,105,110,32,115,121,115,
     46,112,97,116,104,95,105,109,112,111,114,116,101,114,95,99,
-    97,99,104,101,46,10,10,32,32,32,32,32,32,32,32,84,
-    104,105,115,32,109,101,116,104,111,100,32,105,115,32,100,101,
-    112,114,101,99,97,116,101,100,46,32,32,85,115,101,32,102,
-    105,110,100,95,115,112,101,99,40,41,32,105,110,115,116,101,
-    97,100,46,10,10,32,32,32,32,32,32,32,32,78,41,2,
-    114,181,0,0,0,114,127,0,0,0,41,4,114,170,0,0,
-    0,114,126,0,0,0,114,35,0,0,0,114,164,0,0,0,
-    114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,114,
-    182,0,0,0,131,4,0,0,115,8,0,0,0,0,8,18,
-    1,12,1,4,1,122,22,80,97,116,104,70,105,110,100,101,
-    114,46,102,105,110,100,95,109,111,100,117,108,101,41,12,114,
-    112,0,0,0,114,111,0,0,0,114,113,0,0,0,114,114,
-    0,0,0,114,183,0,0,0,114,250,0,0,0,114,255,0,
-    0,0,114,1,1,0,0,114,2,1,0,0,114,5,1,0,
-    0,114,181,0,0,0,114,182,0,0,0,114,4,0,0,0,
-    114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,114,
-    249,0,0,0,11,4,0,0,115,22,0,0,0,12,2,6,
-    2,18,8,18,17,18,22,18,15,3,1,18,31,3,1,21,
-    21,3,1,114,249,0,0,0,99,0,0,0,0,0,0,0,
-    0,0,0,0,0,3,0,0,0,64,0,0,0,115,133,0,
-    0,0,101,0,0,90,1,0,100,0,0,90,2,0,100,1,
-    0,90,3,0,100,2,0,100,3,0,132,0,0,90,4,0,
-    100,4,0,100,5,0,132,0,0,90,5,0,101,6,0,90,
-    7,0,100,6,0,100,7,0,132,0,0,90,8,0,100,8,
-    0,100,9,0,132,0,0,90,9,0,100,10,0,100,11,0,
-    100,12,0,132,1,0,90,10,0,100,13,0,100,14,0,132,
-    0,0,90,11,0,101,12,0,100,15,0,100,16,0,132,0,
-    0,131,1,0,90,13,0,100,17,0,100,18,0,132,0,0,
-    90,14,0,100,10,0,83,41,19,218,10,70,105,108,101,70,
-    105,110,100,101,114,122,172,70,105,108,101,45,98,97,115,101,
-    100,32,102,105,110,100,101,114,46,10,10,32,32,32,32,73,
-    110,116,101,114,97,99,116,105,111,110,115,32,119,105,116,104,
-    32,116,104,101,32,102,105,108,101,32,115,121,115,116,101,109,
-    32,97,114,101,32,99,97,99,104,101,100,32,102,111,114,32,
-    112,101,114,102,111,114,109,97,110,99,101,44,32,98,101,105,
-    110,103,10,32,32,32,32,114,101,102,114,101,115,104,101,100,
-    32,119,104,101,110,32,116,104,101,32,100,105,114,101,99,116,
-    111,114,121,32,116,104,101,32,102,105,110,100,101,114,32,105,
-    115,32,104,97,110,100,108,105,110,103,32,104,97,115,32,98,
-    101,101,110,32,109,111,100,105,102,105,101,100,46,10,10,32,
-    32,32,32,99,2,0,0,0,0,0,0,0,5,0,0,0,
-    5,0,0,0,7,0,0,0,115,122,0,0,0,103,0,0,
-    125,3,0,120,52,0,124,2,0,68,93,44,0,92,2,0,
-    137,0,0,125,4,0,124,3,0,106,0,0,135,0,0,102,
-    1,0,100,1,0,100,2,0,134,0,0,124,4,0,68,131,
-    1,0,131,1,0,1,113,13,0,87,124,3,0,124,0,0,
-    95,1,0,124,1,0,112,79,0,100,3,0,124,0,0,95,
-    2,0,100,6,0,124,0,0,95,3,0,116,4,0,131,0,
-    0,124,0,0,95,5,0,116,4,0,131,0,0,124,0,0,
-    95,6,0,100,5,0,83,41,7,122,154,73,110,105,116,105,
-    97,108,105,122,101,32,119,105,116,104,32,116,104,101,32,112,
-    97,116,104,32,116,111,32,115,101,97,114,99,104,32,111,110,
-    32,97,110,100,32,97,32,118,97,114,105,97,98,108,101,32,
-    110,117,109,98,101,114,32,111,102,10,32,32,32,32,32,32,
-    32,32,50,45,116,117,112,108,101,115,32,99,111,110,116,97,
-    105,110,105,110,103,32,116,104,101,32,108,111,97,100,101,114,
-    32,97,110,100,32,116,104,101,32,102,105,108,101,32,115,117,
-    102,102,105,120,101,115,32,116,104,101,32,108,111,97,100,101,
-    114,10,32,32,32,32,32,32,32,32,114,101,99,111,103,110,
-    105,122,101,115,46,99,1,0,0,0,0,0,0,0,2,0,
-    0,0,3,0,0,0,51,0,0,0,115,27,0,0,0,124,
-    0,0,93,17,0,125,1,0,124,1,0,136,0,0,102,2,
-    0,86,1,113,3,0,100,0,0,83,41,1,78,114,4,0,
-    0,0,41,2,114,22,0,0,0,114,225,0,0,0,41,1,
-    114,127,0,0,0,114,4,0,0,0,114,5,0,0,0,114,
-    227,0,0,0,160,4,0,0,115,2,0,0,0,6,0,122,
-    38,70,105,108,101,70,105,110,100,101,114,46,95,95,105,110,
-    105,116,95,95,46,60,108,111,99,97,108,115,62,46,60,103,
-    101,110,101,120,112,114,62,114,58,0,0,0,114,29,0,0,
-    0,78,114,87,0,0,0,41,7,114,149,0,0,0,218,8,
-    95,108,111,97,100,101,114,115,114,35,0,0,0,218,11,95,
-    112,97,116,104,95,109,116,105,109,101,218,3,115,101,116,218,
-    11,95,112,97,116,104,95,99,97,99,104,101,218,19,95,114,
-    101,108,97,120,101,100,95,112,97,116,104,95,99,97,99,104,
-    101,41,5,114,108,0,0,0,114,35,0,0,0,218,14,108,
-    111,97,100,101,114,95,100,101,116,97,105,108,115,90,7,108,
-    111,97,100,101,114,115,114,166,0,0,0,114,4,0,0,0,
-    41,1,114,127,0,0,0,114,5,0,0,0,114,185,0,0,
-    0,154,4,0,0,115,16,0,0,0,0,4,6,1,19,1,
-    36,1,9,2,15,1,9,1,12,1,122,19,70,105,108,101,
-    70,105,110,100,101,114,46,95,95,105,110,105,116,95,95,99,
-    1,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,
-    67,0,0,0,115,13,0,0,0,100,3,0,124,0,0,95,
-    0,0,100,2,0,83,41,4,122,31,73,110,118,97,108,105,
-    100,97,116,101,32,116,104,101,32,100,105,114,101,99,116,111,
-    114,121,32,109,116,105,109,101,46,114,29,0,0,0,78,114,
-    87,0,0,0,41,1,114,8,1,0,0,41,1,114,108,0,
-    0,0,114,4,0,0,0,114,4,0,0,0,114,5,0,0,
-    0,114,250,0,0,0,168,4,0,0,115,2,0,0,0,0,
-    2,122,28,70,105,108,101,70,105,110,100,101,114,46,105,110,
-    118,97,108,105,100,97,116,101,95,99,97,99,104,101,115,99,
-    2,0,0,0,0,0,0,0,3,0,0,0,2,0,0,0,
-    67,0,0,0,115,59,0,0,0,124,0,0,106,0,0,124,
-    1,0,131,1,0,125,2,0,124,2,0,100,1,0,107,8,
-    0,114,37,0,100,1,0,103,0,0,102,2,0,83,124,2,
-    0,106,1,0,124,2,0,106,2,0,112,55,0,103,0,0,
-    102,2,0,83,41,2,122,197,84,114,121,32,116,111,32,102,
-    105,110,100,32,97,32,108,111,97,100,101,114,32,102,111,114,
-    32,116,104,101,32,115,112,101,99,105,102,105,101,100,32,109,
-    111,100,117,108,101,44,32,111,114,32,116,104,101,32,110,97,
-    109,101,115,112,97,99,101,10,32,32,32,32,32,32,32,32,
-    112,97,99,107,97,103,101,32,112,111,114,116,105,111,110,115,
-    46,32,82,101,116,117,114,110,115,32,40,108,111,97,100,101,
-    114,44,32,108,105,115,116,45,111,102,45,112,111,114,116,105,
-    111,110,115,41,46,10,10,32,32,32,32,32,32,32,32,84,
-    104,105,115,32,109,101,116,104,111,100,32,105,115,32,100,101,
-    112,114,101,99,97,116,101,100,46,32,32,85,115,101,32,102,
-    105,110,100,95,115,112,101,99,40,41,32,105,110,115,116,101,
-    97,100,46,10,10,32,32,32,32,32,32,32,32,78,41,3,
-    114,181,0,0,0,114,127,0,0,0,114,156,0,0,0,41,
-    3,114,108,0,0,0,114,126,0,0,0,114,164,0,0,0,
-    114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,114,
-    124,0,0,0,174,4,0,0,115,8,0,0,0,0,7,15,
-    1,12,1,10,1,122,22,70,105,108,101,70,105,110,100,101,
-    114,46,102,105,110,100,95,108,111,97,100,101,114,99,6,0,
-    0,0,0,0,0,0,7,0,0,0,7,0,0,0,67,0,
-    0,0,115,40,0,0,0,124,1,0,124,2,0,124,3,0,
-    131,2,0,125,6,0,116,0,0,124,2,0,124,3,0,100,
-    1,0,124,6,0,100,2,0,124,4,0,131,2,2,83,41,
-    3,78,114,127,0,0,0,114,156,0,0,0,41,1,114,167,
-    0,0,0,41,7,114,108,0,0,0,114,165,0,0,0,114,
-    126,0,0,0,114,35,0,0,0,90,4,115,109,115,108,114,
-    180,0,0,0,114,127,0,0,0,114,4,0,0,0,114,4,
-    0,0,0,114,5,0,0,0,114,5,1,0,0,186,4,0,
-    0,115,6,0,0,0,0,1,15,1,18,1,122,20,70,105,
-    108,101,70,105,110,100,101,114,46,95,103,101,116,95,115,112,
-    101,99,78,99,3,0,0,0,0,0,0,0,14,0,0,0,
-    15,0,0,0,67,0,0,0,115,234,1,0,0,100,1,0,
-    125,3,0,124,1,0,106,0,0,100,2,0,131,1,0,100,
-    3,0,25,125,4,0,121,34,0,116,1,0,124,0,0,106,
-    2,0,112,49,0,116,3,0,106,4,0,131,0,0,131,1,
-    0,106,5,0,125,5,0,87,110,24,0,4,116,6,0,107,
-    10,0,114,85,0,1,1,1,100,10,0,125,5,0,89,110,
-    1,0,88,124,5,0,124,0,0,106,7,0,107,3,0,114,
-    120,0,124,0,0,106,8,0,131,0,0,1,124,5,0,124,
-    0,0,95,7,0,116,9,0,131,0,0,114,153,0,124,0,
-    0,106,10,0,125,6,0,124,4,0,106,11,0,131,0,0,
-    125,7,0,110,15,0,124,0,0,106,12,0,125,6,0,124,
-    4,0,125,7,0,124,7,0,124,6,0,107,6,0,114,45,
-    1,116,13,0,124,0,0,106,2,0,124,4,0,131,2,0,
-    125,8,0,120,100,0,124,0,0,106,14,0,68,93,77,0,
-    92,2,0,125,9,0,125,10,0,100,5,0,124,9,0,23,
-    125,11,0,116,13,0,124,8,0,124,11,0,131,2,0,125,
-    12,0,116,15,0,124,12,0,131,1,0,114,208,0,124,0,
-    0,106,16,0,124,10,0,124,1,0,124,12,0,124,8,0,
-    103,1,0,124,2,0,131,5,0,83,113,208,0,87,116,17,
-    0,124,8,0,131,1,0,125,3,0,120,123,0,124,0,0,
-    106,14,0,68,93,112,0,92,2,0,125,9,0,125,10,0,
-    116,13,0,124,0,0,106,2,0,124,4,0,124,9,0,23,
-    131,2,0,125,12,0,116,18,0,100,6,0,106,19,0,124,
-    12,0,131,1,0,100,7,0,100,3,0,131,1,1,1,124,
-    7,0,124,9,0,23,124,6,0,107,6,0,114,55,1,116,
-    15,0,124,12,0,131,1,0,114,55,1,124,0,0,106,16,
-    0,124,10,0,124,1,0,124,12,0,100,8,0,124,2,0,
-    131,5,0,83,113,55,1,87,124,3,0,114,230,1,116,18,
-    0,100,9,0,106,19,0,124,8,0,131,1,0,131,1,0,
-    1,116,20,0,106,21,0,124,1,0,100,8,0,131,2,0,
-    125,13,0,124,8,0,103,1,0,124,13,0,95,22,0,124,
-    13,0,83,100,8,0,83,41,11,122,102,84,114,121,32,116,
-    111,32,102,105,110,100,32,97,32,115,112,101,99,32,102,111,
-    114,32,116,104,101,32,115,112,101,99,105,102,105,101,100,32,
-    109,111,100,117,108,101,46,32,32,82,101,116,117,114,110,115,
-    32,116,104,101,10,32,32,32,32,32,32,32,32,109,97,116,
-    99,104,105,110,103,32,115,112,101,99,44,32,111,114,32,78,
-    111,110,101,32,105,102,32,110,111,116,32,102,111,117,110,100,
-    46,70,114,58,0,0,0,114,56,0,0,0,114,29,0,0,
-    0,114,185,0,0,0,122,9,116,114,121,105,110,103,32,123,
-    125,114,98,0,0,0,78,122,25,112,111,115,115,105,98,108,
-    101,32,110,97,109,101,115,112,97,99,101,32,102,111,114,32,
-    123,125,114,87,0,0,0,41,23,114,32,0,0,0,114,39,
-    0,0,0,114,35,0,0,0,114,3,0,0,0,114,45,0,
-    0,0,114,219,0,0,0,114,40,0,0,0,114,8,1,0,
-    0,218,11,95,102,105,108,108,95,99,97,99,104,101,114,6,
-    0,0,0,114,11,1,0,0,114,88,0,0,0,114,10,1,
-    0,0,114,28,0,0,0,114,7,1,0,0,114,44,0,0,
-    0,114,5,1,0,0,114,46,0,0,0,114,105,0,0,0,
-    114,47,0,0,0,114,121,0,0,0,114,160,0,0,0,114,
-    156,0,0,0,41,14,114,108,0,0,0,114,126,0,0,0,
-    114,180,0,0,0,90,12,105,115,95,110,97,109,101,115,112,
-    97,99,101,90,11,116,97,105,108,95,109,111,100,117,108,101,
-    114,133,0,0,0,90,5,99,97,99,104,101,90,12,99,97,
-    99,104,101,95,109,111,100,117,108,101,90,9,98,97,115,101,
-    95,112,97,116,104,114,225,0,0,0,114,165,0,0,0,90,
-    13,105,110,105,116,95,102,105,108,101,110,97,109,101,90,9,
-    102,117,108,108,95,112,97,116,104,114,164,0,0,0,114,4,
-    0,0,0,114,4,0,0,0,114,5,0,0,0,114,181,0,
-    0,0,191,4,0,0,115,68,0,0,0,0,3,6,1,19,
-    1,3,1,34,1,13,1,11,1,15,1,10,1,9,2,9,
-    1,9,1,15,2,9,1,6,2,12,1,18,1,22,1,10,
-    1,15,1,12,1,32,4,12,2,22,1,22,1,25,1,16,
-    1,12,1,29,1,6,1,19,1,18,1,12,1,4,1,122,
-    20,70,105,108,101,70,105,110,100,101,114,46,102,105,110,100,
-    95,115,112,101,99,99,1,0,0,0,0,0,0,0,9,0,
-    0,0,13,0,0,0,67,0,0,0,115,11,1,0,0,124,
-    0,0,106,0,0,125,1,0,121,31,0,116,1,0,106,2,
-    0,124,1,0,112,33,0,116,1,0,106,3,0,131,0,0,
-    131,1,0,125,2,0,87,110,33,0,4,116,4,0,116,5,
-    0,116,6,0,102,3,0,107,10,0,114,75,0,1,1,1,
-    103,0,0,125,2,0,89,110,1,0,88,116,7,0,106,8,
-    0,106,9,0,100,1,0,131,1,0,115,112,0,116,10,0,
-    124,2,0,131,1,0,124,0,0,95,11,0,110,111,0,116,
-    10,0,131,0,0,125,3,0,120,90,0,124,2,0,68,93,
-    82,0,125,4,0,124,4,0,106,12,0,100,2,0,131,1,
-    0,92,3,0,125,5,0,125,6,0,125,7,0,124,6,0,
-    114,191,0,100,3,0,106,13,0,124,5,0,124,7,0,106,
-    14,0,131,0,0,131,2,0,125,8,0,110,6,0,124,5,
-    0,125,8,0,124,3,0,106,15,0,124,8,0,131,1,0,
-    1,113,128,0,87,124,3,0,124,0,0,95,11,0,116,7,
-    0,106,8,0,106,9,0,116,16,0,131,1,0,114,7,1,
-    100,4,0,100,5,0,132,0,0,124,2,0,68,131,1,0,
-    124,0,0,95,17,0,100,6,0,83,41,7,122,68,70,105,
-    108,108,32,116,104,101,32,99,97,99,104,101,32,111,102,32,
-    112,111,116,101,110,116,105,97,108,32,109,111,100,117,108,101,
-    115,32,97,110,100,32,112,97,99,107,97,103,101,115,32,102,
-    111,114,32,116,104,105,115,32,100,105,114,101,99,116,111,114,
-    121,46,114,0,0,0,0,114,58,0,0,0,122,5,123,125,
-    46,123,125,99,1,0,0,0,0,0,0,0,2,0,0,0,
-    3,0,0,0,83,0,0,0,115,28,0,0,0,104,0,0,
-    124,0,0,93,18,0,125,1,0,124,1,0,106,0,0,131,
-    0,0,146,2,0,113,6,0,83,114,4,0,0,0,41,1,
-    114,88,0,0,0,41,2,114,22,0,0,0,90,2,102,110,
-    114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,250,
-    9,60,115,101,116,99,111,109,112,62,9,5,0,0,115,2,
-    0,0,0,9,0,122,41,70,105,108,101,70,105,110,100,101,
-    114,46,95,102,105,108,108,95,99,97,99,104,101,46,60,108,
-    111,99,97,108,115,62,46,60,115,101,116,99,111,109,112,62,
-    78,41,18,114,35,0,0,0,114,3,0,0,0,90,7,108,
-    105,115,116,100,105,114,114,45,0,0,0,114,0,1,0,0,
-    218,15,80,101,114,109,105,115,115,105,111,110,69,114,114,111,
-    114,218,18,78,111,116,65,68,105,114,101,99,116,111,114,121,
-    69,114,114,111,114,114,7,0,0,0,114,8,0,0,0,114,
-    9,0,0,0,114,9,1,0,0,114,10,1,0,0,114,83,
-    0,0,0,114,47,0,0,0,114,88,0,0,0,218,3,97,
-    100,100,114,10,0,0,0,114,11,1,0,0,41,9,114,108,
-    0,0,0,114,35,0,0,0,90,8,99,111,110,116,101,110,
-    116,115,90,21,108,111,119,101,114,95,115,117,102,102,105,120,
-    95,99,111,110,116,101,110,116,115,114,245,0,0,0,114,106,
-    0,0,0,114,237,0,0,0,114,225,0,0,0,90,8,110,
-    101,119,95,110,97,109,101,114,4,0,0,0,114,4,0,0,
-    0,114,5,0,0,0,114,13,1,0,0,236,4,0,0,115,
-    34,0,0,0,0,2,9,1,3,1,31,1,22,3,11,3,
-    18,1,18,7,9,1,13,1,24,1,6,1,27,2,6,1,
-    17,1,9,1,18,1,122,22,70,105,108,101,70,105,110,100,
-    101,114,46,95,102,105,108,108,95,99,97,99,104,101,99,1,
-    0,0,0,0,0,0,0,3,0,0,0,3,0,0,0,7,
-    0,0,0,115,25,0,0,0,135,0,0,135,1,0,102,2,
-    0,100,1,0,100,2,0,134,0,0,125,2,0,124,2,0,
-    83,41,3,97,20,1,0,0,65,32,99,108,97,115,115,32,
-    109,101,116,104,111,100,32,119,104,105,99,104,32,114,101,116,
-    117,114,110,115,32,97,32,99,108,111,115,117,114,101,32,116,
-    111,32,117,115,101,32,111,110,32,115,121,115,46,112,97,116,
-    104,95,104,111,111,107,10,32,32,32,32,32,32,32,32,119,
-    104,105,99,104,32,119,105,108,108,32,114,101,116,117,114,110,
-    32,97,110,32,105,110,115,116,97,110,99,101,32,117,115,105,
-    110,103,32,116,104,101,32,115,112,101,99,105,102,105,101,100,
-    32,108,111,97,100,101,114,115,32,97,110,100,32,116,104,101,
-    32,112,97,116,104,10,32,32,32,32,32,32,32,32,99,97,
-    108,108,101,100,32,111,110,32,116,104,101,32,99,108,111,115,
-    117,114,101,46,10,10,32,32,32,32,32,32,32,32,73,102,
-    32,116,104,101,32,112,97,116,104,32,99,97,108,108,101,100,
-    32,111,110,32,116,104,101,32,99,108,111,115,117,114,101,32,
-    105,115,32,110,111,116,32,97,32,100,105,114,101,99,116,111,
-    114,121,44,32,73,109,112,111,114,116,69,114,114,111,114,32,
-    105,115,10,32,32,32,32,32,32,32,32,114,97,105,115,101,
-    100,46,10,10,32,32,32,32,32,32,32,32,99,1,0,0,
-    0,0,0,0,0,1,0,0,0,4,0,0,0,19,0,0,
-    0,115,43,0,0,0,116,0,0,124,0,0,131,1,0,115,
-    30,0,116,1,0,100,1,0,100,2,0,124,0,0,131,1,
-    1,130,1,0,136,0,0,124,0,0,136,1,0,140,1,0,
-    83,41,3,122,45,80,97,116,104,32,104,111,111,107,32,102,
-    111,114,32,105,109,112,111,114,116,108,105,98,46,109,97,99,
-    104,105,110,101,114,121,46,70,105,108,101,70,105,110,100,101,
-    114,46,122,30,111,110,108,121,32,100,105,114,101,99,116,111,
-    114,105,101,115,32,97,114,101,32,115,117,112,112,111,114,116,
-    101,100,114,35,0,0,0,41,2,114,46,0,0,0,114,107,
-    0,0,0,41,1,114,35,0,0,0,41,2,114,170,0,0,
-    0,114,12,1,0,0,114,4,0,0,0,114,5,0,0,0,
-    218,24,112,97,116,104,95,104,111,111,107,95,102,111,114,95,
-    70,105,108,101,70,105,110,100,101,114,21,5,0,0,115,6,
-    0,0,0,0,2,12,1,18,1,122,54,70,105,108,101,70,
-    105,110,100,101,114,46,112,97,116,104,95,104,111,111,107,46,
-    60,108,111,99,97,108,115,62,46,112,97,116,104,95,104,111,
-    111,107,95,102,111,114,95,70,105,108,101,70,105,110,100,101,
-    114,114,4,0,0,0,41,3,114,170,0,0,0,114,12,1,
-    0,0,114,18,1,0,0,114,4,0,0,0,41,2,114,170,
-    0,0,0,114,12,1,0,0,114,5,0,0,0,218,9,112,
-    97,116,104,95,104,111,111,107,11,5,0,0,115,4,0,0,
-    0,0,10,21,6,122,20,70,105,108,101,70,105,110,100,101,
-    114,46,112,97,116,104,95,104,111,111,107,99,1,0,0,0,
-    0,0,0,0,1,0,0,0,2,0,0,0,67,0,0,0,
-    115,16,0,0,0,100,1,0,106,0,0,124,0,0,106,1,
-    0,131,1,0,83,41,2,78,122,16,70,105,108,101,70,105,
-    110,100,101,114,40,123,33,114,125,41,41,2,114,47,0,0,
-    0,114,35,0,0,0,41,1,114,108,0,0,0,114,4,0,
-    0,0,114,4,0,0,0,114,5,0,0,0,114,244,0,0,
-    0,29,5,0,0,115,2,0,0,0,0,1,122,19,70,105,
-    108,101,70,105,110,100,101,114,46,95,95,114,101,112,114,95,
-    95,41,15,114,112,0,0,0,114,111,0,0,0,114,113,0,
-    0,0,114,114,0,0,0,114,185,0,0,0,114,250,0,0,
-    0,114,130,0,0,0,114,182,0,0,0,114,124,0,0,0,
-    114,5,1,0,0,114,181,0,0,0,114,13,1,0,0,114,
-    183,0,0,0,114,19,1,0,0,114,244,0,0,0,114,4,
-    0,0,0,114,4,0,0,0,114,4,0,0,0,114,5,0,
-    0,0,114,6,1,0,0,145,4,0,0,115,20,0,0,0,
-    12,7,6,2,12,14,12,4,6,2,12,12,12,5,15,45,
-    12,31,18,18,114,6,1,0,0,99,4,0,0,0,0,0,
-    0,0,6,0,0,0,11,0,0,0,67,0,0,0,115,195,
-    0,0,0,124,0,0,106,0,0,100,1,0,131,1,0,125,
-    4,0,124,0,0,106,0,0,100,2,0,131,1,0,125,5,
-    0,124,4,0,115,99,0,124,5,0,114,54,0,124,5,0,
-    106,1,0,125,4,0,110,45,0,124,2,0,124,3,0,107,
-    2,0,114,84,0,116,2,0,124,1,0,124,2,0,131,2,
-    0,125,4,0,110,15,0,116,3,0,124,1,0,124,2,0,
-    131,2,0,125,4,0,124,5,0,115,126,0,116,4,0,124,
-    1,0,124,2,0,100,3,0,124,4,0,131,2,1,125,5,
-    0,121,44,0,124,5,0,124,0,0,100,2,0,60,124,4,
-    0,124,0,0,100,1,0,60,124,2,0,124,0,0,100,4,
-    0,60,124,3,0,124,0,0,100,5,0,60,87,110,18,0,
-    4,116,5,0,107,10,0,114,190,0,1,1,1,89,110,1,
-    0,88,100,0,0,83,41,6,78,218,10,95,95,108,111,97,
-    100,101,114,95,95,218,8,95,95,115,112,101,99,95,95,114,
-    127,0,0,0,90,8,95,95,102,105,108,101,95,95,90,10,
-    95,95,99,97,99,104,101,100,95,95,41,6,218,3,103,101,
-    116,114,127,0,0,0,114,223,0,0,0,114,218,0,0,0,
-    114,167,0,0,0,218,9,69,120,99,101,112,116,105,111,110,
-    41,6,90,2,110,115,114,106,0,0,0,90,8,112,97,116,
-    104,110,97,109,101,90,9,99,112,97,116,104,110,97,109,101,
-    114,127,0,0,0,114,164,0,0,0,114,4,0,0,0,114,
-    4,0,0,0,114,5,0,0,0,218,14,95,102,105,120,95,
-    117,112,95,109,111,100,117,108,101,35,5,0,0,115,34,0,
-    0,0,0,2,15,1,15,1,6,1,6,1,12,1,12,1,
-    18,2,15,1,6,1,21,1,3,1,10,1,10,1,10,1,
-    14,1,13,2,114,24,1,0,0,99,0,0,0,0,0,0,
-    0,0,3,0,0,0,3,0,0,0,67,0,0,0,115,55,
-    0,0,0,116,0,0,116,1,0,106,2,0,131,0,0,102,
-    2,0,125,0,0,116,3,0,116,4,0,102,2,0,125,1,
-    0,116,5,0,116,6,0,102,2,0,125,2,0,124,0,0,
-    124,1,0,124,2,0,103,3,0,83,41,1,122,95,82,101,
-    116,117,114,110,115,32,97,32,108,105,115,116,32,111,102,32,
-    102,105,108,101,45,98,97,115,101,100,32,109,111,100,117,108,
-    101,32,108,111,97,100,101,114,115,46,10,10,32,32,32,32,
-    69,97,99,104,32,105,116,101,109,32,105,115,32,97,32,116,
-    117,112,108,101,32,40,108,111,97,100,101,114,44,32,115,117,
-    102,102,105,120,101,115,41,46,10,32,32,32,32,41,7,114,
-    224,0,0,0,114,145,0,0,0,218,18,101,120,116,101,110,
-    115,105,111,110,95,115,117,102,102,105,120,101,115,114,218,0,
-    0,0,114,84,0,0,0,114,223,0,0,0,114,74,0,0,
-    0,41,3,90,10,101,120,116,101,110,115,105,111,110,115,90,
-    6,115,111,117,114,99,101,90,8,98,121,116,101,99,111,100,
-    101,114,4,0,0,0,114,4,0,0,0,114,5,0,0,0,
-    114,161,0,0,0,58,5,0,0,115,8,0,0,0,0,5,
-    18,1,12,1,12,1,114,161,0,0,0,99,1,0,0,0,
-    0,0,0,0,12,0,0,0,12,0,0,0,67,0,0,0,
-    115,70,2,0,0,124,0,0,97,0,0,116,0,0,106,1,
-    0,97,1,0,116,0,0,106,2,0,97,2,0,116,1,0,
-    106,3,0,116,4,0,25,125,1,0,120,76,0,100,26,0,
-    68,93,68,0,125,2,0,124,2,0,116,1,0,106,3,0,
-    107,7,0,114,83,0,116,0,0,106,5,0,124,2,0,131,
-    1,0,125,3,0,110,13,0,116,1,0,106,3,0,124,2,
-    0,25,125,3,0,116,6,0,124,1,0,124,2,0,124,3,
-    0,131,3,0,1,113,44,0,87,100,5,0,100,6,0,103,
-    1,0,102,2,0,100,7,0,100,8,0,100,6,0,103,2,
-    0,102,2,0,102,2,0,125,4,0,120,149,0,124,4,0,
-    68,93,129,0,92,2,0,125,5,0,125,6,0,116,7,0,
-    100,9,0,100,10,0,132,0,0,124,6,0,68,131,1,0,
-    131,1,0,115,199,0,116,8,0,130,1,0,124,6,0,100,
-    11,0,25,125,7,0,124,5,0,116,1,0,106,3,0,107,
-    6,0,114,241,0,116,1,0,106,3,0,124,5,0,25,125,
-    8,0,80,113,156,0,121,20,0,116,0,0,106,5,0,124,
-    5,0,131,1,0,125,8,0,80,87,113,156,0,4,116,9,
-    0,107,10,0,114,28,1,1,1,1,119,156,0,89,113,156,
-    0,88,113,156,0,87,116,9,0,100,12,0,131,1,0,130,
-    1,0,116,6,0,124,1,0,100,13,0,124,8,0,131,3,
-    0,1,116,6,0,124,1,0,100,14,0,124,7,0,131,3,
-    0,1,116,6,0,124,1,0,100,15,0,100,16,0,106,10,
-    0,124,6,0,131,1,0,131,3,0,1,121,19,0,116,0,
-    0,106,5,0,100,17,0,131,1,0,125,9,0,87,110,24,
-    0,4,116,9,0,107,10,0,114,147,1,1,1,1,100,18,
-    0,125,9,0,89,110,1,0,88,116,6,0,124,1,0,100,
-    17,0,124,9,0,131,3,0,1,116,0,0,106,5,0,100,
-    19,0,131,1,0,125,10,0,116,6,0,124,1,0,100,19,
-    0,124,10,0,131,3,0,1,124,5,0,100,7,0,107,2,
-    0,114,238,1,116,0,0,106,5,0,100,20,0,131,1,0,
-    125,11,0,116,6,0,124,1,0,100,21,0,124,11,0,131,
-    3,0,1,116,6,0,124,1,0,100,22,0,116,11,0,131,
-    0,0,131,3,0,1,116,12,0,106,13,0,116,2,0,106,
-    14,0,131,0,0,131,1,0,1,124,5,0,100,7,0,107,
-    2,0,114,66,2,116,15,0,106,16,0,100,23,0,131,1,
-    0,1,100,24,0,116,12,0,107,6,0,114,66,2,100,25,
-    0,116,17,0,95,18,0,100,18,0,83,41,27,122,205,83,
-    101,116,117,112,32,116,104,101,32,112,97,116,104,45,98,97,
-    115,101,100,32,105,109,112,111,114,116,101,114,115,32,102,111,
-    114,32,105,109,112,111,114,116,108,105,98,32,98,121,32,105,
-    109,112,111,114,116,105,110,103,32,110,101,101,100,101,100,10,
-    32,32,32,32,98,117,105,108,116,45,105,110,32,109,111,100,
-    117,108,101,115,32,97,110,100,32,105,110,106,101,99,116,105,
-    110,103,32,116,104,101,109,32,105,110,116,111,32,116,104,101,
-    32,103,108,111,98,97,108,32,110,97,109,101,115,112,97,99,
-    101,46,10,10,32,32,32,32,79,116,104,101,114,32,99,111,
-    109,112,111,110,101,110,116,115,32,97,114,101,32,101,120,116,
-    114,97,99,116,101,100,32,102,114,111,109,32,116,104,101,32,
-    99,111,114,101,32,98,111,111,116,115,116,114,97,112,32,109,
-    111,100,117,108,101,46,10,10,32,32,32,32,114,49,0,0,
-    0,114,60,0,0,0,218,8,98,117,105,108,116,105,110,115,
-    114,142,0,0,0,90,5,112,111,115,105,120,250,1,47,218,
-    2,110,116,250,1,92,99,1,0,0,0,0,0,0,0,2,
-    0,0,0,3,0,0,0,115,0,0,0,115,33,0,0,0,
-    124,0,0,93,23,0,125,1,0,116,0,0,124,1,0,131,
-    1,0,100,0,0,107,2,0,86,1,113,3,0,100,1,0,
-    83,41,2,114,29,0,0,0,78,41,1,114,31,0,0,0,
-    41,2,114,22,0,0,0,114,77,0,0,0,114,4,0,0,
-    0,114,4,0,0,0,114,5,0,0,0,114,227,0,0,0,
-    94,5,0,0,115,2,0,0,0,6,0,122,25,95,115,101,
-    116,117,112,46,60,108,111,99,97,108,115,62,46,60,103,101,
-    110,101,120,112,114,62,114,59,0,0,0,122,30,105,109,112,
-    111,114,116,108,105,98,32,114,101,113,117,105,114,101,115,32,
-    112,111,115,105,120,32,111,114,32,110,116,114,3,0,0,0,
-    114,25,0,0,0,114,21,0,0,0,114,30,0,0,0,90,
-    7,95,116,104,114,101,97,100,78,90,8,95,119,101,97,107,
-    114,101,102,90,6,119,105,110,114,101,103,114,169,0,0,0,
-    114,6,0,0,0,122,4,46,112,121,119,122,6,95,100,46,
-    112,121,100,84,41,4,122,3,95,105,111,122,9,95,119,97,
-    114,110,105,110,103,115,122,8,98,117,105,108,116,105,110,115,
-    122,7,109,97,114,115,104,97,108,41,19,114,121,0,0,0,
-    114,7,0,0,0,114,145,0,0,0,114,239,0,0,0,114,
-    112,0,0,0,90,18,95,98,117,105,108,116,105,110,95,102,
-    114,111,109,95,110,97,109,101,114,116,0,0,0,218,3,97,
-    108,108,218,14,65,115,115,101,114,116,105,111,110,69,114,114,
-    111,114,114,107,0,0,0,114,26,0,0,0,114,11,0,0,
-    0,114,229,0,0,0,114,149,0,0,0,114,25,1,0,0,
-    114,84,0,0,0,114,163,0,0,0,114,168,0,0,0,114,
-    173,0,0,0,41,12,218,17,95,98,111,111,116,115,116,114,
-    97,112,95,109,111,100,117,108,101,90,11,115,101,108,102,95,
-    109,111,100,117,108,101,90,12,98,117,105,108,116,105,110,95,
-    110,97,109,101,90,14,98,117,105,108,116,105,110,95,109,111,
-    100,117,108,101,90,10,111,115,95,100,101,116,97,105,108,115,
-    90,10,98,117,105,108,116,105,110,95,111,115,114,21,0,0,
-    0,114,25,0,0,0,90,9,111,115,95,109,111,100,117,108,
-    101,90,13,116,104,114,101,97,100,95,109,111,100,117,108,101,
-    90,14,119,101,97,107,114,101,102,95,109,111,100,117,108,101,
-    90,13,119,105,110,114,101,103,95,109,111,100,117,108,101,114,
-    4,0,0,0,114,4,0,0,0,114,5,0,0,0,218,6,
-    95,115,101,116,117,112,69,5,0,0,115,82,0,0,0,0,
-    8,6,1,9,1,9,3,13,1,13,1,15,1,18,2,13,
-    1,20,3,33,1,19,2,31,1,10,1,15,1,13,1,4,
-    2,3,1,15,1,5,1,13,1,12,2,12,1,16,1,16,
-    1,25,3,3,1,19,1,13,2,11,1,16,3,15,1,16,
-    3,12,1,15,1,16,3,19,1,19,1,12,1,13,1,12,
-    1,114,33,1,0,0,99,1,0,0,0,0,0,0,0,2,
-    0,0,0,3,0,0,0,67,0,0,0,115,116,0,0,0,
-    116,0,0,124,0,0,131,1,0,1,116,1,0,131,0,0,
-    125,1,0,116,2,0,106,3,0,106,4,0,116,5,0,106,
-    6,0,124,1,0,140,0,0,103,1,0,131,1,0,1,116,
-    7,0,106,8,0,100,1,0,107,2,0,114,78,0,116,2,
-    0,106,9,0,106,10,0,116,11,0,131,1,0,1,116,2,
-    0,106,9,0,106,10,0,116,12,0,131,1,0,1,116,5,
-    0,124,0,0,95,5,0,116,13,0,124,0,0,95,13,0,
-    100,2,0,83,41,3,122,41,73,110,115,116,97,108,108,32,
-    116,104,101,32,112,97,116,104,45,98,97,115,101,100,32,105,
-    109,112,111,114,116,32,99,111,109,112,111,110,101,110,116,115,
-    46,114,28,1,0,0,78,41,14,114,33,1,0,0,114,161,
-    0,0,0,114,7,0,0,0,114,254,0,0,0,114,149,0,
-    0,0,114,6,1,0,0,114,19,1,0,0,114,3,0,0,
-    0,114,112,0,0,0,218,9,109,101,116,97,95,112,97,116,
-    104,114,163,0,0,0,114,168,0,0,0,114,249,0,0,0,
-    114,218,0,0,0,41,2,114,32,1,0,0,90,17,115,117,
-    112,112,111,114,116,101,100,95,108,111,97,100,101,114,115,114,
-    4,0,0,0,114,4,0,0,0,114,5,0,0,0,218,8,
-    95,105,110,115,116,97,108,108,137,5,0,0,115,16,0,0,
-    0,0,2,10,1,9,1,28,1,15,1,16,1,16,4,9,
-    1,114,35,1,0,0,41,3,122,3,119,105,110,114,1,0,
-    0,0,114,2,0,0,0,41,57,114,114,0,0,0,114,10,
-    0,0,0,114,11,0,0,0,114,17,0,0,0,114,19,0,
-    0,0,114,28,0,0,0,114,38,0,0,0,114,39,0,0,
-    0,114,43,0,0,0,114,44,0,0,0,114,46,0,0,0,
-    114,55,0,0,0,218,4,116,121,112,101,218,8,95,95,99,
-    111,100,101,95,95,114,144,0,0,0,114,15,0,0,0,114,
-    135,0,0,0,114,14,0,0,0,114,18,0,0,0,90,17,
-    95,82,65,87,95,77,65,71,73,67,95,78,85,77,66,69,
-    82,114,73,0,0,0,114,72,0,0,0,114,84,0,0,0,
-    114,74,0,0,0,90,23,68,69,66,85,71,95,66,89,84,
-    69,67,79,68,69,95,83,85,70,70,73,88,69,83,90,27,
-    79,80,84,73,77,73,90,69,68,95,66,89,84,69,67,79,
-    68,69,95,83,85,70,70,73,88,69,83,114,79,0,0,0,
-    114,85,0,0,0,114,91,0,0,0,114,95,0,0,0,114,
-    97,0,0,0,114,105,0,0,0,114,123,0,0,0,114,130,
-    0,0,0,114,141,0,0,0,114,147,0,0,0,114,150,0,
-    0,0,114,155,0,0,0,218,6,111,98,106,101,99,116,114,
-    162,0,0,0,114,167,0,0,0,114,168,0,0,0,114,184,
-    0,0,0,114,194,0,0,0,114,210,0,0,0,114,218,0,
-    0,0,114,223,0,0,0,114,229,0,0,0,114,224,0,0,
-    0,114,230,0,0,0,114,247,0,0,0,114,249,0,0,0,
-    114,6,1,0,0,114,24,1,0,0,114,161,0,0,0,114,
-    33,1,0,0,114,35,1,0,0,114,4,0,0,0,114,4,
-    0,0,0,114,4,0,0,0,114,5,0,0,0,218,8,60,
-    109,111,100,117,108,101,62,8,0,0,0,115,100,0,0,0,
-    6,17,6,3,12,12,12,5,12,5,12,6,12,12,12,10,
-    12,9,12,5,12,7,15,22,15,113,22,1,18,2,6,1,
-    6,2,9,2,9,2,10,2,21,44,12,33,12,19,12,12,
-    12,12,18,8,12,28,12,17,21,55,21,12,18,10,12,14,
-    9,3,12,1,15,65,19,64,19,28,22,110,19,41,25,43,
-    25,16,6,3,25,53,19,57,19,41,19,134,19,146,15,23,
-    12,11,12,68,
+    97,99,104,101,115,32,40,119,104,101,114,101,32,105,109,112,
+    108,101,109,101,110,116,101,100,41,46,218,17,105,110,118,97,
+    108,105,100,97,116,101,95,99,97,99,104,101,115,78,41,5,
+    114,8,0,0,0,218,19,112,97,116,104,95,105,109,112,111,
+    114,116,101,114,95,99,97,99,104,101,218,6,118,97,108,117,
+    101,115,114,117,0,0,0,114,251,0,0,0,41,2,114,172,
+    0,0,0,218,6,102,105,110,100,101,114,114,4,0,0,0,
+    114,4,0,0,0,114,6,0,0,0,114,251,0,0,0,23,
+    4,0,0,115,6,0,0,0,0,4,22,1,15,1,122,28,
+    80,97,116,104,70,105,110,100,101,114,46,105,110,118,97,108,
+    105,100,97,116,101,95,99,97,99,104,101,115,99,2,0,0,
+    0,0,0,0,0,3,0,0,0,12,0,0,0,67,0,0,
+    0,115,107,0,0,0,116,0,0,106,1,0,100,1,0,107,
+    9,0,114,41,0,116,0,0,106,1,0,12,114,41,0,116,
+    2,0,106,3,0,100,2,0,116,4,0,131,2,0,1,120,
+    59,0,116,0,0,106,1,0,68,93,44,0,125,2,0,121,
+    14,0,124,2,0,124,1,0,131,1,0,83,87,113,51,0,
+    4,116,5,0,107,10,0,114,94,0,1,1,1,119,51,0,
+    89,113,51,0,88,113,51,0,87,100,1,0,83,100,1,0,
+    83,41,3,122,113,83,101,97,114,99,104,32,115,101,113,117,
+    101,110,99,101,32,111,102,32,104,111,111,107,115,32,102,111,
+    114,32,97,32,102,105,110,100,101,114,32,102,111,114,32,39,
+    112,97,116,104,39,46,10,10,32,32,32,32,32,32,32,32,
+    73,102,32,39,104,111,111,107,115,39,32,105,115,32,102,97,
+    108,115,101,32,116,104,101,110,32,117,115,101,32,115,121,115,
+    46,112,97,116,104,95,104,111,111,107,115,46,10,10,32,32,
+    32,32,32,32,32,32,78,122,23,115,121,115,46,112,97,116,
+    104,95,104,111,111,107,115,32,105,115,32,101,109,112,116,121,
+    41,6,114,8,0,0,0,218,10,112,97,116,104,95,104,111,
+    111,107,115,114,62,0,0,0,114,63,0,0,0,114,127,0,
+    0,0,114,109,0,0,0,41,3,114,172,0,0,0,114,37,
+    0,0,0,90,4,104,111,111,107,114,4,0,0,0,114,4,
+    0,0,0,114,6,0,0,0,218,11,95,112,97,116,104,95,
+    104,111,111,107,115,31,4,0,0,115,16,0,0,0,0,7,
+    25,1,16,1,16,1,3,1,14,1,13,1,12,2,122,22,
+    80,97,116,104,70,105,110,100,101,114,46,95,112,97,116,104,
+    95,104,111,111,107,115,99,2,0,0,0,0,0,0,0,3,
+    0,0,0,19,0,0,0,67,0,0,0,115,123,0,0,0,
+    124,1,0,100,1,0,107,2,0,114,53,0,121,16,0,116,
+    0,0,106,1,0,131,0,0,125,1,0,87,110,22,0,4,
+    116,2,0,107,10,0,114,52,0,1,1,1,100,2,0,83,
+    89,110,1,0,88,121,17,0,116,3,0,106,4,0,124,1,
+    0,25,125,2,0,87,110,46,0,4,116,5,0,107,10,0,
+    114,118,0,1,1,1,124,0,0,106,6,0,124,1,0,131,
+    1,0,125,2,0,124,2,0,116,3,0,106,4,0,124,1,
+    0,60,89,110,1,0,88,124,2,0,83,41,3,122,210,71,
+    101,116,32,116,104,101,32,102,105,110,100,101,114,32,102,111,
+    114,32,116,104,101,32,112,97,116,104,32,101,110,116,114,121,
+    32,102,114,111,109,32,115,121,115,46,112,97,116,104,95,105,
+    109,112,111,114,116,101,114,95,99,97,99,104,101,46,10,10,
+    32,32,32,32,32,32,32,32,73,102,32,116,104,101,32,112,
+    97,116,104,32,101,110,116,114,121,32,105,115,32,110,111,116,
+    32,105,110,32,116,104,101,32,99,97,99,104,101,44,32,102,
+    105,110,100,32,116,104,101,32,97,112,112,114,111,112,114,105,
+    97,116,101,32,102,105,110,100,101,114,10,32,32,32,32,32,
+    32,32,32,97,110,100,32,99,97,99,104,101,32,105,116,46,
+    32,73,102,32,110,111,32,102,105,110,100,101,114,32,105,115,
+    32,97,118,97,105,108,97,98,108,101,44,32,115,116,111,114,
+    101,32,78,111,110,101,46,10,10,32,32,32,32,32,32,32,
+    32,114,32,0,0,0,78,41,7,114,3,0,0,0,114,47,
+    0,0,0,218,17,70,105,108,101,78,111,116,70,111,117,110,
+    100,69,114,114,111,114,114,8,0,0,0,114,252,0,0,0,
+    114,139,0,0,0,114,0,1,0,0,41,3,114,172,0,0,
+    0,114,37,0,0,0,114,254,0,0,0,114,4,0,0,0,
+    114,4,0,0,0,114,6,0,0,0,218,20,95,112,97,116,
+    104,95,105,109,112,111,114,116,101,114,95,99,97,99,104,101,
+    48,4,0,0,115,22,0,0,0,0,8,12,1,3,1,16,
+    1,13,3,9,1,3,1,17,1,13,1,15,1,18,1,122,
+    31,80,97,116,104,70,105,110,100,101,114,46,95,112,97,116,
+    104,95,105,109,112,111,114,116,101,114,95,99,97,99,104,101,
+    99,3,0,0,0,0,0,0,0,6,0,0,0,3,0,0,
+    0,67,0,0,0,115,119,0,0,0,116,0,0,124,2,0,
+    100,1,0,131,2,0,114,39,0,124,2,0,106,1,0,124,
+    1,0,131,1,0,92,2,0,125,3,0,125,4,0,110,21,
+    0,124,2,0,106,2,0,124,1,0,131,1,0,125,3,0,
+    103,0,0,125,4,0,124,3,0,100,0,0,107,9,0,114,
+    88,0,116,3,0,106,4,0,124,1,0,124,3,0,131,2,
+    0,83,116,3,0,106,5,0,124,1,0,100,0,0,131,2,
+    0,125,5,0,124,4,0,124,5,0,95,6,0,124,5,0,
+    83,41,2,78,114,126,0,0,0,41,7,114,117,0,0,0,
+    114,126,0,0,0,114,183,0,0,0,114,123,0,0,0,114,
+    180,0,0,0,114,162,0,0,0,114,158,0,0,0,41,6,
+    114,172,0,0,0,114,128,0,0,0,114,254,0,0,0,114,
+    129,0,0,0,114,130,0,0,0,114,166,0,0,0,114,4,
+    0,0,0,114,4,0,0,0,114,6,0,0,0,218,16,95,
+    108,101,103,97,99,121,95,103,101,116,95,115,112,101,99,70,
+    4,0,0,115,18,0,0,0,0,4,15,1,24,2,15,1,
+    6,1,12,1,16,1,18,1,9,1,122,27,80,97,116,104,
+    70,105,110,100,101,114,46,95,108,101,103,97,99,121,95,103,
+    101,116,95,115,112,101,99,78,99,4,0,0,0,0,0,0,
+    0,9,0,0,0,5,0,0,0,67,0,0,0,115,243,0,
+    0,0,103,0,0,125,4,0,120,230,0,124,2,0,68,93,
+    191,0,125,5,0,116,0,0,124,5,0,116,1,0,116,2,
+    0,102,2,0,131,2,0,115,43,0,113,13,0,124,0,0,
+    106,3,0,124,5,0,131,1,0,125,6,0,124,6,0,100,
+    1,0,107,9,0,114,13,0,116,4,0,124,6,0,100,2,
+    0,131,2,0,114,106,0,124,6,0,106,5,0,124,1,0,
+    124,3,0,131,2,0,125,7,0,110,18,0,124,0,0,106,
+    6,0,124,1,0,124,6,0,131,2,0,125,7,0,124,7,
+    0,100,1,0,107,8,0,114,139,0,113,13,0,124,7,0,
+    106,7,0,100,1,0,107,9,0,114,158,0,124,7,0,83,
+    124,7,0,106,8,0,125,8,0,124,8,0,100,1,0,107,
+    8,0,114,191,0,116,9,0,100,3,0,131,1,0,130,1,
+    0,124,4,0,106,10,0,124,8,0,131,1,0,1,113,13,
+    0,87,116,11,0,106,12,0,124,1,0,100,1,0,131,2,
+    0,125,7,0,124,4,0,124,7,0,95,8,0,124,7,0,
+    83,100,1,0,83,41,4,122,63,70,105,110,100,32,116,104,
+    101,32,108,111,97,100,101,114,32,111,114,32,110,97,109,101,
+    115,112,97,99,101,95,112,97,116,104,32,102,111,114,32,116,
+    104,105,115,32,109,111,100,117,108,101,47,112,97,99,107,97,
+    103,101,32,110,97,109,101,46,78,114,182,0,0,0,122,19,
+    115,112,101,99,32,109,105,115,115,105,110,103,32,108,111,97,
+    100,101,114,41,13,114,145,0,0,0,114,71,0,0,0,218,
+    5,98,121,116,101,115,114,2,1,0,0,114,117,0,0,0,
+    114,182,0,0,0,114,3,1,0,0,114,129,0,0,0,114,
+    158,0,0,0,114,109,0,0,0,114,151,0,0,0,114,123,
+    0,0,0,114,162,0,0,0,41,9,114,172,0,0,0,114,
+    128,0,0,0,114,37,0,0,0,114,181,0,0,0,218,14,
+    110,97,109,101,115,112,97,99,101,95,112,97,116,104,90,5,
+    101,110,116,114,121,114,254,0,0,0,114,166,0,0,0,114,
+    130,0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,
+    0,0,0,218,9,95,103,101,116,95,115,112,101,99,85,4,
+    0,0,115,40,0,0,0,0,5,6,1,13,1,21,1,3,
+    1,15,1,12,1,15,1,21,2,18,1,12,1,3,1,15,
+    1,4,1,9,1,12,1,12,5,17,2,18,1,9,1,122,
+    20,80,97,116,104,70,105,110,100,101,114,46,95,103,101,116,
+    95,115,112,101,99,99,4,0,0,0,0,0,0,0,6,0,
+    0,0,4,0,0,0,67,0,0,0,115,140,0,0,0,124,
+    2,0,100,1,0,107,8,0,114,21,0,116,0,0,106,1,
+    0,125,2,0,124,0,0,106,2,0,124,1,0,124,2,0,
+    124,3,0,131,3,0,125,4,0,124,4,0,100,1,0,107,
+    8,0,114,58,0,100,1,0,83,124,4,0,106,3,0,100,
+    1,0,107,8,0,114,132,0,124,4,0,106,4,0,125,5,
+    0,124,5,0,114,125,0,100,2,0,124,4,0,95,5,0,
+    116,6,0,124,1,0,124,5,0,124,0,0,106,2,0,131,
+    3,0,124,4,0,95,4,0,124,4,0,83,100,1,0,83,
+    110,4,0,124,4,0,83,100,1,0,83,41,3,122,98,102,
+    105,110,100,32,116,104,101,32,109,111,100,117,108,101,32,111,
+    110,32,115,121,115,46,112,97,116,104,32,111,114,32,39,112,
+    97,116,104,39,32,98,97,115,101,100,32,111,110,32,115,121,
+    115,46,112,97,116,104,95,104,111,111,107,115,32,97,110,100,
+    10,32,32,32,32,32,32,32,32,115,121,115,46,112,97,116,
+    104,95,105,109,112,111,114,116,101,114,95,99,97,99,104,101,
+    46,78,90,9,110,97,109,101,115,112,97,99,101,41,7,114,
+    8,0,0,0,114,37,0,0,0,114,6,1,0,0,114,129,
+    0,0,0,114,158,0,0,0,114,160,0,0,0,114,231,0,
+    0,0,41,6,114,172,0,0,0,114,128,0,0,0,114,37,
+    0,0,0,114,181,0,0,0,114,166,0,0,0,114,5,1,
+    0,0,114,4,0,0,0,114,4,0,0,0,114,6,0,0,
+    0,114,182,0,0,0,117,4,0,0,115,26,0,0,0,0,
+    4,12,1,9,1,21,1,12,1,4,1,15,1,9,1,6,
+    3,9,1,24,1,4,2,7,2,122,20,80,97,116,104,70,
+    105,110,100,101,114,46,102,105,110,100,95,115,112,101,99,99,
+    3,0,0,0,0,0,0,0,4,0,0,0,3,0,0,0,
+    67,0,0,0,115,41,0,0,0,124,0,0,106,0,0,124,
+    1,0,124,2,0,131,2,0,125,3,0,124,3,0,100,1,
+    0,107,8,0,114,34,0,100,1,0,83,124,3,0,106,1,
+    0,83,41,2,122,170,102,105,110,100,32,116,104,101,32,109,
+    111,100,117,108,101,32,111,110,32,115,121,115,46,112,97,116,
+    104,32,111,114,32,39,112,97,116,104,39,32,98,97,115,101,
+    100,32,111,110,32,115,121,115,46,112,97,116,104,95,104,111,
+    111,107,115,32,97,110,100,10,32,32,32,32,32,32,32,32,
+    115,121,115,46,112,97,116,104,95,105,109,112,111,114,116,101,
+    114,95,99,97,99,104,101,46,10,10,32,32,32,32,32,32,
+    32,32,84,104,105,115,32,109,101,116,104,111,100,32,105,115,
+    32,100,101,112,114,101,99,97,116,101,100,46,32,32,85,115,
+    101,32,102,105,110,100,95,115,112,101,99,40,41,32,105,110,
+    115,116,101,97,100,46,10,10,32,32,32,32,32,32,32,32,
+    78,41,2,114,182,0,0,0,114,129,0,0,0,41,4,114,
+    172,0,0,0,114,128,0,0,0,114,37,0,0,0,114,166,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,114,183,0,0,0,139,4,0,0,115,8,0,0,0,
+    0,8,18,1,12,1,4,1,122,22,80,97,116,104,70,105,
+    110,100,101,114,46,102,105,110,100,95,109,111,100,117,108,101,
+    41,12,114,114,0,0,0,114,113,0,0,0,114,115,0,0,
+    0,114,116,0,0,0,114,184,0,0,0,114,251,0,0,0,
+    114,0,1,0,0,114,2,1,0,0,114,3,1,0,0,114,
+    6,1,0,0,114,182,0,0,0,114,183,0,0,0,114,4,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,114,250,0,0,0,19,4,0,0,115,22,0,0,0,
+    12,2,6,2,18,8,18,17,18,22,18,15,3,1,18,31,
+    3,1,21,21,3,1,114,250,0,0,0,99,0,0,0,0,
+    0,0,0,0,0,0,0,0,3,0,0,0,64,0,0,0,
+    115,133,0,0,0,101,0,0,90,1,0,100,0,0,90,2,
+    0,100,1,0,90,3,0,100,2,0,100,3,0,132,0,0,
+    90,4,0,100,4,0,100,5,0,132,0,0,90,5,0,101,
+    6,0,90,7,0,100,6,0,100,7,0,132,0,0,90,8,
+    0,100,8,0,100,9,0,132,0,0,90,9,0,100,10,0,
+    100,11,0,100,12,0,132,1,0,90,10,0,100,13,0,100,
+    14,0,132,0,0,90,11,0,101,12,0,100,15,0,100,16,
+    0,132,0,0,131,1,0,90,13,0,100,17,0,100,18,0,
+    132,0,0,90,14,0,100,10,0,83,41,19,218,10,70,105,
+    108,101,70,105,110,100,101,114,122,172,70,105,108,101,45,98,
+    97,115,101,100,32,102,105,110,100,101,114,46,10,10,32,32,
+    32,32,73,110,116,101,114,97,99,116,105,111,110,115,32,119,
+    105,116,104,32,116,104,101,32,102,105,108,101,32,115,121,115,
+    116,101,109,32,97,114,101,32,99,97,99,104,101,100,32,102,
+    111,114,32,112,101,114,102,111,114,109,97,110,99,101,44,32,
+    98,101,105,110,103,10,32,32,32,32,114,101,102,114,101,115,
+    104,101,100,32,119,104,101,110,32,116,104,101,32,100,105,114,
+    101,99,116,111,114,121,32,116,104,101,32,102,105,110,100,101,
+    114,32,105,115,32,104,97,110,100,108,105,110,103,32,104,97,
+    115,32,98,101,101,110,32,109,111,100,105,102,105,101,100,46,
+    10,10,32,32,32,32,99,2,0,0,0,0,0,0,0,5,
+    0,0,0,5,0,0,0,7,0,0,0,115,122,0,0,0,
+    103,0,0,125,3,0,120,52,0,124,2,0,68,93,44,0,
+    92,2,0,137,0,0,125,4,0,124,3,0,106,0,0,135,
+    0,0,102,1,0,100,1,0,100,2,0,134,0,0,124,4,
+    0,68,131,1,0,131,1,0,1,113,13,0,87,124,3,0,
+    124,0,0,95,1,0,124,1,0,112,79,0,100,3,0,124,
+    0,0,95,2,0,100,6,0,124,0,0,95,3,0,116,4,
+    0,131,0,0,124,0,0,95,5,0,116,4,0,131,0,0,
+    124,0,0,95,6,0,100,5,0,83,41,7,122,154,73,110,
+    105,116,105,97,108,105,122,101,32,119,105,116,104,32,116,104,
+    101,32,112,97,116,104,32,116,111,32,115,101,97,114,99,104,
+    32,111,110,32,97,110,100,32,97,32,118,97,114,105,97,98,
+    108,101,32,110,117,109,98,101,114,32,111,102,10,32,32,32,
+    32,32,32,32,32,50,45,116,117,112,108,101,115,32,99,111,
+    110,116,97,105,110,105,110,103,32,116,104,101,32,108,111,97,
+    100,101,114,32,97,110,100,32,116,104,101,32,102,105,108,101,
+    32,115,117,102,102,105,120,101,115,32,116,104,101,32,108,111,
+    97,100,101,114,10,32,32,32,32,32,32,32,32,114,101,99,
+    111,103,110,105,122,101,115,46,99,1,0,0,0,0,0,0,
+    0,2,0,0,0,3,0,0,0,51,0,0,0,115,27,0,
+    0,0,124,0,0,93,17,0,125,1,0,124,1,0,136,0,
+    0,102,2,0,86,1,113,3,0,100,0,0,83,41,1,78,
+    114,4,0,0,0,41,2,114,24,0,0,0,114,226,0,0,
+    0,41,1,114,129,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,114,228,0,0,0,168,4,0,0,115,2,0,0,0,
+    6,0,122,38,70,105,108,101,70,105,110,100,101,114,46,95,
+    95,105,110,105,116,95,95,46,60,108,111,99,97,108,115,62,
+    46,60,103,101,110,101,120,112,114,62,114,60,0,0,0,114,
+    31,0,0,0,78,114,89,0,0,0,41,7,114,151,0,0,
+    0,218,8,95,108,111,97,100,101,114,115,114,37,0,0,0,
+    218,11,95,112,97,116,104,95,109,116,105,109,101,218,3,115,
+    101,116,218,11,95,112,97,116,104,95,99,97,99,104,101,218,
+    19,95,114,101,108,97,120,101,100,95,112,97,116,104,95,99,
+    97,99,104,101,41,5,114,110,0,0,0,114,37,0,0,0,
+    218,14,108,111,97,100,101,114,95,100,101,116,97,105,108,115,
+    90,7,108,111,97,100,101,114,115,114,168,0,0,0,114,4,
+    0,0,0,41,1,114,129,0,0,0,114,6,0,0,0,114,
+    186,0,0,0,162,4,0,0,115,16,0,0,0,0,4,6,
+    1,19,1,36,1,9,2,15,1,9,1,12,1,122,19,70,
+    105,108,101,70,105,110,100,101,114,46,95,95,105,110,105,116,
+    95,95,99,1,0,0,0,0,0,0,0,1,0,0,0,2,
+    0,0,0,67,0,0,0,115,13,0,0,0,100,3,0,124,
+    0,0,95,0,0,100,2,0,83,41,4,122,31,73,110,118,
+    97,108,105,100,97,116,101,32,116,104,101,32,100,105,114,101,
+    99,116,111,114,121,32,109,116,105,109,101,46,114,31,0,0,
+    0,78,114,89,0,0,0,41,1,114,9,1,0,0,41,1,
+    114,110,0,0,0,114,4,0,0,0,114,4,0,0,0,114,
+    6,0,0,0,114,251,0,0,0,176,4,0,0,115,2,0,
+    0,0,0,2,122,28,70,105,108,101,70,105,110,100,101,114,
+    46,105,110,118,97,108,105,100,97,116,101,95,99,97,99,104,
+    101,115,99,2,0,0,0,0,0,0,0,3,0,0,0,2,
+    0,0,0,67,0,0,0,115,59,0,0,0,124,0,0,106,
+    0,0,124,1,0,131,1,0,125,2,0,124,2,0,100,1,
+    0,107,8,0,114,37,0,100,1,0,103,0,0,102,2,0,
+    83,124,2,0,106,1,0,124,2,0,106,2,0,112,55,0,
+    103,0,0,102,2,0,83,41,2,122,197,84,114,121,32,116,
+    111,32,102,105,110,100,32,97,32,108,111,97,100,101,114,32,
+    102,111,114,32,116,104,101,32,115,112,101,99,105,102,105,101,
+    100,32,109,111,100,117,108,101,44,32,111,114,32,116,104,101,
+    32,110,97,109,101,115,112,97,99,101,10,32,32,32,32,32,
+    32,32,32,112,97,99,107,97,103,101,32,112,111,114,116,105,
+    111,110,115,46,32,82,101,116,117,114,110,115,32,40,108,111,
+    97,100,101,114,44,32,108,105,115,116,45,111,102,45,112,111,
+    114,116,105,111,110,115,41,46,10,10,32,32,32,32,32,32,
+    32,32,84,104,105,115,32,109,101,116,104,111,100,32,105,115,
+    32,100,101,112,114,101,99,97,116,101,100,46,32,32,85,115,
+    101,32,102,105,110,100,95,115,112,101,99,40,41,32,105,110,
+    115,116,101,97,100,46,10,10,32,32,32,32,32,32,32,32,
+    78,41,3,114,182,0,0,0,114,129,0,0,0,114,158,0,
+    0,0,41,3,114,110,0,0,0,114,128,0,0,0,114,166,
+    0,0,0,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,114,126,0,0,0,182,4,0,0,115,8,0,0,0,
+    0,7,15,1,12,1,10,1,122,22,70,105,108,101,70,105,
+    110,100,101,114,46,102,105,110,100,95,108,111,97,100,101,114,
+    99,6,0,0,0,0,0,0,0,7,0,0,0,7,0,0,
+    0,67,0,0,0,115,40,0,0,0,124,1,0,124,2,0,
+    124,3,0,131,2,0,125,6,0,116,0,0,124,2,0,124,
+    3,0,100,1,0,124,6,0,100,2,0,124,4,0,131,2,
+    2,83,41,3,78,114,129,0,0,0,114,158,0,0,0,41,
+    1,114,169,0,0,0,41,7,114,110,0,0,0,114,167,0,
+    0,0,114,128,0,0,0,114,37,0,0,0,90,4,115,109,
+    115,108,114,181,0,0,0,114,129,0,0,0,114,4,0,0,
+    0,114,4,0,0,0,114,6,0,0,0,114,6,1,0,0,
+    194,4,0,0,115,6,0,0,0,0,1,15,1,18,1,122,
+    20,70,105,108,101,70,105,110,100,101,114,46,95,103,101,116,
+    95,115,112,101,99,78,99,3,0,0,0,0,0,0,0,14,
+    0,0,0,15,0,0,0,67,0,0,0,115,234,1,0,0,
+    100,1,0,125,3,0,124,1,0,106,0,0,100,2,0,131,
+    1,0,100,3,0,25,125,4,0,121,34,0,116,1,0,124,
+    0,0,106,2,0,112,49,0,116,3,0,106,4,0,131,0,
+    0,131,1,0,106,5,0,125,5,0,87,110,24,0,4,116,
+    6,0,107,10,0,114,85,0,1,1,1,100,10,0,125,5,
+    0,89,110,1,0,88,124,5,0,124,0,0,106,7,0,107,
+    3,0,114,120,0,124,0,0,106,8,0,131,0,0,1,124,
+    5,0,124,0,0,95,7,0,116,9,0,131,0,0,114,153,
+    0,124,0,0,106,10,0,125,6,0,124,4,0,106,11,0,
+    131,0,0,125,7,0,110,15,0,124,0,0,106,12,0,125,
+    6,0,124,4,0,125,7,0,124,7,0,124,6,0,107,6,
+    0,114,45,1,116,13,0,124,0,0,106,2,0,124,4,0,
+    131,2,0,125,8,0,120,100,0,124,0,0,106,14,0,68,
+    93,77,0,92,2,0,125,9,0,125,10,0,100,5,0,124,
+    9,0,23,125,11,0,116,13,0,124,8,0,124,11,0,131,
+    2,0,125,12,0,116,15,0,124,12,0,131,1,0,114,208,
+    0,124,0,0,106,16,0,124,10,0,124,1,0,124,12,0,
+    124,8,0,103,1,0,124,2,0,131,5,0,83,113,208,0,
+    87,116,17,0,124,8,0,131,1,0,125,3,0,120,123,0,
+    124,0,0,106,14,0,68,93,112,0,92,2,0,125,9,0,
+    125,10,0,116,13,0,124,0,0,106,2,0,124,4,0,124,
+    9,0,23,131,2,0,125,12,0,116,18,0,100,6,0,106,
+    19,0,124,12,0,131,1,0,100,7,0,100,3,0,131,1,
+    1,1,124,7,0,124,9,0,23,124,6,0,107,6,0,114,
+    55,1,116,15,0,124,12,0,131,1,0,114,55,1,124,0,
+    0,106,16,0,124,10,0,124,1,0,124,12,0,100,8,0,
+    124,2,0,131,5,0,83,113,55,1,87,124,3,0,114,230,
+    1,116,18,0,100,9,0,106,19,0,124,8,0,131,1,0,
+    131,1,0,1,116,20,0,106,21,0,124,1,0,100,8,0,
+    131,2,0,125,13,0,124,8,0,103,1,0,124,13,0,95,
+    22,0,124,13,0,83,100,8,0,83,41,11,122,102,84,114,
+    121,32,116,111,32,102,105,110,100,32,97,32,115,112,101,99,
+    32,102,111,114,32,116,104,101,32,115,112,101,99,105,102,105,
+    101,100,32,109,111,100,117,108,101,46,32,32,82,101,116,117,
+    114,110,115,32,116,104,101,10,32,32,32,32,32,32,32,32,
+    109,97,116,99,104,105,110,103,32,115,112,101,99,44,32,111,
+    114,32,78,111,110,101,32,105,102,32,110,111,116,32,102,111,
+    117,110,100,46,70,114,60,0,0,0,114,58,0,0,0,114,
+    31,0,0,0,114,186,0,0,0,122,9,116,114,121,105,110,
+    103,32,123,125,114,100,0,0,0,78,122,25,112,111,115,115,
+    105,98,108,101,32,110,97,109,101,115,112,97,99,101,32,102,
+    111,114,32,123,125,114,89,0,0,0,41,23,114,34,0,0,
+    0,114,41,0,0,0,114,37,0,0,0,114,3,0,0,0,
+    114,47,0,0,0,114,220,0,0,0,114,42,0,0,0,114,
+    9,1,0,0,218,11,95,102,105,108,108,95,99,97,99,104,
+    101,114,7,0,0,0,114,12,1,0,0,114,90,0,0,0,
+    114,11,1,0,0,114,30,0,0,0,114,8,1,0,0,114,
+    46,0,0,0,114,6,1,0,0,114,48,0,0,0,114,107,
+    0,0,0,114,49,0,0,0,114,123,0,0,0,114,162,0,
+    0,0,114,158,0,0,0,41,14,114,110,0,0,0,114,128,
+    0,0,0,114,181,0,0,0,90,12,105,115,95,110,97,109,
+    101,115,112,97,99,101,90,11,116,97,105,108,95,109,111,100,
+    117,108,101,114,135,0,0,0,90,5,99,97,99,104,101,90,
+    12,99,97,99,104,101,95,109,111,100,117,108,101,90,9,98,
+    97,115,101,95,112,97,116,104,114,226,0,0,0,114,167,0,
+    0,0,90,13,105,110,105,116,95,102,105,108,101,110,97,109,
+    101,90,9,102,117,108,108,95,112,97,116,104,114,166,0,0,
+    0,114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,
+    114,182,0,0,0,199,4,0,0,115,68,0,0,0,0,3,
+    6,1,19,1,3,1,34,1,13,1,11,1,15,1,10,1,
+    9,2,9,1,9,1,15,2,9,1,6,2,12,1,18,1,
+    22,1,10,1,15,1,12,1,32,4,12,2,22,1,22,1,
+    25,1,16,1,12,1,29,1,6,1,19,1,18,1,12,1,
+    4,1,122,20,70,105,108,101,70,105,110,100,101,114,46,102,
+    105,110,100,95,115,112,101,99,99,1,0,0,0,0,0,0,
+    0,9,0,0,0,13,0,0,0,67,0,0,0,115,11,1,
+    0,0,124,0,0,106,0,0,125,1,0,121,31,0,116,1,
+    0,106,2,0,124,1,0,112,33,0,116,1,0,106,3,0,
+    131,0,0,131,1,0,125,2,0,87,110,33,0,4,116,4,
+    0,116,5,0,116,6,0,102,3,0,107,10,0,114,75,0,
+    1,1,1,103,0,0,125,2,0,89,110,1,0,88,116,7,
+    0,106,8,0,106,9,0,100,1,0,131,1,0,115,112,0,
+    116,10,0,124,2,0,131,1,0,124,0,0,95,11,0,110,
+    111,0,116,10,0,131,0,0,125,3,0,120,90,0,124,2,
+    0,68,93,82,0,125,4,0,124,4,0,106,12,0,100,2,
+    0,131,1,0,92,3,0,125,5,0,125,6,0,125,7,0,
+    124,6,0,114,191,0,100,3,0,106,13,0,124,5,0,124,
+    7,0,106,14,0,131,0,0,131,2,0,125,8,0,110,6,
+    0,124,5,0,125,8,0,124,3,0,106,15,0,124,8,0,
+    131,1,0,1,113,128,0,87,124,3,0,124,0,0,95,11,
+    0,116,7,0,106,8,0,106,9,0,116,16,0,131,1,0,
+    114,7,1,100,4,0,100,5,0,132,0,0,124,2,0,68,
+    131,1,0,124,0,0,95,17,0,100,6,0,83,41,7,122,
+    68,70,105,108,108,32,116,104,101,32,99,97,99,104,101,32,
+    111,102,32,112,111,116,101,110,116,105,97,108,32,109,111,100,
+    117,108,101,115,32,97,110,100,32,112,97,99,107,97,103,101,
+    115,32,102,111,114,32,116,104,105,115,32,100,105,114,101,99,
+    116,111,114,121,46,114,0,0,0,0,114,60,0,0,0,122,
+    5,123,125,46,123,125,99,1,0,0,0,0,0,0,0,2,
+    0,0,0,3,0,0,0,83,0,0,0,115,28,0,0,0,
+    104,0,0,124,0,0,93,18,0,125,1,0,124,1,0,106,
+    0,0,131,0,0,146,2,0,113,6,0,83,114,4,0,0,
+    0,41,1,114,90,0,0,0,41,2,114,24,0,0,0,90,
+    2,102,110,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,250,9,60,115,101,116,99,111,109,112,62,17,5,0,
+    0,115,2,0,0,0,9,0,122,41,70,105,108,101,70,105,
+    110,100,101,114,46,95,102,105,108,108,95,99,97,99,104,101,
+    46,60,108,111,99,97,108,115,62,46,60,115,101,116,99,111,
+    109,112,62,78,41,18,114,37,0,0,0,114,3,0,0,0,
+    90,7,108,105,115,116,100,105,114,114,47,0,0,0,114,1,
+    1,0,0,218,15,80,101,114,109,105,115,115,105,111,110,69,
+    114,114,111,114,218,18,78,111,116,65,68,105,114,101,99,116,
+    111,114,121,69,114,114,111,114,114,8,0,0,0,114,9,0,
+    0,0,114,10,0,0,0,114,10,1,0,0,114,11,1,0,
+    0,114,85,0,0,0,114,49,0,0,0,114,90,0,0,0,
+    218,3,97,100,100,114,11,0,0,0,114,12,1,0,0,41,
+    9,114,110,0,0,0,114,37,0,0,0,90,8,99,111,110,
+    116,101,110,116,115,90,21,108,111,119,101,114,95,115,117,102,
+    102,105,120,95,99,111,110,116,101,110,116,115,114,246,0,0,
+    0,114,108,0,0,0,114,238,0,0,0,114,226,0,0,0,
+    90,8,110,101,119,95,110,97,109,101,114,4,0,0,0,114,
+    4,0,0,0,114,6,0,0,0,114,14,1,0,0,244,4,
+    0,0,115,34,0,0,0,0,2,9,1,3,1,31,1,22,
+    3,11,3,18,1,18,7,9,1,13,1,24,1,6,1,27,
+    2,6,1,17,1,9,1,18,1,122,22,70,105,108,101,70,
+    105,110,100,101,114,46,95,102,105,108,108,95,99,97,99,104,
+    101,99,1,0,0,0,0,0,0,0,3,0,0,0,3,0,
+    0,0,7,0,0,0,115,25,0,0,0,135,0,0,135,1,
+    0,102,2,0,100,1,0,100,2,0,134,0,0,125,2,0,
+    124,2,0,83,41,3,97,20,1,0,0,65,32,99,108,97,
+    115,115,32,109,101,116,104,111,100,32,119,104,105,99,104,32,
+    114,101,116,117,114,110,115,32,97,32,99,108,111,115,117,114,
+    101,32,116,111,32,117,115,101,32,111,110,32,115,121,115,46,
+    112,97,116,104,95,104,111,111,107,10,32,32,32,32,32,32,
+    32,32,119,104,105,99,104,32,119,105,108,108,32,114,101,116,
+    117,114,110,32,97,110,32,105,110,115,116,97,110,99,101,32,
+    117,115,105,110,103,32,116,104,101,32,115,112,101,99,105,102,
+    105,101,100,32,108,111,97,100,101,114,115,32,97,110,100,32,
+    116,104,101,32,112,97,116,104,10,32,32,32,32,32,32,32,
+    32,99,97,108,108,101,100,32,111,110,32,116,104,101,32,99,
+    108,111,115,117,114,101,46,10,10,32,32,32,32,32,32,32,
+    32,73,102,32,116,104,101,32,112,97,116,104,32,99,97,108,
+    108,101,100,32,111,110,32,116,104,101,32,99,108,111,115,117,
+    114,101,32,105,115,32,110,111,116,32,97,32,100,105,114,101,
+    99,116,111,114,121,44,32,73,109,112,111,114,116,69,114,114,
+    111,114,32,105,115,10,32,32,32,32,32,32,32,32,114,97,
+    105,115,101,100,46,10,10,32,32,32,32,32,32,32,32,99,
+    1,0,0,0,0,0,0,0,1,0,0,0,4,0,0,0,
+    19,0,0,0,115,43,0,0,0,116,0,0,124,0,0,131,
+    1,0,115,30,0,116,1,0,100,1,0,100,2,0,124,0,
+    0,131,1,1,130,1,0,136,0,0,124,0,0,136,1,0,
+    140,1,0,83,41,3,122,45,80,97,116,104,32,104,111,111,
+    107,32,102,111,114,32,105,109,112,111,114,116,108,105,98,46,
+    109,97,99,104,105,110,101,114,121,46,70,105,108,101,70,105,
+    110,100,101,114,46,122,30,111,110,108,121,32,100,105,114,101,
+    99,116,111,114,105,101,115,32,97,114,101,32,115,117,112,112,
+    111,114,116,101,100,114,37,0,0,0,41,2,114,48,0,0,
+    0,114,109,0,0,0,41,1,114,37,0,0,0,41,2,114,
+    172,0,0,0,114,13,1,0,0,114,4,0,0,0,114,6,
+    0,0,0,218,24,112,97,116,104,95,104,111,111,107,95,102,
+    111,114,95,70,105,108,101,70,105,110,100,101,114,29,5,0,
+    0,115,6,0,0,0,0,2,12,1,18,1,122,54,70,105,
+    108,101,70,105,110,100,101,114,46,112,97,116,104,95,104,111,
+    111,107,46,60,108,111,99,97,108,115,62,46,112,97,116,104,
+    95,104,111,111,107,95,102,111,114,95,70,105,108,101,70,105,
+    110,100,101,114,114,4,0,0,0,41,3,114,172,0,0,0,
+    114,13,1,0,0,114,19,1,0,0,114,4,0,0,0,41,
+    2,114,172,0,0,0,114,13,1,0,0,114,6,0,0,0,
+    218,9,112,97,116,104,95,104,111,111,107,19,5,0,0,115,
+    4,0,0,0,0,10,21,6,122,20,70,105,108,101,70,105,
+    110,100,101,114,46,112,97,116,104,95,104,111,111,107,99,1,
+    0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,67,
+    0,0,0,115,16,0,0,0,100,1,0,106,0,0,124,0,
+    0,106,1,0,131,1,0,83,41,2,78,122,16,70,105,108,
+    101,70,105,110,100,101,114,40,123,33,114,125,41,41,2,114,
+    49,0,0,0,114,37,0,0,0,41,1,114,110,0,0,0,
+    114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,114,
+    245,0,0,0,37,5,0,0,115,2,0,0,0,0,1,122,
+    19,70,105,108,101,70,105,110,100,101,114,46,95,95,114,101,
+    112,114,95,95,41,15,114,114,0,0,0,114,113,0,0,0,
+    114,115,0,0,0,114,116,0,0,0,114,186,0,0,0,114,
+    251,0,0,0,114,132,0,0,0,114,183,0,0,0,114,126,
+    0,0,0,114,6,1,0,0,114,182,0,0,0,114,14,1,
+    0,0,114,184,0,0,0,114,20,1,0,0,114,245,0,0,
+    0,114,4,0,0,0,114,4,0,0,0,114,4,0,0,0,
+    114,6,0,0,0,114,7,1,0,0,153,4,0,0,115,20,
+    0,0,0,12,7,6,2,12,14,12,4,6,2,12,12,12,
+    5,15,45,12,31,18,18,114,7,1,0,0,99,4,0,0,
+    0,0,0,0,0,6,0,0,0,11,0,0,0,67,0,0,
+    0,115,195,0,0,0,124,0,0,106,0,0,100,1,0,131,
+    1,0,125,4,0,124,0,0,106,0,0,100,2,0,131,1,
+    0,125,5,0,124,4,0,115,99,0,124,5,0,114,54,0,
+    124,5,0,106,1,0,125,4,0,110,45,0,124,2,0,124,
+    3,0,107,2,0,114,84,0,116,2,0,124,1,0,124,2,
+    0,131,2,0,125,4,0,110,15,0,116,3,0,124,1,0,
+    124,2,0,131,2,0,125,4,0,124,5,0,115,126,0,116,
+    4,0,124,1,0,124,2,0,100,3,0,124,4,0,131,2,
+    1,125,5,0,121,44,0,124,5,0,124,0,0,100,2,0,
+    60,124,4,0,124,0,0,100,1,0,60,124,2,0,124,0,
+    0,100,4,0,60,124,3,0,124,0,0,100,5,0,60,87,
+    110,18,0,4,116,5,0,107,10,0,114,190,0,1,1,1,
+    89,110,1,0,88,100,0,0,83,41,6,78,218,10,95,95,
+    108,111,97,100,101,114,95,95,218,8,95,95,115,112,101,99,
+    95,95,114,129,0,0,0,90,8,95,95,102,105,108,101,95,
+    95,90,10,95,95,99,97,99,104,101,100,95,95,41,6,218,
+    3,103,101,116,114,129,0,0,0,114,224,0,0,0,114,219,
+    0,0,0,114,169,0,0,0,218,9,69,120,99,101,112,116,
+    105,111,110,41,6,90,2,110,115,114,108,0,0,0,90,8,
+    112,97,116,104,110,97,109,101,90,9,99,112,97,116,104,110,
+    97,109,101,114,129,0,0,0,114,166,0,0,0,114,4,0,
+    0,0,114,4,0,0,0,114,6,0,0,0,218,14,95,102,
+    105,120,95,117,112,95,109,111,100,117,108,101,43,5,0,0,
+    115,34,0,0,0,0,2,15,1,15,1,6,1,6,1,12,
+    1,12,1,18,2,15,1,6,1,21,1,3,1,10,1,10,
+    1,10,1,14,1,13,2,114,25,1,0,0,99,0,0,0,
+    0,0,0,0,0,3,0,0,0,3,0,0,0,67,0,0,
+    0,115,55,0,0,0,116,0,0,116,1,0,106,2,0,131,
+    0,0,102,2,0,125,0,0,116,3,0,116,4,0,102,2,
+    0,125,1,0,116,5,0,116,6,0,102,2,0,125,2,0,
+    124,0,0,124,1,0,124,2,0,103,3,0,83,41,1,122,
+    95,82,101,116,117,114,110,115,32,97,32,108,105,115,116,32,
+    111,102,32,102,105,108,101,45,98,97,115,101,100,32,109,111,
+    100,117,108,101,32,108,111,97,100,101,114,115,46,10,10,32,
+    32,32,32,69,97,99,104,32,105,116,101,109,32,105,115,32,
+    97,32,116,117,112,108,101,32,40,108,111,97,100,101,114,44,
+    32,115,117,102,102,105,120,101,115,41,46,10,32,32,32,32,
+    41,7,114,225,0,0,0,114,147,0,0,0,218,18,101,120,
+    116,101,110,115,105,111,110,95,115,117,102,102,105,120,101,115,
+    114,219,0,0,0,114,86,0,0,0,114,224,0,0,0,114,
+    76,0,0,0,41,3,90,10,101,120,116,101,110,115,105,111,
+    110,115,90,6,115,111,117,114,99,101,90,8,98,121,116,101,
+    99,111,100,101,114,4,0,0,0,114,4,0,0,0,114,6,
+    0,0,0,114,163,0,0,0,66,5,0,0,115,8,0,0,
+    0,0,5,18,1,12,1,12,1,114,163,0,0,0,99,1,
+    0,0,0,0,0,0,0,12,0,0,0,12,0,0,0,67,
+    0,0,0,115,70,2,0,0,124,0,0,97,0,0,116,0,
+    0,106,1,0,97,1,0,116,0,0,106,2,0,97,2,0,
+    116,1,0,106,3,0,116,4,0,25,125,1,0,120,76,0,
+    100,26,0,68,93,68,0,125,2,0,124,2,0,116,1,0,
+    106,3,0,107,7,0,114,83,0,116,0,0,106,5,0,124,
+    2,0,131,1,0,125,3,0,110,13,0,116,1,0,106,3,
+    0,124,2,0,25,125,3,0,116,6,0,124,1,0,124,2,
+    0,124,3,0,131,3,0,1,113,44,0,87,100,5,0,100,
+    6,0,103,1,0,102,2,0,100,7,0,100,8,0,100,6,
+    0,103,2,0,102,2,0,102,2,0,125,4,0,120,149,0,
+    124,4,0,68,93,129,0,92,2,0,125,5,0,125,6,0,
+    116,7,0,100,9,0,100,10,0,132,0,0,124,6,0,68,
+    131,1,0,131,1,0,115,199,0,116,8,0,130,1,0,124,
+    6,0,100,11,0,25,125,7,0,124,5,0,116,1,0,106,
+    3,0,107,6,0,114,241,0,116,1,0,106,3,0,124,5,
+    0,25,125,8,0,80,113,156,0,121,20,0,116,0,0,106,
+    5,0,124,5,0,131,1,0,125,8,0,80,87,113,156,0,
+    4,116,9,0,107,10,0,114,28,1,1,1,1,119,156,0,
+    89,113,156,0,88,113,156,0,87,116,9,0,100,12,0,131,
+    1,0,130,1,0,116,6,0,124,1,0,100,13,0,124,8,
+    0,131,3,0,1,116,6,0,124,1,0,100,14,0,124,7,
+    0,131,3,0,1,116,6,0,124,1,0,100,15,0,100,16,
+    0,106,10,0,124,6,0,131,1,0,131,3,0,1,121,19,
+    0,116,0,0,106,5,0,100,17,0,131,1,0,125,9,0,
+    87,110,24,0,4,116,9,0,107,10,0,114,147,1,1,1,
+    1,100,18,0,125,9,0,89,110,1,0,88,116,6,0,124,
+    1,0,100,17,0,124,9,0,131,3,0,1,116,0,0,106,
+    5,0,100,19,0,131,1,0,125,10,0,116,6,0,124,1,
+    0,100,19,0,124,10,0,131,3,0,1,124,5,0,100,7,
+    0,107,2,0,114,238,1,116,0,0,106,5,0,100,20,0,
+    131,1,0,125,11,0,116,6,0,124,1,0,100,21,0,124,
+    11,0,131,3,0,1,116,6,0,124,1,0,100,22,0,116,
+    11,0,131,0,0,131,3,0,1,116,12,0,106,13,0,116,
+    2,0,106,14,0,131,0,0,131,1,0,1,124,5,0,100,
+    7,0,107,2,0,114,66,2,116,15,0,106,16,0,100,23,
+    0,131,1,0,1,100,24,0,116,12,0,107,6,0,114,66,
+    2,100,25,0,116,17,0,95,18,0,100,18,0,83,41,27,
+    122,205,83,101,116,117,112,32,116,104,101,32,112,97,116,104,
+    45,98,97,115,101,100,32,105,109,112,111,114,116,101,114,115,
+    32,102,111,114,32,105,109,112,111,114,116,108,105,98,32,98,
+    121,32,105,109,112,111,114,116,105,110,103,32,110,101,101,100,
+    101,100,10,32,32,32,32,98,117,105,108,116,45,105,110,32,
+    109,111,100,117,108,101,115,32,97,110,100,32,105,110,106,101,
+    99,116,105,110,103,32,116,104,101,109,32,105,110,116,111,32,
+    116,104,101,32,103,108,111,98,97,108,32,110,97,109,101,115,
+    112,97,99,101,46,10,10,32,32,32,32,79,116,104,101,114,
+    32,99,111,109,112,111,110,101,110,116,115,32,97,114,101,32,
+    101,120,116,114,97,99,116,101,100,32,102,114,111,109,32,116,
+    104,101,32,99,111,114,101,32,98,111,111,116,115,116,114,97,
+    112,32,109,111,100,117,108,101,46,10,10,32,32,32,32,114,
+    51,0,0,0,114,62,0,0,0,218,8,98,117,105,108,116,
+    105,110,115,114,144,0,0,0,90,5,112,111,115,105,120,250,
+    1,47,218,2,110,116,250,1,92,99,1,0,0,0,0,0,
+    0,0,2,0,0,0,3,0,0,0,115,0,0,0,115,33,
+    0,0,0,124,0,0,93,23,0,125,1,0,116,0,0,124,
+    1,0,131,1,0,100,0,0,107,2,0,86,1,113,3,0,
+    100,1,0,83,41,2,114,31,0,0,0,78,41,1,114,33,
+    0,0,0,41,2,114,24,0,0,0,114,79,0,0,0,114,
+    4,0,0,0,114,4,0,0,0,114,6,0,0,0,114,228,
+    0,0,0,102,5,0,0,115,2,0,0,0,6,0,122,25,
+    95,115,101,116,117,112,46,60,108,111,99,97,108,115,62,46,
+    60,103,101,110,101,120,112,114,62,114,61,0,0,0,122,30,
+    105,109,112,111,114,116,108,105,98,32,114,101,113,117,105,114,
+    101,115,32,112,111,115,105,120,32,111,114,32,110,116,114,3,
+    0,0,0,114,27,0,0,0,114,23,0,0,0,114,32,0,
+    0,0,90,7,95,116,104,114,101,97,100,78,90,8,95,119,
+    101,97,107,114,101,102,90,6,119,105,110,114,101,103,114,171,
+    0,0,0,114,7,0,0,0,122,4,46,112,121,119,122,6,
+    95,100,46,112,121,100,84,41,4,114,51,0,0,0,114,62,
+    0,0,0,114,27,1,0,0,114,144,0,0,0,41,19,114,
+    123,0,0,0,114,8,0,0,0,114,147,0,0,0,114,240,
+    0,0,0,114,114,0,0,0,90,18,95,98,117,105,108,116,
+    105,110,95,102,114,111,109,95,110,97,109,101,114,118,0,0,
+    0,218,3,97,108,108,218,14,65,115,115,101,114,116,105,111,
+    110,69,114,114,111,114,114,109,0,0,0,114,28,0,0,0,
+    114,13,0,0,0,114,230,0,0,0,114,151,0,0,0,114,
+    26,1,0,0,114,86,0,0,0,114,165,0,0,0,114,170,
+    0,0,0,114,174,0,0,0,41,12,218,17,95,98,111,111,
+    116,115,116,114,97,112,95,109,111,100,117,108,101,90,11,115,
+    101,108,102,95,109,111,100,117,108,101,90,12,98,117,105,108,
+    116,105,110,95,110,97,109,101,90,14,98,117,105,108,116,105,
+    110,95,109,111,100,117,108,101,90,10,111,115,95,100,101,116,
+    97,105,108,115,90,10,98,117,105,108,116,105,110,95,111,115,
+    114,23,0,0,0,114,27,0,0,0,90,9,111,115,95,109,
+    111,100,117,108,101,90,13,116,104,114,101,97,100,95,109,111,
+    100,117,108,101,90,14,119,101,97,107,114,101,102,95,109,111,
+    100,117,108,101,90,13,119,105,110,114,101,103,95,109,111,100,
+    117,108,101,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,218,6,95,115,101,116,117,112,77,5,0,0,115,82,
+    0,0,0,0,8,6,1,9,1,9,3,13,1,13,1,15,
+    1,18,2,13,1,20,3,33,1,19,2,31,1,10,1,15,
+    1,13,1,4,2,3,1,15,1,5,1,13,1,12,2,12,
+    1,16,1,16,1,25,3,3,1,19,1,13,2,11,1,16,
+    3,15,1,16,3,12,1,15,1,16,3,19,1,19,1,12,
+    1,13,1,12,1,114,34,1,0,0,99,1,0,0,0,0,
+    0,0,0,2,0,0,0,3,0,0,0,67,0,0,0,115,
+    116,0,0,0,116,0,0,124,0,0,131,1,0,1,116,1,
+    0,131,0,0,125,1,0,116,2,0,106,3,0,106,4,0,
+    116,5,0,106,6,0,124,1,0,140,0,0,103,1,0,131,
+    1,0,1,116,7,0,106,8,0,100,1,0,107,2,0,114,
+    78,0,116,2,0,106,9,0,106,10,0,116,11,0,131,1,
+    0,1,116,2,0,106,9,0,106,10,0,116,12,0,131,1,
+    0,1,116,5,0,124,0,0,95,5,0,116,13,0,124,0,
+    0,95,13,0,100,2,0,83,41,3,122,41,73,110,115,116,
+    97,108,108,32,116,104,101,32,112,97,116,104,45,98,97,115,
+    101,100,32,105,109,112,111,114,116,32,99,111,109,112,111,110,
+    101,110,116,115,46,114,29,1,0,0,78,41,14,114,34,1,
+    0,0,114,163,0,0,0,114,8,0,0,0,114,255,0,0,
+    0,114,151,0,0,0,114,7,1,0,0,114,20,1,0,0,
+    114,3,0,0,0,114,114,0,0,0,218,9,109,101,116,97,
+    95,112,97,116,104,114,165,0,0,0,114,170,0,0,0,114,
+    250,0,0,0,114,219,0,0,0,41,2,114,33,1,0,0,
+    90,17,115,117,112,112,111,114,116,101,100,95,108,111,97,100,
+    101,114,115,114,4,0,0,0,114,4,0,0,0,114,6,0,
+    0,0,218,8,95,105,110,115,116,97,108,108,145,5,0,0,
+    115,16,0,0,0,0,2,10,1,9,1,28,1,15,1,16,
+    1,16,4,9,1,114,36,1,0,0,41,1,114,0,0,0,
+    0,41,2,114,1,0,0,0,114,2,0,0,0,41,59,114,
+    116,0,0,0,114,12,0,0,0,90,37,95,67,65,83,69,
+    95,73,78,83,69,78,83,73,84,73,86,69,95,80,76,65,
+    84,70,79,82,77,83,95,66,89,84,69,83,95,75,69,89,
+    114,11,0,0,0,114,13,0,0,0,114,19,0,0,0,114,
+    21,0,0,0,114,30,0,0,0,114,40,0,0,0,114,41,
+    0,0,0,114,45,0,0,0,114,46,0,0,0,114,48,0,
+    0,0,114,57,0,0,0,218,4,116,121,112,101,218,8,95,
+    95,99,111,100,101,95,95,114,146,0,0,0,114,17,0,0,
+    0,114,137,0,0,0,114,16,0,0,0,114,20,0,0,0,
+    90,17,95,82,65,87,95,77,65,71,73,67,95,78,85,77,
+    66,69,82,114,75,0,0,0,114,74,0,0,0,114,86,0,
+    0,0,114,76,0,0,0,90,23,68,69,66,85,71,95,66,
+    89,84,69,67,79,68,69,95,83,85,70,70,73,88,69,83,
+    90,27,79,80,84,73,77,73,90,69,68,95,66,89,84,69,
+    67,79,68,69,95,83,85,70,70,73,88,69,83,114,81,0,
+    0,0,114,87,0,0,0,114,93,0,0,0,114,97,0,0,
+    0,114,99,0,0,0,114,107,0,0,0,114,125,0,0,0,
+    114,132,0,0,0,114,143,0,0,0,114,149,0,0,0,114,
+    152,0,0,0,114,157,0,0,0,218,6,111,98,106,101,99,
+    116,114,164,0,0,0,114,169,0,0,0,114,170,0,0,0,
+    114,185,0,0,0,114,195,0,0,0,114,211,0,0,0,114,
+    219,0,0,0,114,224,0,0,0,114,230,0,0,0,114,225,
+    0,0,0,114,231,0,0,0,114,248,0,0,0,114,250,0,
+    0,0,114,7,1,0,0,114,25,1,0,0,114,163,0,0,
+    0,114,34,1,0,0,114,36,1,0,0,114,4,0,0,0,
+    114,4,0,0,0,114,4,0,0,0,114,6,0,0,0,218,
+    8,60,109,111,100,117,108,101,62,8,0,0,0,115,106,0,
+    0,0,6,16,6,1,6,1,3,1,7,3,12,17,12,5,
+    12,5,12,6,12,12,12,10,12,9,12,5,12,7,15,22,
+    15,114,22,1,18,2,6,1,6,2,9,2,9,2,10,2,
+    21,44,12,33,12,19,12,12,12,12,18,8,12,28,12,17,
+    21,55,21,12,18,10,12,14,9,3,12,1,15,65,19,64,
+    19,28,22,110,19,41,25,43,25,16,6,3,25,53,19,57,
+    19,41,19,134,19,146,15,23,12,11,12,68,
 };
index 6d1c6d0..24e20c3 100644 (file)
@@ -281,14 +281,16 @@ int
 _PyState_AddModule(PyObject* module, struct PyModuleDef* def)
 {
     PyInterpreterState *state;
+    if (!def) {
+        assert(PyErr_Occurred());
+        return -1;
+    }
     if (def->m_slots) {
         PyErr_SetString(PyExc_SystemError,
                         "PyState_AddModule called on module with slots");
         return -1;
     }
     state = GET_INTERP_STATE();
-    if (!def)
-        return -1;
     if (!state->modules_by_index) {
         state->modules_by_index = PyList_New(0);
         if (!state->modules_by_index)
index 7fbf06e..90cb2de 100644 (file)
@@ -528,7 +528,7 @@ print_error_text(PyObject *f, int offset, PyObject *text_obj)
             offset -= (int)(nl+1-text);
             text = nl+1;
         }
-        while (*text == ' ' || *text == '\t') {
+        while (*text == ' ' || *text == '\t' || *text == '\f') {
             text++;
             offset--;
         }
@@ -747,7 +747,7 @@ print_exception(PyObject *f, PyObject *value)
             err = PyFile_WriteString("<unknown>", f);
         }
         else {
-            if (_PyUnicode_CompareWithId(moduleName, &PyId_builtins) != 0)
+            if (!_PyUnicode_EqualToASCIIId(moduleName, &PyId_builtins))
             {
                 err = PyFile_WriteObject(moduleName, f, Py_PRINT_RAW);
                 err += PyFile_WriteString(".", f);
index 07dacfe..d203939 100644 (file)
@@ -9,9 +9,10 @@
 #  ifdef HAVE_LINUX_RANDOM_H
 #    include <linux/random.h>
 #  endif
-#  ifdef HAVE_GETRANDOM
+#  if defined(HAVE_SYS_RANDOM_H) && (defined(HAVE_GETRANDOM) || defined(HAVE_GETENTROPY))
 #    include <sys/random.h>
-#  elif defined(HAVE_GETRANDOM_SYSCALL)
+#  endif
+#  if !defined(HAVE_GETRANDOM) && defined(HAVE_GETRANDOM_SYSCALL)
 #    include <sys/syscall.h>
 #  endif
 #endif
@@ -119,11 +120,20 @@ py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal)
 #if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)
 #define PY_GETRANDOM 1
 
+/* Call getrandom()
+   - Return 1 on success
+   - Return 0 if getrandom() syscall is not available (failed with ENOSYS or
+     EPERM) or if getrandom(GRND_NONBLOCK) failed with EAGAIN (system urandom
+     not initialized yet) and raise=0.
+   - Raise an exception (if raise is non-zero) and return -1 on error:
+     getrandom() failed with EINTR and the Python signal handler raised an
+     exception, or getrandom() failed with a different error. */
 static int
 py_getrandom(void *buffer, Py_ssize_t size, int raise)
 {
-    /* Is getrandom() supported by the running kernel?
-     * Need Linux kernel 3.17 or newer, or Solaris 11.3 or newer */
+    /* Is getrandom() supported by the running kernel? Set to 0 if getrandom()
+       failed with ENOSYS or EPERM. Need Linux kernel 3.17 or newer, or Solaris
+       11.3 or newer */
     static int getrandom_works = 1;
 
     /* getrandom() on Linux will block if called before the kernel has
@@ -132,10 +142,11 @@ py_getrandom(void *buffer, Py_ssize_t size, int raise)
      * see https://bugs.python.org/issue26839. To avoid this, use the
      * GRND_NONBLOCK flag. */
     const int flags = GRND_NONBLOCK;
-    int n;
+    long n;
 
-    if (!getrandom_works)
+    if (!getrandom_works) {
         return 0;
+    }
 
     while (0 < size) {
 #ifdef sun
@@ -143,7 +154,7 @@ py_getrandom(void *buffer, Py_ssize_t size, int raise)
            to 1024 bytes */
         n = Py_MIN(size, 1024);
 #else
-        n = size;
+        n = Py_MIN(size, LONG_MAX);
 #endif
 
         errno = 0;
@@ -171,36 +182,43 @@ py_getrandom(void *buffer, Py_ssize_t size, int raise)
 #endif
 
         if (n < 0) {
-            if (errno == ENOSYS) {
+            /* ENOSYS: getrandom() syscall not supported by the kernel (but
+             * maybe supported by the host which built Python). EPERM:
+             * getrandom() syscall blocked by SECCOMP or something else. */
+            if (errno == ENOSYS || errno == EPERM) {
                 getrandom_works = 0;
                 return 0;
             }
             if (errno == EAGAIN) {
-                /* If we failed with EAGAIN, the entropy pool was
-                 * uninitialized. In this case, we return failure to fall
-                 * back to reading from /dev/urandom.
-                 *
-                 * Note: In this case the data read will not be random so
-                 * should not be used for cryptographic purposes. Retaining
-                 * the existing semantics for practical purposes. */
+                /* getrandom(GRND_NONBLOCK) fails with EAGAIN if the system
+                   urandom is not initialiazed yet. In this case, fall back on
+                   reading from /dev/urandom.
+
+                   Note: In this case the data read will not be random so
+                   should not be used for cryptographic purposes. Retaining
+                   the existing semantics for practical purposes. */
                 getrandom_works = 0;
                 return 0;
             }
 
             if (errno == EINTR) {
                 if (PyErr_CheckSignals()) {
-                    if (!raise)
+                    if (!raise) {
                         Py_FatalError("getrandom() interrupted by a signal");
+                    }
                     return -1;
                 }
+
                 /* retry getrandom() */
                 continue;
             }
 
-            if (raise)
+            if (raise) {
                 PyErr_SetFromErrno(PyExc_OSError);
-            else
+            }
+            else {
                 Py_FatalError("getrandom() failed");
+            }
             return -1;
         }
 
@@ -218,7 +236,9 @@ static struct {
 } urandom_cache = { -1 };
 
 
-/* Read size bytes from /dev/urandom into buffer.
+/* Read 'size' random bytes from py_getrandom(). Fall back on reading from
+   /dev/urandom if getrandom() is not available.
+
    Call Py_FatalError() on error. */
 static void
 dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
@@ -229,35 +249,39 @@ dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
     assert (0 < size);
 
 #ifdef PY_GETRANDOM
-    if (py_getrandom(buffer, size, 0) == 1)
+    if (py_getrandom(buffer, size, 0) == 1) {
         return;
-    /* getrandom() is not supported by the running kernel, fall back
-     * on reading /dev/urandom */
+    }
+    /* getrandom() failed with ENOSYS or EPERM,
+       fall back on reading /dev/urandom */
 #endif
 
     fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
-    if (fd < 0)
+    if (fd < 0) {
         Py_FatalError("Failed to open /dev/urandom");
+    }
 
     while (0 < size)
     {
         do {
             n = read(fd, buffer, (size_t)size);
         } while (n < 0 && errno == EINTR);
-        if (n <= 0)
-        {
-            /* stop on error or if read(size) returned 0 */
+
+        if (n <= 0) {
+            /* read() failed or returned 0 bytes */
             Py_FatalError("Failed to read bytes from /dev/urandom");
             break;
         }
         buffer += n;
-        size -= (Py_ssize_t)n;
+        size -= n;
     }
     close(fd);
 }
 
-/* Read size bytes from /dev/urandom into buffer.
-   Return 0 on success, raise an exception and return -1 on error. */
+/* Read 'size' random bytes from py_getrandom(). Fall back on reading from
+   /dev/urandom if getrandom() is not available.
+
+   Return 0 on success. Raise an exception and return -1 on error. */
 static int
 dev_urandom_python(char *buffer, Py_ssize_t size)
 {
@@ -273,12 +297,14 @@ dev_urandom_python(char *buffer, Py_ssize_t size)
 
 #ifdef PY_GETRANDOM
     res = py_getrandom(buffer, size, 1);
-    if (res < 0)
+    if (res < 0) {
         return -1;
-    if (res == 1)
+    }
+    if (res == 1) {
         return 0;
-    /* getrandom() is not supported by the running kernel, fall back
-     * on reading /dev/urandom */
+    }
+    /* getrandom() failed with ENOSYS or EPERM,
+       fall back on reading /dev/urandom */
 #endif
 
     if (urandom_cache.fd >= 0) {
@@ -325,8 +351,9 @@ dev_urandom_python(char *buffer, Py_ssize_t size)
 
     do {
         n = _Py_read(fd, buffer, (size_t)size);
-        if (n == -1)
+        if (n == -1) {
             return -1;
+        }
         if (n == 0) {
             PyErr_Format(PyExc_RuntimeError,
                     "Failed to read %zi bytes from /dev/urandom",
index 1591a20..adca2da 100644 (file)
@@ -1472,7 +1472,7 @@ symtable_visit_expr(struct symtable *st, expr_ty e)
         /* Special-case super: it counts as a use of __class__ */
         if (e->v.Name.ctx == Load &&
             st->st_cur->ste_type == FunctionBlock &&
-            !PyUnicode_CompareWithASCIIString(e->v.Name.id, "super")) {
+            _PyUnicode_EqualToASCIIString(e->v.Name.id, "super")) {
             if (!GET_IDENTIFIER(__class__) ||
                 !symtable_add_def(st, __class__, USE))
                 VISIT_QUIT(st, 0);
@@ -1621,7 +1621,7 @@ symtable_visit_alias(struct symtable *st, alias_ty a)
         store_name = name;
         Py_INCREF(store_name);
     }
-    if (PyUnicode_CompareWithASCIIString(name, "*")) {
+    if (!_PyUnicode_EqualToASCIIString(name, "*")) {
         int r = symtable_add_def(st, store_name, DEF_IMPORT);
         Py_DECREF(store_name);
         return r;
index 8d7e05a..1dc7d7c 100644 (file)
@@ -825,6 +825,7 @@ static PyStructSequence_Field windows_version_fields[] = {
     {"service_pack_minor", "Service Pack minor version number"},
     {"suite_mask", "Bit mask identifying available product suites"},
     {"product_type", "System product type"},
+    {"_platform_version", "Diagnostic version number"},
     {0}
 };
 
@@ -849,6 +850,12 @@ sys_getwindowsversion(PyObject *self)
     PyObject *version;
     int pos = 0;
     OSVERSIONINFOEX ver;
+    DWORD realMajor, realMinor, realBuild;
+    HANDLE hKernel32;
+    wchar_t kernel32_path[MAX_PATH];
+    LPVOID verblock;
+    DWORD verblock_size;
+
     ver.dwOSVersionInfoSize = sizeof(ver);
     if (!GetVersionEx((OSVERSIONINFO*) &ver))
         return PyErr_SetFromWindowsErr(0);
@@ -867,10 +874,40 @@ sys_getwindowsversion(PyObject *self)
     PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
     PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
 
+    realMajor = ver.dwMajorVersion;
+    realMinor = ver.dwMinorVersion;
+    realBuild = ver.dwBuildNumber;
+
+    // GetVersion will lie if we are running in a compatibility mode.
+    // We need to read the version info from a system file resource
+    // to accurately identify the OS version. If we fail for any reason,
+    // just return whatever GetVersion said.
+    hKernel32 = GetModuleHandleW(L"kernel32.dll");
+    if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
+        (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
+        (verblock = PyMem_RawMalloc(verblock_size))) {
+        VS_FIXEDFILEINFO *ffi;
+        UINT ffi_len;
+
+        if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
+            VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
+            realMajor = HIWORD(ffi->dwProductVersionMS);
+            realMinor = LOWORD(ffi->dwProductVersionMS);
+            realBuild = HIWORD(ffi->dwProductVersionLS);
+        }
+        PyMem_RawFree(verblock);
+    }
+    PyStructSequence_SET_ITEM(version, pos++, PyTuple_Pack(3,
+        PyLong_FromLong(realMajor),
+        PyLong_FromLong(realMinor),
+        PyLong_FromLong(realBuild)
+    ));
+
     if (PyErr_Occurred()) {
         Py_DECREF(version);
         return NULL;
     }
+
     return version;
 }
 
@@ -1582,7 +1619,7 @@ static PyStructSequence_Field version_info_fields[] = {
     {"major", "Major release number"},
     {"minor", "Minor release number"},
     {"micro", "Patch release number"},
-    {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
+    {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
     {"serial", "Serial release number"},
     {0}
 };
index 941d1cb..9e7fe3b 100644 (file)
@@ -132,47 +132,53 @@ newtracebackobject(PyTracebackObject *next, PyFrameObject *frame)
 int
 PyTraceBack_Here(PyFrameObject *frame)
 {
-    PyThreadState *tstate = PyThreadState_GET();
-    PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback;
-    PyTracebackObject *tb = newtracebackobject(oldtb, frame);
-    if (tb == NULL)
+    PyObject *exc, *val, *tb, *newtb;
+    PyErr_Fetch(&exc, &val, &tb);
+    newtb = (PyObject *)newtracebackobject((PyTracebackObject *)tb, frame);
+    if (newtb == NULL) {
+        _PyErr_ChainExceptions(exc, val, tb);
         return -1;
-    tstate->curexc_traceback = (PyObject *)tb;
-    Py_XDECREF(oldtb);
+    }
+    PyErr_Restore(exc, val, newtb);
+    Py_XDECREF(tb);
     return 0;
 }
 
 /* Insert a frame into the traceback for (funcname, filename, lineno). */
 void _PyTraceback_Add(const char *funcname, const char *filename, int lineno)
 {
-    PyObject *globals = NULL;
-    PyCodeObject *code = NULL;
-    PyFrameObject *frame = NULL;
-    PyObject *exception, *value, *tb;
+    PyObject *globals;
+    PyCodeObject *code;
+    PyFrameObject *frame;
+    PyObject *exc, *val, *tb;
 
     /* Save and clear the current exception. Python functions must not be
        called with an exception set. Calling Python functions happens when
        the codec of the filesystem encoding is implemented in pure Python. */
-    PyErr_Fetch(&exception, &value, &tb);
+    PyErr_Fetch(&exc, &val, &tb);
 
     globals = PyDict_New();
     if (!globals)
-        goto done;
+        goto error;
     code = PyCode_NewEmpty(filename, funcname, lineno);
-    if (!code)
-        goto done;
+    if (!code) {
+        Py_DECREF(globals);
+        goto error;
+    }
     frame = PyFrame_New(PyThreadState_Get(), code, globals, NULL);
+    Py_DECREF(globals);
+    Py_DECREF(code);
     if (!frame)
-        goto done;
+        goto error;
     frame->f_lineno = lineno;
 
-    PyErr_Restore(exception, value, tb);
+    PyErr_Restore(exc, val, tb);
     PyTraceBack_Here(frame);
+    Py_DECREF(frame);
+    return;
 
-done:
-    Py_XDECREF(globals);
-    Py_XDECREF(code);
-    Py_XDECREF(frame);
+error:
+    _PyErr_ChainExceptions(exc, val, tb);
 }
 
 static PyObject *
diff --git a/README b/README
index 9a07bfd..de3a091 100644 (file)
--- a/README
+++ b/README
@@ -1,8 +1,9 @@
-This is Python version 3.5.2
+This is Python version 3.5.3
 ============================
 
 Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
-2012, 2013, 2014, 2015, 2016 Python Software Foundation.  All rights reserved.
+2012, 2013, 2014, 2015, 2016, 2017 Python Software Foundation.  All rights
+reserved.
 
 Python 3.x is a new version of the language, which is incompatible with the
 2.x line of releases.  The language is mostly the same, but many details,
@@ -46,16 +47,17 @@ For example:
 (This will fail if you *also* built at the top-level directory.
 You should do a "make clean" at the toplevel first.)
 
-If you need an optimized version of Python, you type "make profile-opt" in the
-top level directory. This will rebuild the interpreter executable using Profile
-Guided Optimization (PGO). For more details, see the section bellow.
+To get an optimized build of Python, "configure --enable-optimizations" before
+you run make.  This sets the default make targets up to enable Profile Guided
+Optimization (PGO) and may be used to auto-enable Link Time Optimization (LTO)
+on some platforms.  For more details, see the sections bellow.
 
 
 Profile Guided Optimization
 ---------------------------
 
 PGO takes advantage of recent versions of the GCC or Clang compilers.
-If ran, the "profile-opt" rule will do several steps.
+If ran, "make profile-opt" will do several steps.
 
 First, the entire Python directory is cleaned of temporary files that
 may have resulted in a previous compilation.
@@ -68,13 +70,22 @@ workloads, as it has profiling instructions embedded inside.
 After this instrumented version of the interpreter is built, the Makefile
 will automatically run a training workload. This is necessary in order to
 profile the interpreter execution. Note also that any output, both stdout
-and stderr, that may appear at this step is supressed.
+and stderr, that may appear at this step is suppressed.
 
 Finally, the last step is to rebuild the interpreter, using the information
 collected in the previous one. The end result will be a Python binary
 that is optimized and suitable for distribution or production installation.
 
 
+Link Time Optimization
+----------------------
+
+Enabled via configure's --with-lto flag.  LTO takes advantages of recent
+compiler toolchains ability to optimize across the otherwise arbitrary .o file
+boundary when building final executables or shared libraries for additional
+performance gains.
+
+
 What's New
 ----------
 
index 1d851da..f615ed9 100755 (executable)
@@ -2793,7 +2793,7 @@ def correct_name_for_self(f):
     if f.kind in (CALLABLE, METHOD_INIT):
         if f.cls:
             return "PyObject *", "self"
-        return "PyModuleDef *", "module"
+        return "PyObject *", "module"
     if f.kind == STATIC_METHOD:
         return "void *", "null"
     if f.kind in (CLASS_METHOD, METHOD_NEW):
index ac0640c..a9479a6 100644 (file)
@@ -90,7 +90,7 @@ class ClinicWholeFileTest(TestCase):
         # the "end line" for the block if it
         # didn't end in "\n" (as in, the last)
         # byte of the file was '/'.
-        # so it woudl spit out an end line for you.
+        # so it would spit out an end line for you.
         # and since you really already had one,
         # the last line of the block got corrupted.
         c = clinic.Clinic(clinic.CLanguage(None))
index b10b030..8335d4c 100755 (executable)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python3
 
-"""Basic regular expression demostration facility (Perl style syntax)."""
+"""Basic regular expression demonstration facility (Perl style syntax)."""
 
 from tkinter import *
 import re
index c075807..44edd57 100755 (executable)
@@ -159,7 +159,7 @@ def main():
     except getopt.error as msg:
         usage('getopt error: ' + str(msg))
 
-    # proces option arguments
+    # process option arguments
     for o, a in opts:
         if o == '-h':
             print(__doc__)
index 3843388..390d8ac 100644 (file)
@@ -144,5 +144,5 @@ def realwork(vars, moddefns, target):
     print("<<")
     print()
     print("clean:")
-    print("\t-rm -f *.obj")
-    print("\t-rm -f $(target).exe")
+    print("\t-del /f *.obj")
+    print("\t-del /f $(target).exe")
index 75f1ccb..ed515c0 100755 (executable)
@@ -1527,7 +1527,11 @@ class Frame(object):
     def get_selected_python_frame(cls):
         '''Try to obtain the Frame for the python-related code in the selected
         frame, or None'''
-        frame = cls.get_selected_frame()
+        try:
+            frame = cls.get_selected_frame()
+        except gdb.error:
+            # No frame: Python didn't start yet
+            return None
 
         while frame:
             if frame.is_python_frame():
@@ -1668,6 +1672,10 @@ PyList()
 def move_in_stack(move_up):
     '''Move up or down the stack (for the py-up/py-down command)'''
     frame = Frame.get_selected_python_frame()
+    if not frame:
+        print('Unable to locate python frame')
+        return
+
     while frame:
         if move_up:
             iter_frame = frame.older()
@@ -1730,6 +1738,10 @@ class PyBacktraceFull(gdb.Command):
 
     def invoke(self, args, from_tty):
         frame = Frame.get_selected_python_frame()
+        if not frame:
+            print('Unable to locate python frame')
+            return
+
         while frame:
             if frame.is_python_frame():
                 frame.print_summary()
@@ -1747,8 +1759,12 @@ class PyBacktrace(gdb.Command):
 
 
     def invoke(self, args, from_tty):
-        sys.stdout.write('Traceback (most recent call first):\n')
         frame = Frame.get_selected_python_frame()
+        if not frame:
+            print('Unable to locate python frame')
+            return
+
+        sys.stdout.write('Traceback (most recent call first):\n')
         while frame:
             if frame.is_python_frame():
                 frame.print_traceback()
index 3c6c14c..da42438 100755 (executable)
@@ -475,7 +475,7 @@ class TokenEater:
                             '# File: %(filename)s, line: %(lineno)d') % d, file=fp)
                 elif options.locationstyle == options.GNU:
                     # fit as many locations on one line, as long as the
-                    # resulting line length doesn't exceeds 'options.width'
+                    # resulting line length doesn't exceed 'options.width'
                     locline = '#:'
                     for filename, lineno in v:
                         d = {'filename': filename, 'lineno': lineno}
index 635dd56..e2ef758 100644 (file)
@@ -5,7 +5,6 @@ thus has no external changes made to import-related attributes in sys.
 
 """
 from test.test_importlib import util
-from test.test_importlib.source import util as source_util
 import decimal
 import imp
 import importlib
@@ -65,11 +64,11 @@ def source_wo_bytecode(seconds, repeat):
     try:
         name = '__importlib_test_benchmark__'
         # Clears out sys.modules and puts an entry at the front of sys.path.
-        with source_util.create_modules(name) as mapping:
+        with util.create_modules(name) as mapping:
             assert not os.path.exists(imp.cache_from_source(mapping[name]))
             sys.meta_path.append(importlib.machinery.PathFinder)
             loader = (importlib.machinery.SourceFileLoader,
-                      importlib.machinery.SOURCE_SUFFIXES, True)
+                      importlib.machinery.SOURCE_SUFFIXES)
             sys.path_hooks.append(importlib.machinery.FileFinder.path_hook(loader))
             yield from bench(name, lambda: sys.modules.pop(name), repeat=repeat,
                              seconds=seconds)
@@ -102,10 +101,10 @@ def source_writing_bytecode(seconds, repeat):
     """Source writing bytecode: small"""
     assert not sys.dont_write_bytecode
     name = '__importlib_test_benchmark__'
-    with source_util.create_modules(name) as mapping:
+    with util.create_modules(name) as mapping:
         sys.meta_path.append(importlib.machinery.PathFinder)
         loader = (importlib.machinery.SourceFileLoader,
-                  importlib.machinery.SOURCE_SUFFIXES, True)
+                  importlib.machinery.SOURCE_SUFFIXES)
         sys.path_hooks.append(importlib.machinery.FileFinder.path_hook(loader))
         def cleanup():
             sys.modules.pop(name)
@@ -136,10 +135,10 @@ decimal_writing_bytecode = _writing_bytecode(decimal)
 def source_using_bytecode(seconds, repeat):
     """Source w/ bytecode: small"""
     name = '__importlib_test_benchmark__'
-    with source_util.create_modules(name) as mapping:
+    with util.create_modules(name) as mapping:
         sys.meta_path.append(importlib.machinery.PathFinder)
         loader = (importlib.machinery.SourceFileLoader,
-                importlib.machinery.SOURCE_SUFFIXES, True)
+                  importlib.machinery.SOURCE_SUFFIXES)
         sys.path_hooks.append(importlib.machinery.FileFinder.path_hook(loader))
         py_compile.compile(mapping[name])
         assert os.path.exists(imp.cache_from_source(mapping[name]))
index a61ace8..69f00c0 100644 (file)
@@ -43,6 +43,9 @@ if defined BUILDDOC (
     if errorlevel 1 goto :eof\r
 )\r
 \r
+rem Build the launcher MSI separately\r
+msbuild "%D%launcher\launcher.wixproj" /p:Platform=x86\r
+\r
 set BUILD_CMD="%D%bundle\snapshot.wixproj"\r
 if defined BUILDTEST (\r
     set BUILD_CMD=%BUILD_CMD% /p:UseTestMarker=true\r
index 2eae07a..f296e61 100644 (file)
@@ -36,6 +36,8 @@ set BUILDX64=
 set TARGET=Rebuild\r
 set TESTTARGETDIR=\r
 set PGO=\r
+set BUILDNUGET=1\r
+set BUILDZIP=1\r
 \r
 \r
 :CheckOpts\r
@@ -55,11 +57,16 @@ if "%1" EQU "--build" (set TARGET=Build) && shift && goto CheckOpts
 if "%1" EQU "-x86" (set BUILDX86=1) && shift && goto CheckOpts\r
 if "%1" EQU "-x64" (set BUILDX64=1) && shift && goto CheckOpts\r
 if "%1" EQU "--pgo" (set PGO=%~2) && shift && shift && goto CheckOpts\r
+if "%1" EQU "--skip-nuget" (set BUILDNUGET=) && shift && goto CheckOpts\r
+if "%1" EQU "--skip-zip" (set BUILDZIP=) && shift && goto CheckOpts\r
 \r
 if "%1" NEQ "" echo Invalid option: "%1" && exit /B 1\r
 \r
 if not defined BUILDX86 if not defined BUILDX64 (set BUILDX86=1) && (set BUILDX64=1)\r
 \r
+if not exist "%HG%" where hg > "%TEMP%\hg.loc" 2> nul && set /P HG= < "%TEMP%\hg.loc" & del "%TEMP%\hg.loc"\r
+if not exist "%HG%" echo Cannot find Mercurial on PATH && exit /B 1\r
+\r
 call "%D%get_externals.bat"\r
 \r
 :builddoc\r
@@ -73,8 +80,6 @@ call "%D%..\..\doc\make.bat" htmlhelp
 if errorlevel 1 goto :eof\r
 :skipdoc\r
 \r
-where hg /q || echo Cannot find Mercurial on PATH && exit /B 1\r
-\r
 where dlltool /q && goto skipdlltoolsearch\r
 set _DLLTOOL_PATH=\r
 where /R "%EXTERNALS%\" dlltool > "%TEMP%\dlltool.loc" 2> nul && set /P _DLLTOOL_PATH= < "%TEMP%\dlltool.loc" & del "%TEMP%\dlltool.loc" \r
@@ -174,28 +179,39 @@ if not "%SKIPBUILD%" EQU "1" (
     @echo off\r
 )\r
 \r
-set BUILDOPTS=/p:Platform=%1 /p:BuildForRelease=true /p:DownloadUrl=%DOWNLOAD_URL% /p:DownloadUrlBase=%DOWNLOAD_URL_BASE% /p:ReleaseUri=%RELEASE_URI%\r
+set BUILDOPTS=/p:BuildForRelease=true /p:DownloadUrl=%DOWNLOAD_URL% /p:DownloadUrlBase=%DOWNLOAD_URL_BASE% /p:ReleaseUri=%RELEASE_URI%\r
 if "%PGO%" NEQ "" set BUILDOPTS=%BUILDOPTS% /p:PGOBuildPath=%BUILD%\r
-msbuild "%D%bundle\releaselocal.wixproj" /t:Rebuild %BUILDOPTS% %CERTOPTS% /p:RebuildAll=true\r
+msbuild "%D%launcher\launcher.wixproj" /p:Platform=x86 %CERTOPTS% /p:ReleaseUri=%RELEASE_URI%\r
+msbuild "%D%bundle\releaselocal.wixproj" /t:Rebuild /p:Platform=%1 %BUILDOPTS% %CERTOPTS% /p:RebuildAll=true\r
 if errorlevel 1 exit /B\r
-msbuild "%D%bundle\releaseweb.wixproj" /t:Rebuild %BUILDOPTS% %CERTOPTS% /p:RebuildAll=false\r
+msbuild "%D%bundle\releaseweb.wixproj" /t:Rebuild /p:Platform=%1 %BUILDOPTS% %CERTOPTS% /p:RebuildAll=false\r
 if errorlevel 1 exit /B\r
 \r
-msbuild "%D%make_zip.proj" /t:Build %BUILDOPTS% %CERTOPTS%\r
+if defined BUILDZIP (\r
+    msbuild "%D%make_zip.proj" /t:Build %BUILDOPTS% %CERTOPTS% /p:OutputPath="%BUILD%en-us"\r
+    if errorlevel 1 exit /B\r
+)\r
+\r
+if defined BUILDNUGET (\r
+    msbuild "%D%..\nuget\make_pkg.proj" /t:Build /p:Configuration=Release /p:Platform=%1 /p:OutputPath="%BUILD%en-us"\r
+    if errorlevel 1 exit /B\r
+)\r
 \r
 if not "%OUTDIR%" EQU "" (\r
     mkdir "%OUTDIR%\%OUTDIR_PLAT%"\r
-    copy /Y "%BUILD%en-us\*.cab" "%OUTDIR%\%OUTDIR_PLAT%"\r
-    copy /Y "%BUILD%en-us\*.exe" "%OUTDIR%\%OUTDIR_PLAT%"\r
-    copy /Y "%BUILD%en-us\*.msi" "%OUTDIR%\%OUTDIR_PLAT%"\r
-    copy /Y "%BUILD%en-us\*.msu" "%OUTDIR%\%OUTDIR_PLAT%"\r
+    mkdir "%OUTDIR%\%OUTDIR_PLAT%\binaries"\r
+    mkdir "%OUTDIR%\%OUTDIR_PLAT%\symbols"\r
+    robocopy "%BUILD%en-us" "%OUTDIR%\%OUTDIR_PLAT%" /XF "*.wixpdb"\r
+    robocopy "%BUILD%\" "%OUTDIR%\%OUTDIR_PLAT%\binaries" *.exe *.dll *.pyd /XF "_test*" /XF "*_d.*" /XF "_freeze*" /XF "tcl*" /XF "tk*" /XF "*_test.*"\r
+    robocopy "%BUILD%\" "%OUTDIR%\%OUTDIR_PLAT%\symbols" *.pdb              /XF "_test*" /XF "*_d.*" /XF "_freeze*" /XF "tcl*" /XF "tk*" /XF "*_test.*"\r
 )\r
 \r
 exit /B 0\r
 \r
 :Help\r
-echo buildrelease.bat [--out DIR] [-x86] [-x64] [--certificate CERTNAME] [--build] [--skip-build]\r
-echo                  [--pgo COMMAND] [--skip-doc] [--download DOWNLOAD URL] [--test TARGETDIR]\r
+echo buildrelease.bat [--out DIR] [-x86] [-x64] [--certificate CERTNAME] [--build] [--pgo COMMAND]\r
+echo                  [--skip-build] [--skip-doc] [--skip-nuget] [--skip-zip]\r
+echo                  [--download DOWNLOAD URL] [--test TARGETDIR]\r
 echo                  [-h]\r
 echo.\r
 echo    --out (-o)          Specify an additional output directory for installers\r
@@ -204,6 +220,8 @@ echo    -x64                Build x64 installers
 echo    --build (-b)        Incrementally build Python rather than rebuilding\r
 echo    --skip-build (-B)   Do not build Python (just do the installers)\r
 echo    --skip-doc (-D)     Do not build documentation\r
+echo    --skip-nuget        Do not build Nuget packages\r
+echo    --skip-zip          Do not build embeddable package\r
 echo    --pgo               Build x64 installers using PGO\r
 echo    --download          Specify the full download URL for MSIs\r
 echo    --test              Specify the test directory to run the installer tests\r
index 697066b..ed79246 100644 (file)
@@ -132,4 +132,14 @@ Please &lt;a href="https://www.bing.com/search?q=how%20to%20install%20windows%20
   <String Id="FailureXPOrEarlier">Windows Vista or later is required to install and use [WixBundleName].
 
 Visit &lt;a href="https://www.python.org/"&gt;python.org&lt;/a&gt; to download Python 3.4.</String>
+
+  <String Id="FailureWS2K8R2MissingSP1">Windows Server 2008 R2 Service Pack 1 and all applicable updates are required to install [WixBundleName].
+
+Please &lt;a href="https://www.bing.com/search?q=how%20to%20install%20windows%20server%202008%20r2%20service%20pack%201"&gt;update your machine&lt;/a&gt; and then restart the installation.</String>
+  <String Id="FailureWS2K8MissingSP2">Windows Server 2008 Service Pack 2 and all applicable updates are required to install [WixBundleName].
+
+Please &lt;a href="https://www.bing.com/search?q=how%20to%20install%20windows%20server%202008%20service%20pack%202"&gt;update your machine&lt;/a&gt; and then restart the installation.</String>
+  <String Id="FailureWS2K3OrEarlier">Windows Server 2008 SP2 or later is required to install and use [WixBundleName].
+
+Visit &lt;a href="https://www.python.org/"&gt;python.org&lt;/a&gt; to download Python 3.4.</String>
 </WixLocalization>
index 1462d7b..6a67ee2 100644 (file)
@@ -327,6 +327,9 @@ class PythonBootstrapperApplication : public CBalBaseBootstrapperApplication {
         case ID_CUSTOM_INSTALL_BUTTON:
             SavePageSettings();
 
+            hr = EnsureTargetDir();
+            ExitOnFailure(hr, L"Failed to set TargetDir");
+
             hr = BalGetStringVariable(L"TargetDir", &targetDir);
             if (SUCCEEDED(hr)) {
                 // TODO: Check whether directory exists and contains another installation
@@ -3032,24 +3035,46 @@ private:
     void ValidateOperatingSystem() {
         LOC_STRING *pLocString = nullptr;
         
-        if (IsWindows7SP1OrGreater()) {
-            BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Target OS is Windows 7 SP1 or later");
-            return;
-        } else if (IsWindows7OrGreater()) {
-            BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Detected Windows 7 RTM");
-            BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Service Pack 1 is required to continue installation");
-            LocGetString(_wixLoc, L"#(loc.FailureWin7MissingSP1)", &pLocString);
-        } else if (IsWindowsVistaSP2OrGreater()) {
-            BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Target OS is Windows Vista SP2");
-            return;
-        } else if (IsWindowsVistaOrGreater()) {
-            BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Detected Windows Vista RTM or SP1");
-            BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Service Pack 2 is required to continue installation");
-            LocGetString(_wixLoc, L"#(loc.FailureVistaMissingSP2)", &pLocString);
-        } else { 
-            BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Detected Windows XP or earlier");
-            BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Windows Vista SP2 or later is required to continue installation");
-            LocGetString(_wixLoc, L"#(loc.FailureXPOrEarlier)", &pLocString);
+        if (IsWindowsServer()) {
+            if (IsWindowsVersionOrGreater(6, 1, 1)) {
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Target OS is Windows Server 2008 R2 or later");
+                return;
+            } else if (IsWindowsVersionOrGreater(6, 1, 0)) {
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Detected Windows Server 2008 R2");
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Service Pack 1 is required to continue installation");
+                LocGetString(_wixLoc, L"#(loc.FailureWS2K8R2MissingSP1)", &pLocString);
+            } else if (IsWindowsVersionOrGreater(6, 0, 2)) {
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Target OS is Windows Server 2008 SP2 or later");
+                return;
+            } else if (IsWindowsVersionOrGreater(6, 0, 0)) {
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Detected Windows Server 2008");
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Service Pack 2 is required to continue installation");
+                LocGetString(_wixLoc, L"#(loc.FailureWS2K8MissingSP2)", &pLocString);
+            } else {
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Detected Windows Server 2003 or earlier");
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Windows Server 2008 SP2 or later is required to continue installation");
+                LocGetString(_wixLoc, L"#(loc.FailureWS2K3OrEarlier)", &pLocString);
+            }
+        } else {
+            if (IsWindows7SP1OrGreater()) {
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_STANDARD, "Target OS is Windows 7 SP1 or later");
+                return;
+            } else if (IsWindows7OrGreater()) {
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Detected Windows 7 RTM");
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Service Pack 1 is required to continue installation");
+                LocGetString(_wixLoc, L"#(loc.FailureWin7MissingSP1)", &pLocString);
+            } else if (IsWindowsVistaSP2OrGreater()) {
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Target OS is Windows Vista SP2");
+                return;
+            } else if (IsWindowsVistaOrGreater()) {
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Detected Windows Vista RTM or SP1");
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Service Pack 2 is required to continue installation");
+                LocGetString(_wixLoc, L"#(loc.FailureVistaMissingSP2)", &pLocString);
+            } else { 
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Detected Windows XP or earlier");
+                BalLog(BOOTSTRAPPER_LOG_LEVEL_ERROR, "Windows Vista SP2 or later is required to continue installation");
+                LocGetString(_wixLoc, L"#(loc.FailureXPOrEarlier)", &pLocString);
+            }
         }
 
         if (pLocString && pLocString->wzText) {
index be12957..bcd3951 100644 (file)
@@ -31,7 +31,7 @@
   <PropertyGroup Label="Configuration">
     <ConfigurationType>DynamicLibrary</ConfigurationType>
     <CharacterSet>Unicode</CharacterSet>
-    <IntDir>$(PySourcePath)PCBuild\obj\$(Configuration)_$(Platform)_Setup\Bootstrap\</IntDir>
+    <IntDir>$(Py_IntDir)\$(Configuration)_$(Platform)_Setup\Bootstrap\</IntDir>
     <OutDir>$(IntDir)</OutDir>
   </PropertyGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
index aeeff3b..e0dae21 100644 (file)
         <MSBuild Projects="@(Package)" Targets="$(BuildPackagesTargets)" BuildInParallel="true" />
     </Target>
     
-    <Target Name="BuildLauncher" BeforeTargets="BeforeBuild" Condition="'$(RebuildAll)' != 'false'">
-        <!--
-        Build the launcher MSI using Exec rather than MSBuild
-        Also, never use the test marker for the launcher. It's going to corrupt things anyway, so we'll
-        just disable it by default.
-         -->
-        <Exec Command='msbuild ..\launcher\launcher.wixproj /p:Platform=x86 /p:ReleaseUri="$(ReleaseUri)" /p:OutputPath="$(BuildPath.TrimEnd(`\`))" /p:OutputSuffix=$(Platform) /p:BuildForRelease=$(BuildForRelease) /p:UseTestMarker=false'
-              ContinueOnError="false" />
-    </Target>
-    
     <Target Name="BuildBootstrapApplication" BeforeTargets="BeforeBuild">
         <Message Text="Building bootstrap app" Importance="high" />
         
index 38307e0..eda0884 100644 (file)
@@ -1,6 +1,7 @@
 <?xml version="1.0"?>
 <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
-     xmlns:bal="http://schemas.microsoft.com/wix/BalExtension">
+     xmlns:bal="http://schemas.microsoft.com/wix/BalExtension"
+     xmlns:dep="http://schemas.microsoft.com/wix/DependencyExtension">
   <Bundle Name="!(loc.FullProductName)"
           UpgradeCode="$(var.CoreUpgradeCode)"
           Version="$(var.Version)"
@@ -8,7 +9,8 @@
           Manufacturer="!(loc.Manufacturer)"
           AboutUrl="http://www.python.org/"
           DisableModify="button"
-          Compressed="no">
+          Compressed="no"
+          dep:ProviderKey="CPython-$(var.MajorVersionNumber).$(var.MinorVersionNumber)$(var.PyArchExt)$(var.PyTestExt)">
     <BootstrapperApplication Id="PythonBA" SourceFile="$(var.BootstrapApp)">
         <Payload Compressed='yes' SourceFile='Default.thm' />
         <Payload Compressed='yes' SourceFile='Default.wxl' />
index 4444f45..7dae8ca 100644 (file)
@@ -4,7 +4,7 @@
         <PackageGroup Id="launcher">
             <!-- The All Users launcher is always the 32-bit version -->
             <MsiPackage Id="launcher_AllUsers"
-                        SourceFile="launcher.msi"
+                        SourceFile="!(bindpath.build32)en-us\launcher.msi"
                         Compressed="$(var.CompressMSI)"
                         DownloadUrl="$(var.DownloadUrl)"
                         ForcePerMachine="yes"
@@ -14,7 +14,7 @@
                         InstallCondition="(InstallAllUsers or InstallLauncherAllUsers) and Include_launcher and not DetectedLauncher" />
 
             <MsiPackage Id="launcher_JustForMe"
-                        SourceFile="launcher.msi"
+                        SourceFile="!(bindpath.build32)en-us\launcher.msi"
                         Compressed="$(var.CompressMSI)"
                         DownloadUrl="$(var.DownloadUrl)"
                         ForcePerMachine="no"
diff --git a/Tools/msi/distutils.command.bdist_wininst.py b/Tools/msi/distutils.command.bdist_wininst.py
new file mode 100644 (file)
index 0000000..d586e34
--- /dev/null
@@ -0,0 +1,20 @@
+"""distutils.command.bdist_wininst
+
+Suppresses the 'bdist_wininst' command, while still allowing
+setuptools to import it without breaking."""
+
+from distutils.core import Command
+from distutils.errors import DistutilsPlatformError
+
+class bdist_wininst(Command):
+    description = "create an executable installer for MS Windows"
+
+    def initialize_options(self):
+        pass
+
+    def finalize_options(self):
+        pass
+
+    def run(self):
+        raise DistutilsPlatformError("bdist_wininst is not supported "
+            "in this Python distribution")
index 8dd0e21..306fb11 100644 (file)
@@ -7,6 +7,12 @@
         <PropertyRef Id="UpgradeTable" />
         <PropertyRef Id="REGISTRYKEY" />
         
+        <Property Id="HHExe" Value="C:\Windows\hh.exe" />
+        <CustomAction Id="SetHHExe" Property="HHCExe" Value='[WindowsFolder]\hh.exe' Execute="immediate" />
+        <InstallExecuteSequence>
+            <Custom Action="SetHHExe" Before="CostFinalize">1</Custom>
+        </InstallExecuteSequence>
+        
         <Feature Id="DefaultFeature" AllowAdvertise="no" Title="!(loc.Title)" Description="!(loc.Description)">
             <ComponentGroupRef Id="doc" Primary="yes" />
             <ComponentRef Id="OptionalFeature" />
                     <RegistryValue Name="$(var.OptionalFeatureName)_shortcut" Type="string" Value="$(var.Version)" KeyPath="yes" />
                 </RegistryKey>
                 <Shortcut Id="python.chm"
-                          Target="[#python.chm]"
+                          Target="[HHExe]"
+                          Arguments="[#python.chm]"
                           Name="!(loc.ShortcutName)"
                           Description="!(loc.ShortcutDescription)"
-                          WorkingDirectory="InstallDirectory" />
+                          WorkingDirectory="InstallDirectory"
+                          Show="maximized" />
                 <RemoveFolder Id="Remove_MenuDir" On="uninstall" />
             </Component>
             <?endif ?>
index 67fb025..01a9dcb 100644 (file)
@@ -7,6 +7,7 @@
         <OutputType>Package</OutputType>
         <DefineConstants>UpgradeCode=1B68A0EC-4DD3-5134-840E-73854B0863F1;$(DefineConstants)</DefineConstants>
         <IgnoreCommonWxlTemplates>true</IgnoreCommonWxlTemplates>
+        <SuppressICEs>ICE80</SuppressICEs>
     </PropertyGroup>
     <Import Project="..\msi.props" />
     <ItemGroup>
         <EmbeddedResource Include="*.wxl" />
     </ItemGroup>
     
+    <Target Name="_EnsurePyEx86" Condition="!Exists('$(BuildPath32)py.exe')" BeforeTargets="PrepareForBuild">
+        <MSBuild Projects="$(PySourcePath)PCBuild\pylauncher.vcxproj" Properties="Platform=Win32" />
+    </Target>
+    <Target Name="_EnsurePywEx86" Condition="!Exists('$(BuildPath32)pyw.exe')" BeforeTargets="PrepareForBuild">
+        <MSBuild Projects="$(PySourcePath)PCBuild\pywlauncher.vcxproj" Properties="Platform=Win32" />
+    </Target>
+    <Target Name="_EnsurePyShellExt86" Condition="!Exists('$(BuildPath32)pyshellext.dll')" BeforeTargets="PrepareForBuild">
+        <MSBuild Projects="$(PySourcePath)PCBuild\pyshellext.vcxproj" Properties="Platform=Win32" />
+    </Target>
+    <Target Name="_EnsurePyShellExt64" Condition="!Exists('$(BuildPath64)pyshellext.dll')" BeforeTargets="PrepareForBuild">
+        <MSBuild Projects="$(PySourcePath)PCBuild\pyshellext.vcxproj" Properties="Platform=x64" />
+    </Target>
+    
     <Import Project="..\msi.targets" />
 </Project>
\ No newline at end of file
index 80e838a..ebd875c 100644 (file)
@@ -28,7 +28,7 @@
 
             <RemoveExistingProducts After="InstallValidate">UPGRADE or REMOVE_350_LAUNCHER</RemoveExistingProducts>
         </InstallExecuteSequence>
-        
+
         <!-- Python 3.5.0 shipped with a different UpgradeCode -->
         <Upgrade Id="A71530B9-E89D-53DB-9C2D-C6D7551876D8">
             <UpgradeVersion Minimum="0.0.0.0" Property="REMOVE_350_LAUNCHER" />
index 589dee5..5b79d76 100644 (file)
                 <Condition>ALLUSERS=1</Condition>
                 <RegistryValue KeyPath="yes" Root="HKMU" Key="Software\Python\PyLauncher" Name="InstallDir" Value="[LauncherInstallDirectory]" Type="string" />
             </Component>
+
+            <Component Id="pyshellext_amd64.dll" Directory="LauncherInstallDirectory" Guid="{E7411EFD-F1DD-40EB-B0C7-4BA02BF3E75F}" Win64="yes">
+                <Condition>VersionNT64</Condition>
+                <File Id="pyshellext_amd64.dll" Name="pyshellext.amd64.dll" Source="!(bindpath.Build64)\pyshellext.dll">
+                    <Class Id="{BEA218D2-6950-497B-9434-61683EC065FE}" Advertise="no" Context="InprocServer32" ThreadingModel="apartment" />
+                </File>
+            </Component>
+            <Component Id="pyshellext_win32.dll" Directory="LauncherInstallDirectory" Guid="{C5936696-9A5A-45A0-A830-D172C3329282}">
+                <Condition>NOT VersionNT64</Condition>
+                <File Id="pyshellext_win32.dll" Name="pyshellext.win32.dll" Source="!(bindpath.Build32)\pyshellext.dll">
+                    <Class Id="{BEA218D2-6950-497B-9434-61683EC065FE}" Advertise="no" Context="InprocServer32" ThreadingModel="apartment" />
+                </File>
+            </Component>
         </ComponentGroup>
     </Fragment>
 </Wix>
index bb42255..981961a 100644 (file)
                         <Verb Id="open" TargetFile="py.exe" Argument="&quot;%L&quot; %*" />
                     </Extension>
                 </ProgId>
-                <RegistryValue Root="HKCR" Key="Python.File\shellex\DropHandler" Value="{60254CA5-953B-11CF-8C96-00AA00B8708C}" Type="string" />
+                <RegistryValue Root="HKCR" Key="Python.File\shellex\DropHandler" Value="{BEA218D2-6950-497B-9434-61683EC065FE}" Type="string" />
                 
                 <ProgId Id="Python.NoConFile" Description="!(loc.PythonNoConFileDescription)" Advertise="no" Icon="py.exe" IconIndex="1">
                     <Extension Id="pyw" ContentType="text/plain">
                         <Verb Id="open" TargetFile="pyw.exe" Argument="&quot;%L&quot; %*" />
                     </Extension>
                 </ProgId>
-                <RegistryValue Root="HKCR" Key="Python.NoConFile\shellex\DropHandler" Value="{60254CA5-953B-11CF-8C96-00AA00B8708C}" Type="string" />
+                <RegistryValue Root="HKCR" Key="Python.NoConFile\shellex\DropHandler" Value="{BEA218D2-6950-497B-9434-61683EC065FE}" Type="string" />
                 
                 <ProgId Id="Python.CompiledFile" Description="!(loc.PythonCompiledFileDescription)" Advertise="no" Icon="py.exe" IconIndex="2">
                     <Extension Id="pyc">
                     </Extension>
                     <Extension Id="pyo" />
                 </ProgId>
-                <RegistryValue Root="HKCR" Key="Python.CompiledFile\shellex\DropHandler" Value="{60254CA5-953B-11CF-8C96-00AA00B8708C}" Type="string" />
+                <RegistryValue Root="HKCR" Key="Python.CompiledFile\shellex\DropHandler" Value="{BEA218D2-6950-497B-9434-61683EC065FE}" Type="string" />
 
                 <ProgId Id="Python.ArchiveFile" Description="!(loc.PythonArchiveFileDescription)" Advertise="no" Icon="py.exe" IconIndex="1">
                     <Extension Id="pyz" ContentType="application/x-zip-compressed">
                         <Verb Id="open" TargetFile="py.exe" Argument="&quot;%L&quot; %*" />
                     </Extension>
                 </ProgId>
-                <RegistryValue Root="HKCR" Key="Python.ArchiveFile\shellex\DropHandler" Value="{60254CA5-953B-11CF-8C96-00AA00B8708C}" Type="string" />
+                <RegistryValue Root="HKCR" Key="Python.ArchiveFile\shellex\DropHandler" Value="{BEA218D2-6950-497B-9434-61683EC065FE}" Type="string" />
                 
                 <ProgId Id="Python.NoConArchiveFile" Description="!(loc.PythonNoConArchiveFileDescription)" Advertise="no" Icon="py.exe" IconIndex="1">
                     <Extension Id="pyzw" ContentType="application/x-zip-compressed">
                         <Verb Id="open" TargetFile="pyw.exe" Argument="&quot;%L&quot; %*" />
                     </Extension>
                 </ProgId>
-                <RegistryValue Root="HKCR" Key="Python.NoConArchiveFile\shellex\DropHandler" Value="{60254CA5-953B-11CF-8C96-00AA00B8708C}" Type="string" />
+                <RegistryValue Root="HKCR" Key="Python.NoConArchiveFile\shellex\DropHandler" Value="{BEA218D2-6950-497B-9434-61683EC065FE}" Type="string" />
             </Component>
         </ComponentGroup>
     </Fragment>
index fa79a8d..a992784 100644 (file)
@@ -22,7 +22,6 @@
             <?foreach ext in $(var.exts)?>
             
             <Component Id="$(var.ext).pdb" Directory="DLLs" Guid="*">
-                <Condition>SYMBOLS=1</Condition>
                 <File Name="$(var.ext).pdb" />
             </Component>
             
index d2e031f..1af6dd2 100644 (file)
         <SignOutput>false</SignOutput>
         <TargetName>python-$(PythonVersion)-embed-$(ArchName)</TargetName>
         <TargetExt>.zip</TargetExt>
-        <TargetPath>$(OutputPath)\en-us\$(TargetName)$(TargetExt)</TargetPath>
+        <TargetPath>$(OutputPath)\$(TargetName)$(TargetExt)</TargetPath>
         <CleanCommand>rmdir /q/s "$(IntermediateOutputPath)\zip_$(ArchName)"</CleanCommand>
         <Arguments>"$(PythonExe)" "$(MSBuildThisFileDirectory)\make_zip.py"</Arguments>
-        <Arguments>$(Arguments) -e -o "$(TargetPath)" -t "$(IntermediateOutputPath)\zip_$(ArchName)" -a $(ArchName)</Arguments>
+        <Arguments>$(Arguments) -e -o "$(TargetPath)" -t "$(IntermediateOutputPath)\zip_$(ArchName)" -b "$(BuildPath.TrimEnd('\'))"</Arguments>
         <Environment>set DOC_FILENAME=python$(PythonVersion).chm
 set VCREDIST_PATH=$(VS140COMNTOOLS)\..\..\VC\redist\$(Platform)\Microsoft.VC140.CRT</Environment>
     </PropertyGroup>
index 753ba0f..9db96cb 100644 (file)
@@ -7,14 +7,25 @@ import stat
 import os
 import tempfile
 
+from itertools import chain
 from pathlib import Path
 from zipfile import ZipFile, ZIP_DEFLATED
 import subprocess
 
 TKTCL_RE = re.compile(r'^(_?tk|tcl).+\.(pyd|dll)', re.IGNORECASE)
-DEBUG_RE = re.compile(r'_d\.(pyd|dll|exe)$', re.IGNORECASE)
+DEBUG_RE = re.compile(r'_d\.(pyd|dll|exe|pdb|lib)$', re.IGNORECASE)
 PYTHON_DLL_RE = re.compile(r'python\d\d?\.dll$', re.IGNORECASE)
 
+DEBUG_FILES = {
+    '_ctypes_test',
+    '_testbuffer',
+    '_testcapi',
+    '_testimportmultiple',
+    '_testmultiphase',
+    'xxlimited',
+    'python3_dstub',
+}
+
 EXCLUDE_FROM_LIBRARY = {
     '__pycache__',
     'ensurepip',
@@ -30,6 +41,12 @@ EXCLUDE_FILE_FROM_LIBRARY = {
     'bdist_wininst.py',
 }
 
+EXCLUDE_FILE_FROM_LIBS = {
+    'ssleay',
+    'libeay',
+    'python3stub',
+}
+
 def is_not_debug(p):
     if DEBUG_RE.search(p.name):
         return False
@@ -37,14 +54,7 @@ def is_not_debug(p):
     if TKTCL_RE.search(p.name):
         return False
 
-    return p.name.lower() not in {
-        '_ctypes_test.pyd',
-        '_testbuffer.pyd',
-        '_testcapi.pyd',
-        '_testimportmultiple.pyd',
-        '_testmultiphase.pyd',
-        'xxlimited.pyd',
-    }
+    return p.stem.lower() not in DEBUG_FILES
 
 def is_not_debug_or_python(p):
     return is_not_debug(p) and not PYTHON_DLL_RE.search(p.name)
@@ -68,6 +78,12 @@ def include_in_lib(p):
     suffix = p.suffix.lower()
     return suffix not in {'.pyc', '.pyo', '.exe'}
 
+def include_in_libs(p):
+    if not is_not_debug(p):
+        return False
+
+    return p.stem.lower() not in EXCLUDE_FILE_FROM_LIBS
+
 def include_in_tools(p):
     if p.is_dir() and p.name.lower() in {'scripts', 'i18n', 'pynche', 'demo', 'parser'}:
         return True
@@ -75,20 +91,23 @@ def include_in_tools(p):
     return p.suffix.lower() in {'.py', '.pyw', '.txt'}
 
 FULL_LAYOUT = [
-    ('/', 'PCBuild/$arch', 'python*.exe', is_not_debug),
-    ('/', 'PCBuild/$arch', 'python*.dll', is_not_debug),
-    ('DLLs/', 'PCBuild/$arch', '*.pyd', is_not_debug),
-    ('DLLs/', 'PCBuild/$arch', '*.dll', is_not_debug),
+    ('/', '$build', 'python.exe', is_not_debug),
+    ('/', '$build', 'pythonw.exe', is_not_debug),
+    ('/', '$build', 'python{0.major}.dll'.format(sys.version_info), is_not_debug),
+    ('/', '$build', 'python{0.major}{0.minor}.dll'.format(sys.version_info), is_not_debug),
+    ('DLLs/', '$build', '*.pyd', is_not_debug),
+    ('DLLs/', '$build', '*.dll', is_not_debug_or_python),
     ('include/', 'include', '*.h', None),
     ('include/', 'PC', 'pyconfig.h', None),
     ('Lib/', 'Lib', '**/*', include_in_lib),
+    ('libs/', '$build', '*.lib', include_in_libs),
     ('Tools/', 'Tools', '**/*', include_in_tools),
 ]
 
 EMBED_LAYOUT = [
-    ('/', 'PCBuild/$arch', 'python*.exe', is_not_debug),
-    ('/', 'PCBuild/$arch', '*.pyd', is_not_debug),
-    ('/', 'PCBuild/$arch', '*.dll', is_not_debug),
+    ('/', '$build', 'python*.exe', is_not_debug),
+    ('/', '$build', '*.pyd', is_not_debug),
+    ('/', '$build', '*.dll', is_not_debug),
     ('python{0.major}{0.minor}.zip'.format(sys.version_info), 'Lib', '**/*', include_in_lib),
 ]
 
@@ -150,18 +169,18 @@ def rglob(root, pattern, condition):
 def main():
     parser = argparse.ArgumentParser()
     parser.add_argument('-s', '--source', metavar='dir', help='The directory containing the repository root', type=Path)
-    parser.add_argument('-o', '--out', metavar='file', help='The name of the output self-extracting archive', type=Path, required=True)
+    parser.add_argument('-o', '--out', metavar='file', help='The name of the output archive', type=Path, default=None)
     parser.add_argument('-t', '--temp', metavar='dir', help='A directory to temporarily extract files into', type=Path, default=None)
     parser.add_argument('-e', '--embed', help='Create an embedding layout', action='store_true', default=False)
-    parser.add_argument('-a', '--arch', help='Specify the architecture to use (win32/amd64)', type=str, default="win32")
+    parser.add_argument('-b', '--build', help='Specify the build directory', type=Path)
     ns = parser.parse_args()
 
-    source = ns.source or (Path(__file__).parent.parent.parent)
+    source = ns.source or (Path(__file__).resolve().parent.parent.parent)
     out = ns.out
-    arch = ns.arch
+    build = ns.build
     assert isinstance(source, Path)
-    assert isinstance(out, Path)
-    assert isinstance(arch, str)
+    assert not out or isinstance(out, Path)
+    assert isinstance(build, Path)
 
     if ns.temp:
         temp = ns.temp
@@ -170,10 +189,11 @@ def main():
         temp = Path(tempfile.mkdtemp())
         delete_temp = True
 
-    try:
-        out.parent.mkdir(parents=True)
-    except FileExistsError:
-        pass
+    if out:
+        try:
+            out.parent.mkdir(parents=True)
+        except FileExistsError:
+            pass
     try:
         temp.mkdir(parents=True)
     except FileExistsError:
@@ -183,15 +203,26 @@ def main():
 
     try:
         for t, s, p, c in layout:
-            s = source / s.replace("$arch", arch)
-            copied = copy_to_layout(temp / t.rstrip('/'), rglob(s, p, c))
+            if s == '$build':
+                fs = build
+            else:
+                fs = source / s
+            files = rglob(fs, p, c)
+            extra_files = []
+            if s == 'Lib' and p == '**/*':
+                extra_files.append((
+                    source / 'tools' / 'msi' / 'distutils.command.bdist_wininst.py',
+                    Path('distutils') / 'command' / 'bdist_wininst.py'
+                ))
+            copied = copy_to_layout(temp / t.rstrip('/'), chain(files, extra_files))
             print('Copied {} files'.format(copied))
 
         with open(str(temp / 'pyvenv.cfg'), 'w') as f:
             print('applocal = true', file=f)
 
-        total = copy_to_layout(out, rglob(temp, '*', None))
-        print('Wrote {} files to {}'.format(total, out))
+        if out:
+            total = copy_to_layout(out, rglob(temp, '**/*', None))
+            print('Wrote {} files to {}'.format(total, out))
     finally:
         if delete_temp:
             shutil.rmtree(temp, True)
index 9ae6d99..0cf7c77 100644 (file)
@@ -47,7 +47,7 @@
     </ItemGroup>
 
     <PropertyGroup>
-        <IntermediateOutputPath>$(PySourcePath)PCBuild\obj\$(Configuration)_$(Platform)_Setup\$(OutputName)</IntermediateOutputPath>
+        <IntermediateOutputPath>$(Py_IntDir)\$(Configuration)_$(Platform)_Setup\$(OutputName)</IntermediateOutputPath>
         <IntermediateOutputPath Condition="'$(OutputSuffix)' != ''">$(IntermediateOutputPath)_$(OutputSuffix)</IntermediateOutputPath>
         <OutputPath Condition="'$(OutputPath)' == ''">$(BuildPath)</OutputPath>
         <OutputPath Condition="!HasTrailingSlash($(OutputPath))">$(OutputPath)\</OutputPath>
         <LinkerBindInputPaths Include="$(VS140COMNTOOLS)\..\..\VC\redist\$(Platform)\Microsoft.VC140.CRT">
             <BindName>redist</BindName>
         </LinkerBindInputPaths>
+        <LinkerBindInputPaths Include="$(BuildPath32)">
+            <BindName>build32</BindName>
+        </LinkerBindInputPaths>
+        <LinkerBindInputPaths Include="$(BuildPath64)">
+            <BindName>build64</BindName>
+        </LinkerBindInputPaths>
     </ItemGroup>
 
     <Target Name="_ValidateMsiProps" BeforeTargets="PrepareForBuild">
diff --git a/Tools/msi/purge.py b/Tools/msi/purge.py
new file mode 100644 (file)
index 0000000..76dbc49
--- /dev/null
@@ -0,0 +1,74 @@
+# Purges the Fastly cache for Windows download files
+#
+# Usage:
+#   py -3 purge.py 3.5.1rc1
+#
+
+__author__ = 'Steve Dower <steve.dower@python.org>'
+__version__ = '1.0.0'
+
+import re
+import sys
+
+from urllib.request import *
+
+VERSION_RE = re.compile(r'(\d+\.\d+\.\d+)(\w+\d+)?$')
+
+try:
+    m = VERSION_RE.match(sys.argv[1])
+    if not m:
+        print('Invalid version:', sys.argv[1])
+        print('Expected something like "3.5.1rc1"')
+        sys.exit(1)
+except LookupError:
+    print('Missing version argument. Expected something like "3.5.1rc1"')
+    sys.exit(1)
+
+URL = "https://www.python.org/ftp/python/{}/".format(m.group(1))
+
+
+FILES = [
+    "core.msi",
+    "core_d.msi",
+    "core_pdb.msi",
+    "dev.msi",
+    "dev_d.msi",
+    "doc.msi",
+    "exe.msi",
+    "exe_d.msi",
+    "exe_pdb.msi",
+    "launcher.msi",
+    "lib.msi",
+    "lib_d.msi",
+    "lib_pdb.msi",
+    "path.msi",
+    "pip.msi",
+    "tcltk.msi",
+    "tcltk_d.msi",
+    "tcltk_pdb.msi",
+    "test.msi",
+    "test_d.msi",
+    "test_pdb.msi",
+    "tools.msi",
+    "Windows6.0-KB2999226-x64.msu",
+    "Windows6.0-KB2999226-x86.msu",
+    "Windows6.1-KB2999226-x64.msu",
+    "Windows6.1-KB2999226-x86.msu",
+    "Windows8.1-KB2999226-x64.msu",
+    "Windows8.1-KB2999226-x86.msu",
+    "Windows8-RT-KB2999226-x64.msu",
+    "Windows8-RT-KB2999226-x86.msu",
+]
+PATHS = [
+    "python-{}.exe".format(m.group(0)),
+    "python-{}-webinstall.exe".format(m.group(0)),
+    "python-{}-amd64.exe".format(m.group(0)),
+    "python-{}-amd64-webinstall.exe".format(m.group(0)),
+] + ["win32{}/{}".format(m.group(2), f) for f in FILES] + ["amd64{}/{}".format(m.group(2), f) for f in FILES]
+
+print('Purged:')
+for n in PATHS:
+    u = URL + n
+    with urlopen(Request(u, method='PURGE', headers={'Fastly-Soft-Purge': 1})) as r:
+        r.read()
+    print('  ', u)
diff --git a/Tools/nuget/build.bat b/Tools/nuget/build.bat
new file mode 100644 (file)
index 0000000..120b38c
--- /dev/null
@@ -0,0 +1,55 @@
+@echo off\r
+setlocal\r
+set D=%~dp0\r
+set PCBUILD=%D%..\..\PCBuild\\r
+\r
+set BUILDX86=\r
+set BUILDX64=\r
+set REBUILD=\r
+set OUTPUT=\r
+set PACKAGES=\r
+\r
+:CheckOpts\r
+if "%~1" EQU "-h" goto Help\r
+if "%~1" EQU "-x86" (set BUILDX86=1) && shift && goto CheckOpts\r
+if "%~1" EQU "-x64" (set BUILDX64=1) && shift && goto CheckOpts\r
+if "%~1" EQU "-r" (set REBUILD=-r) && shift && goto CheckOpts\r
+if "%~1" EQU "-o" (set OUTPUT="/p:OutputPath=%~2") && shift && shift && goto CheckOpts\r
+if "%~1" EQU "--out" (set OUTPUT="/p:OutputPath=%~2") && shift && shift && goto CheckOpts\r
+if "%~1" EQU "-p" (set PACKAGES=%PACKAGES% %~2) && shift && shift && goto CheckOpts\r
+\r
+if not defined BUILDX86 if not defined BUILDX64 (set BUILDX86=1) && (set BUILDX64=1)\r
+\r
+call "%D%..\msi\get_externals.bat"\r
+call "%PCBUILD%env.bat" x86\r
+\r
+if defined PACKAGES set PACKAGES="/p:Packages=%PACKAGES%"\r
+\r
+if defined BUILDX86 (\r
+    if defined REBUILD ( call "%PCBUILD%build.bat" -e -r\r
+    ) else if not exist "%PCBUILD%win32\python.exe" call "%PCBUILD%build.bat" -e\r
+    if errorlevel 1 goto :eof\r
+\r
+    msbuild "%D%make_pkg.proj" /p:Configuration=Release /p:Platform=x86 %OUTPUT% %PACKAGES%\r
+    if errorlevel 1 goto :eof\r
+)\r
+\r
+if defined BUILDX64 (\r
+    if defined REBUILD ( call "%PCBUILD%build.bat" -p x64 -e -r\r
+    ) else if not exist "%PCBUILD%amd64\python.exe" call "%PCBUILD%build.bat" -p x64 -e\r
+    if errorlevel 1 goto :eof\r
+\r
+    msbuild "%D%make_pkg.proj" /p:Configuration=Release /p:Platform=x64 %OUTPUT% %PACKAGES%\r
+    if errorlevel 1 goto :eof\r
+)\r
+\r
+exit /B 0\r
+\r
+:Help\r
+echo build.bat [-x86] [-x64] [--out DIR] [-r] [-h]\r
+echo.\r
+echo    -x86                Build x86 installers\r
+echo    -x64                Build x64 installers\r
+echo    -r                  Rebuild rather than incremental build\r
+echo    --out [DIR]         Override output directory\r
+echo    -h                  Show usage\r
diff --git a/Tools/nuget/make_pkg.proj b/Tools/nuget/make_pkg.proj
new file mode 100644 (file)
index 0000000..81b84f9
--- /dev/null
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+    <PropertyGroup>
+        <ProjectGuid>{10487945-15D1-4092-A214-338395C4116B}</ProjectGuid>
+        <OutputName>python</OutputName>
+        <OutputName Condition="$(Platform) == 'x86'">$(OutputName)x86</OutputName>
+        <OutputSuffix></OutputSuffix>
+        <SupportSigning>false</SupportSigning>
+        <BuildForRelease Condition="$(BuildForRelease) == ''">true</BuildForRelease>
+    </PropertyGroup>
+
+    <Import Project="..\msi\msi.props" />
+
+    <PropertyGroup>
+        <Nuget Condition="$(Nuget) == ''">$(ExternalsDir)\windows-installer\nuget\nuget.exe</Nuget>
+        <NuspecVersion>$(MajorVersionNumber).$(MinorVersionNumber).$(MicroVersionNumber)</NuspecVersion>
+        <NuspecVersion Condition="$(ReleaseLevelName) != ''">$(NuspecVersion)-$(ReleaseLevelName)</NuspecVersion>
+        <SignOutput>false</SignOutput>
+        <TargetName>$(OutputName).$(NuspecVersion)</TargetName>
+        <TargetExt>.nupkg</TargetExt>
+        <IntermediateOutputPath>$(IntermediateOutputPath)\nuget_$(ArchName)</IntermediateOutputPath>
+        
+        <CleanCommand>rmdir /q/s "$(IntermediateOutputPath)"</CleanCommand>
+        
+        <PythonArguments>"$(PythonExe)" "$(MSBuildThisFileDirectory)\..\msi\make_zip.py"</PythonArguments>
+        <PythonArguments>$(PythonArguments) -t "$(IntermediateOutputPath)" -b "$(BuildPath.TrimEnd('\'))"</PythonArguments>
+        
+        <PipArguments>"$(IntermediateOutputPath)\python.exe" -B -c "import sys; sys.path.append(r'$(PySourcePath)\Lib'); import ensurepip; ensurepip._main()"</PipArguments>
+        <PackageArguments Condition="$(Packages) != ''">"$(IntermediateOutputPath)\python.exe" -B -m pip install -U $(Packages)</PackageArguments>
+        
+        <NugetArguments>"$(Nuget)" pack "$(MSBuildThisFileDirectory)\$(OutputName).nuspec"</NugetArguments>
+        <NugetArguments>$(NugetArguments) -BasePath "$(IntermediateOutputPath)"</NugetArguments>
+        <NugetArguments>$(NugetArguments) -OutputDirectory "$(OutputPath.Trim(`\`))"</NugetArguments>
+        <NugetArguments>$(NugetArguments) -Version "$(NuspecVersion)"</NugetArguments>
+        <NugetArguments>$(NugetArguments) -NoPackageAnalysis -NonInteractive</NugetArguments>
+        
+        <Environment>setlocal
+set DOC_FILENAME=python$(PythonVersion).chm
+set VCREDIST_PATH=$(VS140COMNTOOLS)\..\..\VC\redist\$(Platform)\Microsoft.VC140.CRT</Environment>
+    </PropertyGroup>
+
+    <Target Name="_NugetMissing" BeforeTargets="_Build" Condition="!Exists($(Nuget))">
+        <Error Text="$(Nuget) could not be found. Either avoid specifying the property or update your externals/windows-installer files." />
+    </Target>
+
+    <Target Name="_Build">
+        <Exec Command="$(CleanCommand)" />
+        <Exec Command="$(Environment)
+$(PythonArguments)" />
+        <Exec Command="$(PipArguments)" />
+        <Exec Command="$(PackageArguments)" Condition="$(PackageArguments) != ''" />
+        <Exec Command="$(NugetArguments)" />
+    </Target>
+
+    <Target Name="AfterBuild" />
+    <Target Name="Build" DependsOnTargets="_Build;AfterBuild" />
+</Project>
diff --git a/Tools/nuget/python.nuspec b/Tools/nuget/python.nuspec
new file mode 100644 (file)
index 0000000..b3c5c34
--- /dev/null
@@ -0,0 +1,18 @@
+<?xml version="1.0"?>
+<package >
+  <metadata>
+    <id>python</id>
+    <title>Python</title>
+    <version>0.0.0.0</version>
+    <authors>Python Software Foundation</authors>
+    <licenseUrl>https://docs.python.org/3/license.html</licenseUrl>
+    <projectUrl>https://www.python.org/</projectUrl>
+    <requireLicenseAcceptance>false</requireLicenseAcceptance>
+    <description>Installs 64-bit Python for use in build scenarios.</description>
+    <iconUrl>https://www.python.org/static/favicon.ico</iconUrl>
+    <tags>python</tags>
+  </metadata>
+  <files>
+    <file src="**\*" target="tools" />
+  </files>
+</package>
diff --git a/Tools/nuget/pythonx86.nuspec b/Tools/nuget/pythonx86.nuspec
new file mode 100644 (file)
index 0000000..b55c879
--- /dev/null
@@ -0,0 +1,18 @@
+<?xml version="1.0"?>
+<package >
+  <metadata>
+    <id>pythonx86</id>
+    <title>Python (32-bit)</title>
+    <authors>Python Software Foundation</authors>
+    <version>0.0.0.0</version>
+    <licenseUrl>https://docs.python.org/3/license.html</licenseUrl>
+    <projectUrl>https://www.python.org/</projectUrl>
+    <requireLicenseAcceptance>false</requireLicenseAcceptance>
+    <description>Installs 32-bit Python for use in build scenarios.</description>
+    <iconUrl>https://www.python.org/static/favicon.ico</iconUrl>
+    <tags>python</tags>
+  </metadata>
+  <files>
+    <file src="**\*" target="tools" />
+  </files>
+</package>
index 1e4c428..c66a0ac 100755 (executable)
@@ -88,9 +88,9 @@ def main():
     sys.exit(bad)
 
 # Change this regular expression to select a different set of files
-Wanted = '^[a-zA-Z0-9_]+\.[ch]$'
+Wanted = r'^[a-zA-Z0-9_]+\.[ch]$'
 def wanted(name):
-    return re.match(Wanted, name) >= 0
+    return re.match(Wanted, name)
 
 def recursedown(dirname):
     dbg('recursedown(%r)\n' % (dirname,))
@@ -168,6 +168,7 @@ def fix(filename):
     if filename == '-': return 0 # Done in filter mode
     f.close()
     if not g: return 0 # No changes
+    g.close()
 
     # Finishing touch -- move files
 
@@ -193,21 +194,21 @@ def fix(filename):
 
 # Tokenizing ANSI C (partly)
 
-Identifier = '\(struct \)?[a-zA-Z_][a-zA-Z0-9_]+'
-String = '"\([^\n\\"]\|\\\\.\)*"'
-Char = '\'\([^\n\\\']\|\\\\.\)*\''
-CommentStart = '/\*'
-CommentEnd = '\*/'
+Identifier = '(struct )?[a-zA-Z_][a-zA-Z0-9_]+'
+String = r'"([^\n\\"]|\\.)*"'
+Char = r"'([^\n\\']|\\.)*'"
+CommentStart = r'/\*'
+CommentEnd = r'\*/'
 
 Hexnumber = '0[xX][0-9a-fA-F]*[uUlL]*'
 Octnumber = '0[0-7]*[uUlL]*'
 Decnumber = '[1-9][0-9]*[uUlL]*'
-Intnumber = Hexnumber + '\|' + Octnumber + '\|' + Decnumber
+Intnumber = Hexnumber + '|' + Octnumber + '|' + Decnumber
 Exponent = '[eE][-+]?[0-9]+'
-Pointfloat = '\([0-9]+\.[0-9]*\|\.[0-9]+\)\(' + Exponent + '\)?'
+Pointfloat = r'([0-9]+\.[0-9]*|\.[0-9]+)(' + Exponent + r')?'
 Expfloat = '[0-9]+' + Exponent
-Floatnumber = Pointfloat + '\|' + Expfloat
-Number = Floatnumber + '\|' + Intnumber
+Floatnumber = Pointfloat + '|' + Expfloat
+Number = Floatnumber + '|' + Intnumber
 
 # Anything else is an operator -- don't list this explicitly because of '/*'
 
@@ -225,15 +226,16 @@ def initfixline():
 
 def fixline(line):
     global Program
-##  print '-->', repr(line)
+##  print('-->', repr(line))
     i = 0
     while i < len(line):
-        i = Program.search(line, i)
-        if i < 0: break
-        found = Program.group(0)
-##      if Program is InsideCommentProgram: print '...',
-##      else: print '   ',
-##      print found
+        match = Program.search(line, i)
+        if match is None: break
+        i = match.start()
+        found = match.group(0)
+##      if Program is InsideCommentProgram: print(end='... ')
+##      else: print(end='    ')
+##      print(found)
         if len(found) == 2:
             if found == '/*':
                 Program = InsideCommentProgram
@@ -247,15 +249,15 @@ def fixline(line):
                     print('Found in comment:', found)
                     i = i + n
                     continue
-                if NotInComment.has_key(found):
-##                  print 'Ignored in comment:',
-##                  print found, '-->', subst
-##                  print 'Line:', line,
+                if found in NotInComment:
+##                  print(end='Ignored in comment: ')
+##                  print(found, '-->', subst)
+##                  print('Line:', line, end='')
                     subst = found
 ##              else:
-##                  print 'Substituting in comment:',
-##                  print found, '-->', subst
-##                  print 'Line:', line,
+##                  print(end='Substituting in comment: ')
+##                  print(found, '-->', subst)
+##                  print('Line:', line, end='')
             line = line[:i] + subst + line[i+n:]
             n = len(subst)
         i = i + n
index 1f0e6f4..2a745e5 100644 (file)
 # PARTICULAR PURPOSE.
 
 m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])])
-# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
-# serial 1 (pkg-config-0.24)
-# 
-# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-#
-# As a special exception to the GNU General Public License, if you
-# distribute this file as part of a program that contains a
-# configuration script generated by Autoconf, you may include it under
-# the same distribution terms that you use for the rest of that program.
-
-# PKG_PROG_PKG_CONFIG([MIN-VERSION])
-# ----------------------------------
+dnl pkg.m4 - Macros to locate and utilise pkg-config.   -*- Autoconf -*-
+dnl serial 11 (pkg-config-0.29.1)
+dnl
+dnl Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
+dnl Copyright © 2012-2015 Dan Nicholson <dbn.lists@gmail.com>
+dnl
+dnl This program is free software; you can redistribute it and/or modify
+dnl it under the terms of the GNU General Public License as published by
+dnl the Free Software Foundation; either version 2 of the License, or
+dnl (at your option) any later version.
+dnl
+dnl This program is distributed in the hope that it will be useful, but
+dnl WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+dnl General Public License for more details.
+dnl
+dnl You should have received a copy of the GNU General Public License
+dnl along with this program; if not, write to the Free Software
+dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+dnl 02111-1307, USA.
+dnl
+dnl As a special exception to the GNU General Public License, if you
+dnl distribute this file as part of a program that contains a
+dnl configuration script generated by Autoconf, you may include it under
+dnl the same distribution terms that you use for the rest of that
+dnl program.
+
+dnl PKG_PREREQ(MIN-VERSION)
+dnl -----------------------
+dnl Since: 0.29
+dnl
+dnl Verify that the version of the pkg-config macros are at least
+dnl MIN-VERSION. Unlike PKG_PROG_PKG_CONFIG, which checks the user's
+dnl installed version of pkg-config, this checks the developer's version
+dnl of pkg.m4 when generating configure.
+dnl
+dnl To ensure that this macro is defined, also add:
+dnl m4_ifndef([PKG_PREREQ],
+dnl     [m4_fatal([must install pkg-config 0.29 or later before running autoconf/autogen])])
+dnl
+dnl See the "Since" comment for each macro you use to see what version
+dnl of the macros you require.
+m4_defun([PKG_PREREQ],
+[m4_define([PKG_MACROS_VERSION], [0.29.1])
+m4_if(m4_version_compare(PKG_MACROS_VERSION, [$1]), -1,
+    [m4_fatal([pkg.m4 version $1 or higher is required but ]PKG_MACROS_VERSION[ found])])
+])dnl PKG_PREREQ
+
+dnl PKG_PROG_PKG_CONFIG([MIN-VERSION])
+dnl ----------------------------------
+dnl Since: 0.16
+dnl
+dnl Search for the pkg-config tool and set the PKG_CONFIG variable to
+dnl first found in the path. Checks that the version of pkg-config found
+dnl is at least MIN-VERSION. If MIN-VERSION is not specified, 0.9.0 is
+dnl used since that's the first version where most current features of
+dnl pkg-config existed.
 AC_DEFUN([PKG_PROG_PKG_CONFIG],
 [m4_pattern_forbid([^_?PKG_[A-Z_]+$])
 m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
@@ -59,18 +90,19 @@ if test -n "$PKG_CONFIG"; then
                PKG_CONFIG=""
        fi
 fi[]dnl
-])# PKG_PROG_PKG_CONFIG
-
-# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
-#
-# Check to see whether a particular set of modules exists.  Similar
-# to PKG_CHECK_MODULES(), but does not set variables or print errors.
-#
-# Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
-# only at the first occurence in configure.ac, so if the first place
-# it's called might be skipped (such as if it is within an "if", you
-# have to call PKG_CHECK_EXISTS manually
-# --------------------------------------------------------------
+])dnl PKG_PROG_PKG_CONFIG
+
+dnl PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+dnl -------------------------------------------------------------------
+dnl Since: 0.18
+dnl
+dnl Check to see whether a particular set of modules exists. Similar to
+dnl PKG_CHECK_MODULES(), but does not set variables or print errors.
+dnl
+dnl Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
+dnl only at the first occurence in configure.ac, so if the first place
+dnl it's called might be skipped (such as if it is within an "if", you
+dnl have to call PKG_CHECK_EXISTS manually
 AC_DEFUN([PKG_CHECK_EXISTS],
 [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
 if test -n "$PKG_CONFIG" && \
@@ -80,8 +112,10 @@ m4_ifvaln([$3], [else
   $3])dnl
 fi])
 
-# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
-# ---------------------------------------------
+dnl _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
+dnl ---------------------------------------------
+dnl Internal wrapper calling pkg-config via PKG_CONFIG and setting
+dnl pkg_failed based on the result.
 m4_define([_PKG_CONFIG],
 [if test -n "$$1"; then
     pkg_cv_[]$1="$$1"
@@ -93,10 +127,11 @@ m4_define([_PKG_CONFIG],
  else
     pkg_failed=untried
 fi[]dnl
-])# _PKG_CONFIG
+])dnl _PKG_CONFIG
 
-# _PKG_SHORT_ERRORS_SUPPORTED
-# -----------------------------
+dnl _PKG_SHORT_ERRORS_SUPPORTED
+dnl ---------------------------
+dnl Internal check to see if pkg-config supports short errors.
 AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
 [AC_REQUIRE([PKG_PROG_PKG_CONFIG])
 if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
@@ -104,19 +139,17 @@ if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
 else
         _pkg_short_errors_supported=no
 fi[]dnl
-])# _PKG_SHORT_ERRORS_SUPPORTED
-
-
-# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
-# [ACTION-IF-NOT-FOUND])
-#
-#
-# Note that if there is a possibility the first call to
-# PKG_CHECK_MODULES might not happen, you should be sure to include an
-# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
-#
-#
-# --------------------------------------------------------------
+])dnl _PKG_SHORT_ERRORS_SUPPORTED
+
+
+dnl PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
+dnl   [ACTION-IF-NOT-FOUND])
+dnl --------------------------------------------------------------
+dnl Since: 0.4.0
+dnl
+dnl Note that if there is a possibility the first call to
+dnl PKG_CHECK_MODULES might not happen, you should be sure to include an
+dnl explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
 AC_DEFUN([PKG_CHECK_MODULES],
 [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
 AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
@@ -170,16 +203,40 @@ else
         AC_MSG_RESULT([yes])
        $3
 fi[]dnl
-])# PKG_CHECK_MODULES
+])dnl PKG_CHECK_MODULES
+
+
+dnl PKG_CHECK_MODULES_STATIC(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
+dnl   [ACTION-IF-NOT-FOUND])
+dnl ---------------------------------------------------------------------
+dnl Since: 0.29
+dnl
+dnl Checks for existence of MODULES and gathers its build flags with
+dnl static libraries enabled. Sets VARIABLE-PREFIX_CFLAGS from --cflags
+dnl and VARIABLE-PREFIX_LIBS from --libs.
+dnl
+dnl Note that if there is a possibility the first call to
+dnl PKG_CHECK_MODULES_STATIC might not happen, you should be sure to
+dnl include an explicit call to PKG_PROG_PKG_CONFIG in your
+dnl configure.ac.
+AC_DEFUN([PKG_CHECK_MODULES_STATIC],
+[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
+_save_PKG_CONFIG=$PKG_CONFIG
+PKG_CONFIG="$PKG_CONFIG --static"
+PKG_CHECK_MODULES($@)
+PKG_CONFIG=$_save_PKG_CONFIG[]dnl
+])dnl PKG_CHECK_MODULES_STATIC
 
 
-# PKG_INSTALLDIR(DIRECTORY)
-# -------------------------
-# Substitutes the variable pkgconfigdir as the location where a module
-# should install pkg-config .pc files. By default the directory is
-# $libdir/pkgconfig, but the default can be changed by passing
-# DIRECTORY. The user can override through the --with-pkgconfigdir
-# parameter.
+dnl PKG_INSTALLDIR([DIRECTORY])
+dnl -------------------------
+dnl Since: 0.27
+dnl
+dnl Substitutes the variable pkgconfigdir as the location where a module
+dnl should install pkg-config .pc files. By default the directory is
+dnl $libdir/pkgconfig, but the default can be changed by passing
+dnl DIRECTORY. The user can override through the --with-pkgconfigdir
+dnl parameter.
 AC_DEFUN([PKG_INSTALLDIR],
 [m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])])
 m4_pushdef([pkg_description],
@@ -190,16 +247,18 @@ AC_ARG_WITH([pkgconfigdir],
 AC_SUBST([pkgconfigdir], [$with_pkgconfigdir])
 m4_popdef([pkg_default])
 m4_popdef([pkg_description])
-]) dnl PKG_INSTALLDIR
+])dnl PKG_INSTALLDIR
 
 
-# PKG_NOARCH_INSTALLDIR(DIRECTORY)
-# -------------------------
-# Substitutes the variable noarch_pkgconfigdir as the location where a
-# module should install arch-independent pkg-config .pc files. By
-# default the directory is $datadir/pkgconfig, but the default can be
-# changed by passing DIRECTORY. The user can override through the
-# --with-noarch-pkgconfigdir parameter.
+dnl PKG_NOARCH_INSTALLDIR([DIRECTORY])
+dnl --------------------------------
+dnl Since: 0.27
+dnl
+dnl Substitutes the variable noarch_pkgconfigdir as the location where a
+dnl module should install arch-independent pkg-config .pc files. By
+dnl default the directory is $datadir/pkgconfig, but the default can be
+dnl changed by passing DIRECTORY. The user can override through the
+dnl --with-noarch-pkgconfigdir parameter.
 AC_DEFUN([PKG_NOARCH_INSTALLDIR],
 [m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])])
 m4_pushdef([pkg_description],
@@ -210,13 +269,15 @@ AC_ARG_WITH([noarch-pkgconfigdir],
 AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir])
 m4_popdef([pkg_default])
 m4_popdef([pkg_description])
-]) dnl PKG_NOARCH_INSTALLDIR
+])dnl PKG_NOARCH_INSTALLDIR
 
 
-# PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
-# [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
-# -------------------------------------------
-# Retrieves the value of the pkg-config variable for the given module.
+dnl PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
+dnl [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
+dnl -------------------------------------------
+dnl Since: 0.28
+dnl
+dnl Retrieves the value of the pkg-config variable for the given module.
 AC_DEFUN([PKG_CHECK_VAR],
 [AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
 AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl
@@ -225,5 +286,5 @@ _PKG_CONFIG([$1], [variable="][$3]["], [$2])
 AS_VAR_COPY([$1], [pkg_cv_][$1])
 
 AS_VAR_IF([$1], [""], [$5], [$4])dnl
-])# PKG_CHECK_VAR
+])dnl PKG_CHECK_VAR
 
index 1f5c50c..2e9ad7f 100755 (executable)
@@ -1,8 +1,8 @@
 #! /bin/sh
 # Attempt to guess a canonical system name.
-#   Copyright 1992-2014 Free Software Foundation, Inc.
+#   Copyright 1992-2016 Free Software Foundation, Inc.
 
-timestamp='2014-03-23'
+timestamp='2016-10-02'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -24,12 +24,12 @@ timestamp='2014-03-23'
 # program.  This Exception is an additional permission under section 7
 # of the GNU General Public License, version 3 ("GPLv3").
 #
-# Originally written by Per Bothner.
+# Originally written by Per Bothner; maintained since 2000 by Ben Elliston.
 #
 # You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess
 #
-# Please send patches with a ChangeLog entry to config-patches@gnu.org.
+# Please send patches to <config-patches@gnu.org>.
 
 
 me=`echo "$0" | sed -e 's,.*/,,'`
@@ -50,7 +50,7 @@ version="\
 GNU config.guess ($timestamp)
 
 Originally written by Per Bothner.
-Copyright 1992-2014 Free Software Foundation, Inc.
+Copyright 1992-2016 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -168,19 +168,29 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
        # Note: NetBSD doesn't particularly care about the vendor
        # portion of the name.  We always set it to "unknown".
        sysctl="sysctl -n hw.machine_arch"
-       UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \
-           /usr/sbin/$sysctl 2>/dev/null || echo unknown)`
+       UNAME_MACHINE_ARCH=`(uname -p 2>/dev/null || \
+           /sbin/$sysctl 2>/dev/null || \
+           /usr/sbin/$sysctl 2>/dev/null || \
+           echo unknown)`
        case "${UNAME_MACHINE_ARCH}" in
            armeb) machine=armeb-unknown ;;
            arm*) machine=arm-unknown ;;
            sh3el) machine=shl-unknown ;;
            sh3eb) machine=sh-unknown ;;
            sh5el) machine=sh5le-unknown ;;
+           earmv*)
+               arch=`echo ${UNAME_MACHINE_ARCH} | sed -e 's,^e\(armv[0-9]\).*$,\1,'`
+               endian=`echo ${UNAME_MACHINE_ARCH} | sed -ne 's,^.*\(eb\)$,\1,p'`
+               machine=${arch}${endian}-unknown
+               ;;
            *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
        esac
        # The Operating System including object format, if it has switched
-       # to ELF recently, or will in the future.
+       # to ELF recently (or will in the future) and ABI.
        case "${UNAME_MACHINE_ARCH}" in
+           earm*)
+               os=netbsdelf
+               ;;
            arm*|i386|m68k|ns32k|sh3*|sparc|vax)
                eval $set_cc_for_build
                if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
@@ -197,6 +207,13 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
                os=netbsd
                ;;
        esac
+       # Determine ABI tags.
+       case "${UNAME_MACHINE_ARCH}" in
+           earm*)
+               expr='s/^earmv[0-9]/-eabi/;s/eb$//'
+               abi=`echo ${UNAME_MACHINE_ARCH} | sed -e "$expr"`
+               ;;
+       esac
        # The OS release
        # Debian GNU/NetBSD machines have a different userland, and
        # thus, need a distinct triplet. However, they do not need
@@ -207,13 +224,13 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
                release='-gnu'
                ;;
            *)
-               release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+               release=`echo ${UNAME_RELEASE} | sed -e 's/[-_].*//' | cut -d. -f1,2`
                ;;
        esac
        # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
        # contains redundant information, the shorter form:
        # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
-       echo "${machine}-${os}${release}"
+       echo "${machine}-${os}${release}${abi}"
        exit ;;
     *:Bitrig:*:*)
        UNAME_MACHINE_ARCH=`arch | sed 's/Bitrig.//'`
@@ -223,6 +240,10 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
        UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'`
        echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE}
        exit ;;
+    *:LibertyBSD:*:*)
+       UNAME_MACHINE_ARCH=`arch | sed 's/^.*BSD\.//'`
+       echo ${UNAME_MACHINE_ARCH}-unknown-libertybsd${UNAME_RELEASE}
+       exit ;;
     *:ekkoBSD:*:*)
        echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE}
        exit ;;
@@ -235,6 +256,9 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
     *:MirBSD:*:*)
        echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE}
        exit ;;
+    *:Sortix:*:*)
+       echo ${UNAME_MACHINE}-unknown-sortix
+       exit ;;
     alpha:OSF1:*:*)
        case $UNAME_RELEASE in
        *4.0)
@@ -251,42 +275,42 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
        ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^  The alpha \(.*\) processor.*$/\1/p' | head -n 1`
        case "$ALPHA_CPU_TYPE" in
            "EV4 (21064)")
-               UNAME_MACHINE="alpha" ;;
+               UNAME_MACHINE=alpha ;;
            "EV4.5 (21064)")
-               UNAME_MACHINE="alpha" ;;
+               UNAME_MACHINE=alpha ;;
            "LCA4 (21066/21068)")
-               UNAME_MACHINE="alpha" ;;
+               UNAME_MACHINE=alpha ;;
            "EV5 (21164)")
-               UNAME_MACHINE="alphaev5" ;;
+               UNAME_MACHINE=alphaev5 ;;
            "EV5.6 (21164A)")
-               UNAME_MACHINE="alphaev56" ;;
+               UNAME_MACHINE=alphaev56 ;;
            "EV5.6 (21164PC)")
-               UNAME_MACHINE="alphapca56" ;;
+               UNAME_MACHINE=alphapca56 ;;
            "EV5.7 (21164PC)")
-               UNAME_MACHINE="alphapca57" ;;
+               UNAME_MACHINE=alphapca57 ;;
            "EV6 (21264)")
-               UNAME_MACHINE="alphaev6" ;;
+               UNAME_MACHINE=alphaev6 ;;
            "EV6.7 (21264A)")
-               UNAME_MACHINE="alphaev67" ;;
+               UNAME_MACHINE=alphaev67 ;;
            "EV6.8CB (21264C)")
-               UNAME_MACHINE="alphaev68" ;;
+               UNAME_MACHINE=alphaev68 ;;
            "EV6.8AL (21264B)")
-               UNAME_MACHINE="alphaev68" ;;
+               UNAME_MACHINE=alphaev68 ;;
            "EV6.8CX (21264D)")
-               UNAME_MACHINE="alphaev68" ;;
+               UNAME_MACHINE=alphaev68 ;;
            "EV6.9A (21264/EV69A)")
-               UNAME_MACHINE="alphaev69" ;;
+               UNAME_MACHINE=alphaev69 ;;
            "EV7 (21364)")
-               UNAME_MACHINE="alphaev7" ;;
+               UNAME_MACHINE=alphaev7 ;;
            "EV7.9 (21364A)")
-               UNAME_MACHINE="alphaev79" ;;
+               UNAME_MACHINE=alphaev79 ;;
        esac
        # A Pn.n version is a patched version.
        # A Vn.n version is a released version.
        # A Tn.n version is a released field test version.
        # A Xn.n version is an unreleased experimental baselevel.
        # 1.2 uses "1.2" for uname -r.
-       echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+       echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
        # Reset EXIT trap before exiting to avoid spurious non-zero exit code.
        exitcode=$?
        trap '' 0
@@ -359,16 +383,16 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
        exit ;;
     i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*)
        eval $set_cc_for_build
-       SUN_ARCH="i386"
+       SUN_ARCH=i386
        # If there is a compiler, see if it is configured for 64-bit objects.
        # Note that the Sun cc does not turn __LP64__ into 1 like gcc does.
        # This test works for both compilers.
-       if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+       if [ "$CC_FOR_BUILD" != no_compiler_found ]; then
            if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \
-               (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+               (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
                grep IS_64BIT_ARCH >/dev/null
            then
-               SUN_ARCH="x86_64"
+               SUN_ARCH=x86_64
            fi
        fi
        echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
@@ -393,7 +417,7 @@ case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
        exit ;;
     sun*:*:4.2BSD:*)
        UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
-       test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+       test "x${UNAME_RELEASE}" = x && UNAME_RELEASE=3
        case "`/bin/arch`" in
            sun3)
                echo m68k-sun-sunos${UNAME_RELEASE}
@@ -579,8 +603,9 @@ EOF
        else
                IBM_ARCH=powerpc
        fi
-       if [ -x /usr/bin/oslevel ] ; then
-               IBM_REV=`/usr/bin/oslevel`
+       if [ -x /usr/bin/lslpp ] ; then
+               IBM_REV=`/usr/bin/lslpp -Lqc bos.rte.libc |
+                          awk -F: '{ print $3 }' | sed s/[0-9]*$/0/`
        else
                IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
        fi
@@ -617,13 +642,13 @@ EOF
                    sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
                    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
                    case "${sc_cpu_version}" in
-                     523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
-                     528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+                     523) HP_ARCH=hppa1.0 ;; # CPU_PA_RISC1_0
+                     528) HP_ARCH=hppa1.1 ;; # CPU_PA_RISC1_1
                      532)                      # CPU_PA_RISC2_0
                        case "${sc_kernel_bits}" in
-                         32) HP_ARCH="hppa2.0n" ;;
-                         64) HP_ARCH="hppa2.0w" ;;
-                         '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+                         32) HP_ARCH=hppa2.0n ;;
+                         64) HP_ARCH=hppa2.0w ;;
+                         '') HP_ARCH=hppa2.0 ;;   # HP-UX 10.20
                        esac ;;
                    esac
                fi
@@ -662,11 +687,11 @@ EOF
                    exit (0);
                }
 EOF
-                   (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
+                   (CCOPTS="" $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy`
                    test -z "$HP_ARCH" && HP_ARCH=hppa
                fi ;;
        esac
-       if [ ${HP_ARCH} = "hppa2.0w" ]
+       if [ ${HP_ARCH} = hppa2.0w ]
        then
            eval $set_cc_for_build
 
@@ -679,12 +704,12 @@ EOF
            # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess
            # => hppa64-hp-hpux11.23
 
-           if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) |
+           if echo __LP64__ | (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) |
                grep -q __LP64__
            then
-               HP_ARCH="hppa2.0w"
+               HP_ARCH=hppa2.0w
            else
-               HP_ARCH="hppa64"
+               HP_ARCH=hppa64
            fi
        fi
        echo ${HP_ARCH}-hp-hpux${HPUX_REV}
@@ -789,14 +814,14 @@ EOF
        echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
        exit ;;
     F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
-       FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
-       FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+       FUJITSU_PROC=`uname -m | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz`
+       FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
        FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
        echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
        exit ;;
     5000:UNIX_System_V:4.*:*)
-       FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
-       FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'`
+       FUJITSU_SYS=`uname -p | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/\///'`
+       FUJITSU_REL=`echo ${UNAME_RELEASE} | tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz | sed -e 's/ /_/'`
        echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
        exit ;;
     i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
@@ -878,7 +903,7 @@ EOF
        exit ;;
     *:GNU/*:*:*)
        # other systems with GNU libc and userland
-       echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
+       echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr "[:upper:]" "[:lower:]"``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-${LIBC}
        exit ;;
     i*86:Minix:*:*)
        echo ${UNAME_MACHINE}-pc-minix
@@ -901,7 +926,7 @@ EOF
          EV68*) UNAME_MACHINE=alphaev68 ;;
        esac
        objdump --private-headers /bin/sh | grep -q ld.so.1
-       if test "$?" = 0 ; then LIBC="gnulibc1" ; fi
+       if test "$?" = 0 ; then LIBC=gnulibc1 ; fi
        echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
        exit ;;
     arc:Linux:*:* | arceb:Linux:*:*)
@@ -932,6 +957,9 @@ EOF
     crisv32:Linux:*:*)
        echo ${UNAME_MACHINE}-axis-linux-${LIBC}
        exit ;;
+    e2k:Linux:*:*)
+       echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+       exit ;;
     frv:Linux:*:*)
        echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
        exit ;;
@@ -944,6 +972,9 @@ EOF
     ia64:Linux:*:*)
        echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
        exit ;;
+    k1om:Linux:*:*)
+       echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+       exit ;;
     m32r*:Linux:*:*)
        echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
        exit ;;
@@ -969,6 +1000,9 @@ EOF
        eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'`
        test x"${CPU}" != x && { echo "${CPU}-unknown-linux-${LIBC}"; exit; }
        ;;
+    mips64el:Linux:*:*)
+       echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+       exit ;;
     openrisc*:Linux:*:*)
        echo or1k-unknown-linux-${LIBC}
        exit ;;
@@ -1001,6 +1035,9 @@ EOF
     ppcle:Linux:*:*)
        echo powerpcle-unknown-linux-${LIBC}
        exit ;;
+    riscv32:Linux:*:* | riscv64:Linux:*:*)
+       echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+       exit ;;
     s390:Linux:*:* | s390x:Linux:*:*)
        echo ${UNAME_MACHINE}-ibm-linux-${LIBC}
        exit ;;
@@ -1020,7 +1057,7 @@ EOF
        echo ${UNAME_MACHINE}-dec-linux-${LIBC}
        exit ;;
     x86_64:Linux:*:*)
-       echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
+       echo ${UNAME_MACHINE}-pc-linux-${LIBC}
        exit ;;
     xtensa*:Linux:*:*)
        echo ${UNAME_MACHINE}-unknown-linux-${LIBC}
@@ -1099,7 +1136,7 @@ EOF
        # uname -m prints for DJGPP always 'pc', but it prints nothing about
        # the processor, so we play safe by assuming i586.
        # Note: whatever this is, it MUST be the same as what config.sub
-       # prints for the "djgpp" host, or else GDB configury will decide that
+       # prints for the "djgpp" host, or else GDB configure will decide that
        # this is a cross-build.
        echo i586-pc-msdosdjgpp
        exit ;;
@@ -1248,6 +1285,9 @@ EOF
     SX-8R:SUPER-UX:*:*)
        echo sx8r-nec-superux${UNAME_RELEASE}
        exit ;;
+    SX-ACE:SUPER-UX:*:*)
+       echo sxace-nec-superux${UNAME_RELEASE}
+       exit ;;
     Power*:Rhapsody:*:*)
        echo powerpc-apple-rhapsody${UNAME_RELEASE}
        exit ;;
@@ -1261,9 +1301,9 @@ EOF
            UNAME_PROCESSOR=powerpc
        fi
        if test `echo "$UNAME_RELEASE" | sed -e 's/\..*//'` -le 10 ; then
-           if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then
+           if [ "$CC_FOR_BUILD" != no_compiler_found ]; then
                if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \
-                   (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \
+                   (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \
                    grep IS_64BIT_ARCH >/dev/null
                then
                    case $UNAME_PROCESSOR in
@@ -1285,7 +1325,7 @@ EOF
        exit ;;
     *:procnto*:*:* | *:QNX:[0123456789]*:*)
        UNAME_PROCESSOR=`uname -p`
-       if test "$UNAME_PROCESSOR" = "x86"; then
+       if test "$UNAME_PROCESSOR" = x86; then
                UNAME_PROCESSOR=i386
                UNAME_MACHINE=pc
        fi
@@ -1316,7 +1356,7 @@ EOF
        # "uname -m" is not consistent, so use $cputype instead. 386
        # is converted to i386 for consistency with other x86
        # operating systems.
-       if test "$cputype" = "386"; then
+       if test "$cputype" = 386; then
            UNAME_MACHINE=i386
        else
            UNAME_MACHINE="$cputype"
@@ -1358,7 +1398,7 @@ EOF
        echo i386-pc-xenix
        exit ;;
     i*86:skyos:*:*)
-       echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//'
+       echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE} | sed -e 's/ .*$//'`
        exit ;;
     i*86:rdos:*:*)
        echo ${UNAME_MACHINE}-pc-rdos
@@ -1369,23 +1409,25 @@ EOF
     x86_64:VMkernel:*:*)
        echo ${UNAME_MACHINE}-unknown-esx
        exit ;;
+    amd64:Isilon\ OneFS:*:*)
+       echo x86_64-unknown-onefs
+       exit ;;
 esac
 
 cat >&2 <<EOF
 $0: unable to guess system type
 
-This script, last modified $timestamp, has failed to recognize
-the operating system you are using. It is advised that you
-download the most up to date version of the config scripts from
+This script (version $timestamp), has failed to recognize the
+operating system you are using. If your script is old, overwrite
+config.guess and config.sub with the latest versions from:
 
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess
 and
-  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+  http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub
 
-If the version you run ($0) is already up to date, please
-send the following data and any information you think might be
-pertinent to <config-patches@gnu.org> in order to provide the needed
-information to handle your system.
+If $0 has already been updated, send the following data and any
+information you think might be pertinent to config-patches@gnu.org to
+provide the necessary information to handle your system.
 
 config.guess timestamp = $timestamp
 
index d654d03..3478c1f 100755 (executable)
@@ -1,8 +1,8 @@
 #! /bin/sh
 # Configuration validation subroutine script.
-#   Copyright 1992-2014 Free Software Foundation, Inc.
+#   Copyright 1992-2016 Free Software Foundation, Inc.
 
-timestamp='2014-05-01'
+timestamp='2016-11-19'
 
 # This file is free software; you can redistribute it and/or modify it
 # under the terms of the GNU General Public License as published by
@@ -25,7 +25,7 @@ timestamp='2014-05-01'
 # of the GNU General Public License, version 3 ("GPLv3").
 
 
-# Please send patches with a ChangeLog entry to config-patches@gnu.org.
+# Please send patches to <config-patches@gnu.org>.
 #
 # Configuration subroutine to validate and canonicalize a configuration type.
 # Supply the specified configuration type as an argument.
@@ -33,7 +33,7 @@ timestamp='2014-05-01'
 # Otherwise, we print the canonical config type on stdout and succeed.
 
 # You can get the latest version of this script from:
-# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD
+# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub
 
 # This file is supposed to be the same for all GNU packages
 # and recognize all the CPU types, system types and aliases
@@ -53,8 +53,7 @@ timestamp='2014-05-01'
 me=`echo "$0" | sed -e 's,.*/,,'`
 
 usage="\
-Usage: $0 [OPTION] CPU-MFR-OPSYS
-       $0 [OPTION] ALIAS
+Usage: $0 [OPTION] CPU-MFR-OPSYS or ALIAS
 
 Canonicalize a configuration name.
 
@@ -68,7 +67,7 @@ Report bugs and patches to <config-patches@gnu.org>."
 version="\
 GNU config.sub ($timestamp)
 
-Copyright 1992-2014 Free Software Foundation, Inc.
+Copyright 1992-2016 Free Software Foundation, Inc.
 
 This is free software; see the source for copying conditions.  There is NO
 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
@@ -117,8 +116,8 @@ maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
 case $maybe_os in
   nto-qnx* | linux-gnu* | linux-android* | linux-dietlibc | linux-newlib* | \
   linux-musl* | linux-uclibc* | uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | \
-  knetbsd*-gnu* | netbsd*-gnu* | \
-  kopensolaris*-gnu* | \
+  knetbsd*-gnu* | netbsd*-gnu* | netbsd*-eabi* | \
+  kopensolaris*-gnu* | cloudabi*-eabi* | \
   storm-chaos* | os2-emx* | rtmk-nova*)
     os=-$maybe_os
     basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
@@ -255,12 +254,13 @@ case $basic_machine in
        | arc | arceb \
        | arm | arm[bl]e | arme[lb] | armv[2-8] | armv[3-8][lb] | armv7[arm] \
        | avr | avr32 \
+       | ba \
        | be32 | be64 \
        | bfin \
        | c4x | c8051 | clipper \
        | d10v | d30v | dlx | dsp16xx \
-       | epiphany \
-       | fido | fr30 | frv \
+       | e2k | epiphany \
+       | fido | fr30 | frv | ft32 \
        | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
        | hexagon \
        | i370 | i860 | i960 | ia64 \
@@ -301,10 +301,12 @@ case $basic_machine in
        | open8 | or1k | or1knd | or32 \
        | pdp10 | pdp11 | pj | pjl \
        | powerpc | powerpc64 | powerpc64le | powerpcle \
+       | pru \
        | pyramid \
+       | riscv32 | riscv64 \
        | rl78 | rx \
        | score \
-       | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
+       | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[234]eb | sheb | shbe | shle | sh[1234]le | sh3ele \
        | sh64 | sh64le \
        | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \
        | sparcv8 | sparcv9 | sparcv9b | sparcv9v \
@@ -312,6 +314,7 @@ case $basic_machine in
        | tahoe | tic4x | tic54x | tic55x | tic6x | tic80 | tron \
        | ubicom32 \
        | v850 | v850e | v850e1 | v850e2 | v850es | v850e2v3 \
+       | visium \
        | we32k \
        | x86 | xc16x | xstormy16 | xtensa \
        | z8k | z80)
@@ -326,6 +329,9 @@ case $basic_machine in
        c6x)
                basic_machine=tic6x-unknown
                ;;
+       leon|leon[3-9])
+               basic_machine=sparc-$basic_machine
+               ;;
        m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x | nvptx | picochip)
                basic_machine=$basic_machine-unknown
                os=-none
@@ -371,12 +377,13 @@ case $basic_machine in
        | alphapca5[67]-* | alpha64pca5[67]-* | arc-* | arceb-* \
        | arm-*  | armbe-* | armle-* | armeb-* | armv*-* \
        | avr-* | avr32-* \
+       | ba-* \
        | be32-* | be64-* \
        | bfin-* | bs2000-* \
        | c[123]* | c30-* | [cjt]90-* | c4x-* \
        | c8051-* | clipper-* | craynv-* | cydra-* \
        | d10v-* | d30v-* | dlx-* \
-       | elxsi-* \
+       | e2k-* | elxsi-* \
        | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \
        | h8300-* | h8500-* \
        | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
@@ -422,13 +429,15 @@ case $basic_machine in
        | orion-* \
        | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
        | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* \
+       | pru-* \
        | pyramid-* \
+       | riscv32-* | riscv64-* \
        | rl78-* | romp-* | rs6000-* | rx-* \
        | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \
        | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \
        | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \
        | sparclite-* \
-       | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx?-* \
+       | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | sv1-* | sx*-* \
        | tahoe-* \
        | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \
        | tile*-* \
@@ -436,6 +445,7 @@ case $basic_machine in
        | ubicom32-* \
        | v850-* | v850e-* | v850e1-* | v850es-* | v850e2-* | v850e2v3-* \
        | vax-* \
+       | visium-* \
        | we32k-* \
        | x86-* | x86_64-* | xc16x-* | xps100-* \
        | xstormy16-* | xtensa*-* \
@@ -512,6 +522,9 @@ case $basic_machine in
                basic_machine=i386-pc
                os=-aros
                ;;
+       asmjs)
+               basic_machine=asmjs-unknown
+               ;;
        aux)
                basic_machine=m68k-apple
                os=-aux
@@ -632,6 +645,14 @@ case $basic_machine in
                basic_machine=m68k-bull
                os=-sysv3
                ;;
+       e500v[12])
+               basic_machine=powerpc-unknown
+               os=$os"spe"
+               ;;
+       e500v[12]-*)
+               basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+               os=$os"spe"
+               ;;
        ebmon29k)
                basic_machine=a29k-amd
                os=-ebmon
@@ -773,6 +794,9 @@ case $basic_machine in
                basic_machine=m68k-isi
                os=-sysv
                ;;
+       leon-*|leon[3-9]-*)
+               basic_machine=sparc-`echo $basic_machine | sed 's/-.*//'`
+               ;;
        m68knommu)
                basic_machine=m68k-unknown
                os=-linux
@@ -828,6 +852,10 @@ case $basic_machine in
                basic_machine=powerpc-unknown
                os=-morphos
                ;;
+       moxiebox)
+               basic_machine=moxie-unknown
+               os=-moxiebox
+               ;;
        msdos)
                basic_machine=i386-pc
                os=-msdos
@@ -1004,7 +1032,7 @@ case $basic_machine in
        ppc-* | ppcbe-*)
                basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
                ;;
-       ppcle | powerpclittle | ppc-le | powerpc-little)
+       ppcle | powerpclittle)
                basic_machine=powerpcle-unknown
                ;;
        ppcle-* | powerpclittle-*)
@@ -1014,7 +1042,7 @@ case $basic_machine in
                ;;
        ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
                ;;
-       ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+       ppc64le | powerpc64little)
                basic_machine=powerpc64le-unknown
                ;;
        ppc64le-* | powerpc64little-*)
@@ -1360,27 +1388,28 @@ case $os in
              | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \
              | -sym* | -kopensolaris* | -plan9* \
              | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
-             | -aos* | -aros* \
+             | -aos* | -aros* | -cloudabi* | -sortix* \
              | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
              | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
              | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \
-             | -bitrig* | -openbsd* | -solidbsd* \
+             | -bitrig* | -openbsd* | -solidbsd* | -libertybsd* \
              | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \
              | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
              | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
              | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
-             | -chorusos* | -chorusrdb* | -cegcc* \
+             | -chorusos* | -chorusrdb* | -cegcc* | -glidix* \
              | -cygwin* | -msys* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
-             | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
+             | -midipix* | -mingw32* | -mingw64* | -linux-gnu* | -linux-android* \
              | -linux-newlib* | -linux-musl* | -linux-uclibc* \
-             | -uxpv* | -beos* | -mpeix* | -udk* \
+             | -uxpv* | -beos* | -mpeix* | -udk* | -moxiebox* \
              | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \
              | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
              | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
              | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \
              | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \
              | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \
-             | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* | -tirtos*)
+             | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es* \
+             | -onefs* | -tirtos* | -phoenix* | -fuchsia*)
        # Remember, each alternative MUST END IN *, to match a version number.
                ;;
        -qnx*)
@@ -1512,6 +1541,8 @@ case $os in
                ;;
        -nacl*)
                ;;
+       -ios)
+               ;;
        -none)
                ;;
        *)
index c892a99..1f84647 100755 (executable)
--- a/configure
+++ b/configure
@@ -2,7 +2,7 @@
 # Guess values for system-dependent variables and create Makefiles.
 # Generated by GNU Autoconf 2.69 for python 3.5.
 #
-# Report bugs to <http://bugs.python.org/>.
+# Report bugs to <https://bugs.python.org/>.
 #
 #
 # Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
@@ -267,7 +267,7 @@ fi
     $as_echo "$0: be upgraded to zsh 4.3.4 or later."
   else
     $as_echo "$0: Please tell bug-autoconf@gnu.org and
-$0: http://bugs.python.org/ about your system, including
+$0: https://bugs.python.org/ about your system, including
 $0: any error possibly output before this message. Then
 $0: install a modern shell, or manually run the script
 $0: under such a shell if you do have one."
@@ -582,7 +582,7 @@ PACKAGE_NAME='python'
 PACKAGE_TARNAME='python'
 PACKAGE_VERSION='3.5'
 PACKAGE_STRING='python 3.5'
-PACKAGE_BUGREPORT='http://bugs.python.org/'
+PACKAGE_BUGREPORT='https://bugs.python.org/'
 PACKAGE_URL=''
 
 ac_unique_file="Include/object.h"
@@ -668,21 +668,25 @@ CFLAGS_NODIST
 BASECFLAGS
 OPT
 LLVM_PROF_FOUND
+target_os
+target_vendor
+target_cpu
+target
+LLVM_PROFDATA
 LLVM_PROF_ERR
 LLVM_PROF_FILE
 LLVM_PROF_MERGER
 PGO_PROF_USE_FLAG
 PGO_PROF_GEN_FLAG
 LTOFLAGS
+DEF_MAKE_RULE
+DEF_MAKE_ALL_RULE
 ABIFLAGS
 LN
 MKDIR_P
 INSTALL_DATA
 INSTALL_SCRIPT
 INSTALL_PROGRAM
-OPCODEHGEN
-PYTHON
-ASDLGEN
 ac_ct_READELF
 READELF
 ARFLAGS
@@ -742,7 +746,9 @@ UNIVERSALSDK
 CONFIG_ARGS
 SOVERSION
 VERSION
+GENERATED_COMMENT
 PYTHON_FOR_BUILD
+PYTHON_FOR_GEN
 host_os
 host_vendor
 host_cpu
@@ -751,7 +757,6 @@ build_os
 build_vendor
 build_cpu
 build
-cross_compiling
 HAS_HG
 HGBRANCH
 HGTAG
@@ -776,6 +781,7 @@ infodir
 docdir
 oldincludedir
 includedir
+runstatedir
 localstatedir
 sharedstatedir
 sysconfdir
@@ -809,6 +815,7 @@ with_suffix
 enable_shared
 enable_profiling
 with_pydebug
+enable_optimizations
 with_lto
 with_hash_algorithm
 with_address_sanitizer
@@ -886,6 +893,7 @@ datadir='${datarootdir}'
 sysconfdir='${prefix}/etc'
 sharedstatedir='${prefix}/com'
 localstatedir='${prefix}/var'
+runstatedir='${localstatedir}/run'
 includedir='${prefix}/include'
 oldincludedir='/usr/include'
 docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
@@ -1138,6 +1146,15 @@ do
   | -silent | --silent | --silen | --sile | --sil)
     silent=yes ;;
 
+  -runstatedir | --runstatedir | --runstatedi | --runstated \
+  | --runstate | --runstat | --runsta | --runst | --runs \
+  | --run | --ru | --r)
+    ac_prev=runstatedir ;;
+  -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \
+  | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \
+  | --run=* | --ru=* | --r=*)
+    runstatedir=$ac_optarg ;;
+
   -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
     ac_prev=sbindir ;;
   -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
@@ -1275,7 +1292,7 @@ fi
 for ac_var in  exec_prefix prefix bindir sbindir libexecdir datarootdir \
                datadir sysconfdir sharedstatedir localstatedir includedir \
                oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
-               libdir localedir mandir
+               libdir localedir mandir runstatedir
 do
   eval ac_val=\$$ac_var
   # Remove trailing slashes.
@@ -1428,6 +1445,7 @@ Fine tuning of the installation directories:
   --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
   --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
   --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
+  --runstatedir=DIR       modifiable per-process data [LOCALSTATEDIR/run]
   --libdir=DIR            object code libraries [EPREFIX/lib]
   --includedir=DIR        C header files [PREFIX/include]
   --oldincludedir=DIR     C header files for non-gcc [/usr/include]
@@ -1448,6 +1466,7 @@ _ACEOF
 System types:
   --build=BUILD     configure for building on BUILD [guessed]
   --host=HOST       cross-compile to build programs to run on HOST [BUILD]
+  --target=TARGET   configure for building compilers for TARGET [HOST]
 _ACEOF
 fi
 
@@ -1467,6 +1486,8 @@ Optional Features:
                           Build (MacOSX|Darwin) framework
   --enable-shared         disable/enable building shared python library
   --enable-profiling      enable C-level code profiling
+  --enable-optimizations  Enable expensive optimizations (PGO, maybe LTO,
+                          etc). Disabled by default.
   --enable-loadable-sqlite-extensions
                           support loadable extensions in _sqlite module
   --enable-ipv6           Enable ipv6 (with ipv4) support
@@ -1547,7 +1568,7 @@ Some influential environment variables:
 Use these variables to override the choices made by `configure' or to help
 it to find libraries and programs with nonstandard names/locations.
 
-Report bugs to <http://bugs.python.org/>.
+Report bugs to <https://bugs.python.org/>.
 _ACEOF
 ac_status=$?
 fi
@@ -1815,9 +1836,9 @@ $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
 $as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
     { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-( $as_echo "## -------------------------------------- ##
-## Report this to http://bugs.python.org/ ##
-## -------------------------------------- ##"
+( $as_echo "## --------------------------------------- ##
+## Report this to https://bugs.python.org/ ##
+## --------------------------------------- ##"
      ) | sed "s/^/$as_me: WARNING:     /" >&2
     ;;
 esac
@@ -2799,7 +2820,7 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
 
-if test "$abs_srcdir" != "$abs_builddir"; then
+if test "$srcdir" != . -a "$srcdir" != "$(pwd)"; then
     # If we're building out-of-tree, we need to make sure the following
     # resources get picked up before their $srcdir counterparts.
     #   Objects/ -> typeslots.inc
@@ -2876,7 +2897,6 @@ fi
 ac_config_headers="$ac_config_headers pyconfig.h"
 
 
-
 ac_aux_dir=
 for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do
   if test -f "$ac_dir/install-sh"; then
@@ -2983,6 +3003,56 @@ case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac
 # pybuilddir.txt will be created by --generate-posix-vars in the Makefile
 rm -f pybuilddir.txt
 
+for ac_prog in python$PACKAGE_VERSION python3 python
+do
+  # Extract the first word of "$ac_prog", so it can be a program name with args.
+set dummy $ac_prog; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_prog_PYTHON_FOR_GEN+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test -n "$PYTHON_FOR_GEN"; then
+  ac_cv_prog_PYTHON_FOR_GEN="$PYTHON_FOR_GEN" # Let the user override the test.
+else
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_prog_PYTHON_FOR_GEN="$ac_prog"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+fi
+fi
+PYTHON_FOR_GEN=$ac_cv_prog_PYTHON_FOR_GEN
+if test -n "$PYTHON_FOR_GEN"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON_FOR_GEN" >&5
+$as_echo "$PYTHON_FOR_GEN" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+
+  test -n "$PYTHON_FOR_GEN" && break
+done
+test -n "$PYTHON_FOR_GEN" || PYTHON_FOR_GEN="not-found"
+
+if test "$PYTHON_FOR_GEN" = not-found; then
+    PYTHON_FOR_GEN='@echo "Cannot generate $@, python not found !" && \
+    echo "To skip re-generation of $@ run <make touch> or <make -t $@>." && \
+    echo "Otherwise, set python in PATH and run configure or run <make PYTHON_FOR_GEN=python>." && false &&'
+fi
+
+
 if test "$cross_compiling" = yes; then
     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for python interpreter for cross build" >&5
 $as_echo_n "checking for python interpreter for cross build... " >&6; }
@@ -3001,14 +3071,18 @@ $as_echo_n "checking for python interpreter for cross build... " >&6; }
 $as_echo "$interp" >&6; }
        PYTHON_FOR_BUILD='_PYTHON_PROJECT_BASE=$(abs_builddir) _PYTHON_HOST_PLATFORM=$(_PYTHON_HOST_PLATFORM) PYTHONPATH=$(shell test -f pybuilddir.txt && echo $(abs_builddir)/`cat pybuilddir.txt`:)$(srcdir)/Lib:$(srcdir)/Lib/$(PLATDIR) '$interp
     fi
+    # Used to comment out stuff for rebuilding generated files
+    GENERATED_COMMENT='#'
 elif test "$cross_compiling" = maybe; then
     as_fn_error $? "Cross compiling required --host=HOST-TUPLE and --build=ARCH" "$LINENO" 5
 else
     PYTHON_FOR_BUILD='./$(BUILDPYTHON) -E'
+    GENERATED_COMMENT=''
 fi
 
 
 
+
 if test "$prefix" != "/"; then
     prefix=`echo "$prefix" | sed -e 's/\/$//g'`
 fi
@@ -5317,7 +5391,7 @@ cat >> conftest.c <<EOF
 
 EOF
 
-if $CPP conftest.c >conftest.out 2>/dev/null; then
+if $CPP $CPPFLAGS conftest.c >conftest.out 2>/dev/null; then
   PLATFORM_TRIPLET=`grep -v '^#' conftest.out | grep -v '^ *$' | tr -d '       '`
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PLATFORM_TRIPLET" >&5
 $as_echo "$PLATFORM_TRIPLET" >&6; }
@@ -6283,107 +6357,6 @@ fi
 
 
 
-for ac_prog in python$PACKAGE_VERSION python3 python
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_PYTHON+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$PYTHON"; then
-  ac_cv_prog_PYTHON="$PYTHON" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_PYTHON="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-PYTHON=$ac_cv_prog_PYTHON
-if test -n "$PYTHON"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON" >&5
-$as_echo "$PYTHON" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$PYTHON" && break
-done
-test -n "$PYTHON" || PYTHON="not-found"
-
-if test "$PYTHON" = not-found; then
-    ASDLGEN="@echo python: $PYTHON! cannot run \$(srcdir)/Parser/asdl_c.py #"
-else
-    ASDLGEN="$PYTHON"
-fi
-
-
-for ac_prog in python$PACKAGE_VERSION python3 python
-do
-  # Extract the first word of "$ac_prog", so it can be a program name with args.
-set dummy $ac_prog; ac_word=$2
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
-$as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_PYTHON+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  if test -n "$PYTHON"; then
-  ac_cv_prog_PYTHON="$PYTHON" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-    for ac_exec_ext in '' $ac_executable_extensions; do
-  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_PYTHON="$ac_prog"
-    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-  done
-IFS=$as_save_IFS
-
-fi
-fi
-PYTHON=$ac_cv_prog_PYTHON
-if test -n "$PYTHON"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $PYTHON" >&5
-$as_echo "$PYTHON" >&6; }
-else
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
-$as_echo "no" >&6; }
-fi
-
-
-  test -n "$PYTHON" && break
-done
-test -n "$PYTHON" || PYTHON="not-found"
-
-if test "$PYTHON" = not-found; then
-    OPCODEHGEN="@echo python: $PYTHON! cannot run Tools/scripts/generate_opcode_h.py"
-else
-    OPCODEHGEN="$PYTHON"
-fi
-
-
-
 case $MACHDEP in
 bsdos*|hp*|HP*)
        # install -d does not work on BSDI or HP-UX
@@ -6566,6 +6539,44 @@ $as_echo "no" >&6; }
 fi
 
 
+# Enable optimization flags
+
+
+Py_OPT='false'
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for --enable-optimizations" >&5
+$as_echo_n "checking for --enable-optimizations... " >&6; }
+# Check whether --enable-optimizations was given.
+if test "${enable_optimizations+set}" = set; then :
+  enableval=$enable_optimizations;
+if test "$withval" != no
+then
+  Py_OPT='true'
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
+$as_echo "yes" >&6; };
+else
+  Py_OPT='false'
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; };
+fi
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
+fi
+
+if test "$Py_OPT" = 'true' ; then
+  # Intentionally not forcing Py_LTO='true' here.  Too many toolchains do not
+  # compile working code using it and both test_distutils and test_gdb are
+  # broken when you do managed to get a toolchain that works with it.  People
+  # who want LTO need to use --with-lto themselves.
+  DEF_MAKE_ALL_RULE="profile-opt"
+  REQUIRE_PGO="yes"
+  DEF_MAKE_RULE="build_all"
+else
+  DEF_MAKE_ALL_RULE="build_all"
+  REQUIRE_PGO="no"
+  DEF_MAKE_RULE="all"
+fi
+
 # Enable LTO flags
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for --with-lto" >&5
@@ -6614,25 +6625,84 @@ fi
 
 
 
+# Make this work on systems where llvm tools are not installed with their
+# normal names in the default $PATH (ie: Ubuntu).  They exist under the
+# non-suffixed name in their versioned llvm directory.
+llvm_bin_dir=''
+llvm_path="${PATH}"
+if test "${CC}" = "clang"
+then
+  clang_bin=`which clang`
+  # Some systems install clang elsewhere as a symlink to the real path
+  # which is where the related llvm tools are located.
+  if test -L "${clang_bin}"
+  then
+    clang_dir=`dirname "${clang_bin}"`
+    clang_bin=`readlink "${clang_bin}"`
+    llvm_bin_dir="${clang_dir}/"`dirname "${clang_bin}"`
+    llvm_path="${llvm_path}${PATH_SEPARATOR}${llvm_bin_dir}"
+  fi
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking target system type" >&5
+$as_echo_n "checking target system type... " >&6; }
+if ${ac_cv_target+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  if test "x$target_alias" = x; then
+  ac_cv_target=$ac_cv_host
+else
+  ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` ||
+    as_fn_error $? "$SHELL $ac_aux_dir/config.sub $target_alias failed" "$LINENO" 5
+fi
 
-# Extract the first word of "llvm-profdata", so it can be a program name with args.
-set dummy llvm-profdata; ac_word=$2
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_target" >&5
+$as_echo "$ac_cv_target" >&6; }
+case $ac_cv_target in
+*-*-*) ;;
+*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5;;
+esac
+target=$ac_cv_target
+ac_save_IFS=$IFS; IFS='-'
+set x $ac_cv_target
+shift
+target_cpu=$1
+target_vendor=$2
+shift; shift
+# Remember, the first character of IFS is used to create $*,
+# except with old shells:
+target_os=$*
+IFS=$ac_save_IFS
+case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac
+
+
+# The aliases save the names the user supplied, while $host etc.
+# will get canonicalized.
+test -n "$target_alias" &&
+  test "$program_prefix$program_suffix$program_transform_name" = \
+    NONENONEs,x,x, &&
+  program_prefix=${target_alias}-
+# Extract the first word of "$target_alias-llvm-profdata", so it can be a program name with args.
+set dummy $target_alias-llvm-profdata; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if ${ac_cv_prog_LLVM_PROF_FOUND+:} false; then :
+if ${ac_cv_path_LLVM_PROFDATA+:} false; then :
   $as_echo_n "(cached) " >&6
 else
-  if test -n "$LLVM_PROF_FOUND"; then
-  ac_cv_prog_LLVM_PROF_FOUND="$LLVM_PROF_FOUND" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
+  case $LLVM_PROFDATA in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_LLVM_PROFDATA="$LLVM_PROFDATA" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in ${llvm_path}
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
   if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_LLVM_PROF_FOUND="found"
+    ac_cv_path_LLVM_PROFDATA="$as_dir/$ac_word$ac_exec_ext"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
@@ -6640,30 +6710,105 @@ done
   done
 IFS=$as_save_IFS
 
-  test -z "$ac_cv_prog_LLVM_PROF_FOUND" && ac_cv_prog_LLVM_PROF_FOUND="not-found"
+  ;;
+esac
+fi
+LLVM_PROFDATA=$ac_cv_path_LLVM_PROFDATA
+if test -n "$LLVM_PROFDATA"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LLVM_PROFDATA" >&5
+$as_echo "$LLVM_PROFDATA" >&6; }
+else
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
+$as_echo "no" >&6; }
 fi
+
+
+if test -z "$ac_cv_path_LLVM_PROFDATA"; then
+  if test "$build" = "$target"; then
+    ac_pt_LLVM_PROFDATA=$LLVM_PROFDATA
+    # Extract the first word of "llvm-profdata", so it can be a program name with args.
+set dummy llvm-profdata; ac_word=$2
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
+$as_echo_n "checking for $ac_word... " >&6; }
+if ${ac_cv_path_ac_pt_LLVM_PROFDATA+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  case $ac_pt_LLVM_PROFDATA in
+  [\\/]* | ?:[\\/]*)
+  ac_cv_path_ac_pt_LLVM_PROFDATA="$ac_pt_LLVM_PROFDATA" # Let the user override the test with a path.
+  ;;
+  *)
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in ${llvm_path}
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+    for ac_exec_ext in '' $ac_executable_extensions; do
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+    ac_cv_path_ac_pt_LLVM_PROFDATA="$as_dir/$ac_word$ac_exec_ext"
+    $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
+    break 2
+  fi
+done
+  done
+IFS=$as_save_IFS
+
+  test -z "$ac_cv_path_ac_pt_LLVM_PROFDATA" && ac_cv_path_ac_pt_LLVM_PROFDATA="''"
+  ;;
+esac
 fi
-LLVM_PROF_FOUND=$ac_cv_prog_LLVM_PROF_FOUND
-if test -n "$LLVM_PROF_FOUND"; then
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $LLVM_PROF_FOUND" >&5
-$as_echo "$LLVM_PROF_FOUND" >&6; }
+ac_pt_LLVM_PROFDATA=$ac_cv_path_ac_pt_LLVM_PROFDATA
+if test -n "$ac_pt_LLVM_PROFDATA"; then
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_LLVM_PROFDATA" >&5
+$as_echo "$ac_pt_LLVM_PROFDATA" >&6; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
 $as_echo "no" >&6; }
 fi
 
+    LLVM_PROFDATA=$ac_pt_LLVM_PROFDATA
+  else
+    LLVM_PROFDATA="''"
+  fi
+else
+  LLVM_PROFDATA="$ac_cv_path_LLVM_PROFDATA"
+fi
+
 
+if test -n "${LLVM_PROFDATA}" -a -x "${LLVM_PROFDATA}"
+then
+  LLVM_PROF_FOUND="found"
+else
+  LLVM_PROF_FOUND="not-found"
+fi
+if test "$ac_sys_system" = "Darwin" -a "${LLVM_PROF_FOUND}" = "not-found"
+then
+  found_llvm_profdata=`/usr/bin/xcrun -find llvm-profdata 2>/dev/null`
+  if test -n "${found_llvm_profdata}"
+  then
+    # llvm-profdata isn't directly in $PATH in some cases.
+    # https://apple.stackexchange.com/questions/197053/
+    LLVM_PROFDATA='/usr/bin/xcrun llvm-profdata'
+    LLVM_PROF_FOUND=found
+    { $as_echo "$as_me:${as_lineno-$LINENO}: llvm-profdata found via xcrun: ${LLVM_PROFDATA}" >&5
+$as_echo "$as_me: llvm-profdata found via xcrun: ${LLVM_PROFDATA}" >&6;}
+  fi
+fi
 LLVM_PROF_ERR=no
 case $CC in
   *clang*)
     # Any changes made here should be reflected in the GCC+Darwin case below
     PGO_PROF_GEN_FLAG="-fprofile-instr-generate"
     PGO_PROF_USE_FLAG="-fprofile-instr-use=code.profclangd"
-    LLVM_PROF_MERGER="llvm-profdata merge -output=code.profclangd *.profclangr"
+    LLVM_PROF_MERGER="${LLVM_PROFDATA} merge -output=code.profclangd *.profclangr"
     LLVM_PROF_FILE="LLVM_PROFILE_FILE=\"code-%p.profclangr\""
     if test $LLVM_PROF_FOUND = not-found
     then
       LLVM_PROF_ERR=yes
+      if test "${REQUIRE_PGO}" = "yes"
+      then
+        as_fn_error $? "llvm-profdata is required for a --enable-optimizations build but could not be found." "$LINENO" 5
+      fi
     fi
     ;;
   *gcc*)
@@ -6671,11 +6816,15 @@ case $CC in
       Darwin*)
         PGO_PROF_GEN_FLAG="-fprofile-instr-generate"
         PGO_PROF_USE_FLAG="-fprofile-instr-use=code.profclangd"
-        LLVM_PROF_MERGER="llvm-profdata merge -output=code.profclangd *.profclangr"
+        LLVM_PROF_MERGER="${LLVM_PROFDATA} merge -output=code.profclangd *.profclangr"
         LLVM_PROF_FILE="LLVM_PROFILE_FILE=\"code-%p.profclangr\""
-        if test $LLVM_PROF_FOUND = not-found
+        if test "${LLVM_PROF_FOUND}" = "not-found"
         then
           LLVM_PROF_ERR=yes
+          if test "${REQUIRE_PGO}" = "yes"
+         then
+           as_fn_error $? "llvm-profdata is required for a --enable-optimizations build but could not be found." "$LINENO" 5
+         fi
         fi
         ;;
       *)
@@ -7114,7 +7263,7 @@ $as_echo "$CC" >&6; }
         # Calculate an appropriate deployment target for this build:
         # The deployment target value is used explicitly to enable certain
         # features are enabled (such as builtin libedit support for readline)
-        # through the use of Apple's Availabiliy Macros and is used as a
+        # through the use of Apple's Availability Macros and is used as a
         # component of the string returned by distutils.get_platform().
         #
         # Use the value from:
@@ -7565,7 +7714,7 @@ unistd.h utime.h \
 poll.h sys/devpoll.h sys/epoll.h sys/poll.h \
 sys/audioio.h sys/xattr.h sys/bsdtty.h sys/event.h sys/file.h sys/ioctl.h \
 sys/kern_control.h sys/loadavg.h sys/lock.h sys/mkdev.h sys/modem.h \
-sys/param.h sys/select.h sys/sendfile.h sys/socket.h sys/statvfs.h \
+sys/param.h sys/random.h sys/select.h sys/sendfile.h sys/socket.h sys/statvfs.h \
 sys/stat.h sys/syscall.h sys/sys_domain.h sys/termio.h sys/time.h \
 sys/times.h sys/types.h sys/uio.h sys/un.h sys/utsname.h sys/wait.h pty.h \
 libutil.h sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \
@@ -9077,8 +9226,8 @@ if test -z "$LDSHARED"
 then
        case $ac_sys_system/$ac_sys_release in
        AIX*)
-               BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:\$(srcdir)/Modules/python.exp"
-               LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp"
+               BLDSHARED="Modules/ld_so_aix \$(CC) -bI:Modules/python.exp"
+               LDSHARED="\$(LIBPL)/ld_so_aix \$(CC) -bI:\$(LIBPL)/python.exp"
                ;;
        IRIX/5*) LDSHARED="ld -shared";;
        IRIX*/6*) LDSHARED="ld ${SGI_ABI} -shared -all";;
@@ -9480,48 +9629,6 @@ _ACEOF
 
 fi
        # Dynamic linking for HP-UX
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for RAND_egd in -lcrypto" >&5
-$as_echo_n "checking for RAND_egd in -lcrypto... " >&6; }
-if ${ac_cv_lib_crypto_RAND_egd+:} false; then :
-  $as_echo_n "(cached) " >&6
-else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lcrypto  $LIBS"
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-/* Override any GCC internal prototype to avoid an error.
-   Use char because int might match the return type of a GCC
-   builtin and then its argument prototype would still apply.  */
-#ifdef __cplusplus
-extern "C"
-#endif
-char RAND_egd ();
-int
-main ()
-{
-return RAND_egd ();
-  ;
-  return 0;
-}
-_ACEOF
-if ac_fn_c_try_link "$LINENO"; then :
-  ac_cv_lib_crypto_RAND_egd=yes
-else
-  ac_cv_lib_crypto_RAND_egd=no
-fi
-rm -f core conftest.err conftest.$ac_objext \
-    conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
-fi
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_crypto_RAND_egd" >&5
-$as_echo "$ac_cv_lib_crypto_RAND_egd" >&6; }
-if test "x$ac_cv_lib_crypto_RAND_egd" = xyes; then :
-
-$as_echo "#define HAVE_RAND_EGD 1" >>confdefs.h
-
-fi
-
 
 # only check for sem_init if thread support is requested
 if test "$with_threads" = "yes" -o -z "$with_threads"; then
@@ -12661,6 +12768,8 @@ int main()
         break;
       }
     }
+    freeaddrinfo(aitop);
+    aitop = NULL;
   }
 
   if (!(inet4 == 0 || inet4 == 2))
@@ -16960,7 +17069,7 @@ $config_files
 Configuration headers:
 $config_headers
 
-Report bugs to <http://bugs.python.org/>."
+Report bugs to <https://bugs.python.org/>."
 
 _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
@@ -17714,3 +17823,13 @@ $SHELL $srcdir/Modules/makesetup -c $srcdir/Modules/config.c.in \
                        -s Modules Modules/Setup.config \
                        Modules/Setup.local Modules/Setup
 mv config.c Modules
+
+if test "$Py_OPT" = 'false' -a "$Py_DEBUG" != 'true'; then
+    echo "" >&6
+    echo "" >&6
+    echo "If you want a release build with all optimizations active (LTO, PGO, etc),"
+    echo "please run ./configure --enable-optimizations" >&6
+    echo "" >&6
+    echo "" >&6
+fi
+
index 1c07c05..49d1a37 100644 (file)
@@ -7,10 +7,10 @@ m4_define(PYTHON_VERSION, 3.5)
 
 AC_PREREQ(2.65)
 
-AC_INIT(python, PYTHON_VERSION, http://bugs.python.org/)
+AC_INIT(python, PYTHON_VERSION, https://bugs.python.org/)
 
 AC_SUBST(BASECPPFLAGS)
-if test "$abs_srcdir" != "$abs_builddir"; then
+if test "$srcdir" != . -a "$srcdir" != "$(pwd)"; then
     # If we're building out-of-tree, we need to make sure the following
     # resources get picked up before their $srcdir counterparts.
     #   Objects/ -> typeslots.inc
@@ -49,7 +49,6 @@ fi
 AC_CONFIG_SRCDIR([Include/object.h])
 AC_CONFIG_HEADER(pyconfig.h)
 
-AC_SUBST(cross_compiling)
 AC_CANONICAL_HOST
 AC_SUBST(build)
 AC_SUBST(host)
@@ -57,6 +56,14 @@ AC_SUBST(host)
 # pybuilddir.txt will be created by --generate-posix-vars in the Makefile
 rm -f pybuilddir.txt
 
+AC_CHECK_PROGS(PYTHON_FOR_GEN, python$PACKAGE_VERSION python3 python, not-found)
+if test "$PYTHON_FOR_GEN" = not-found; then
+    PYTHON_FOR_GEN='@echo "Cannot generate $@, python not found !" && \
+    echo "To skip re-generation of $@ run <make touch> or <make -t $@>." && \
+    echo "Otherwise, set python in PATH and run configure or run <make PYTHON_FOR_GEN=python>." && false &&'
+fi
+AC_SUBST(PYTHON_FOR_GEN)
+
 if test "$cross_compiling" = yes; then
     AC_MSG_CHECKING([for python interpreter for cross build])
     if test -z "$PYTHON_FOR_BUILD"; then
@@ -73,12 +80,16 @@ if test "$cross_compiling" = yes; then
         AC_MSG_RESULT($interp)
        PYTHON_FOR_BUILD='_PYTHON_PROJECT_BASE=$(abs_builddir) _PYTHON_HOST_PLATFORM=$(_PYTHON_HOST_PLATFORM) PYTHONPATH=$(shell test -f pybuilddir.txt && echo $(abs_builddir)/`cat pybuilddir.txt`:)$(srcdir)/Lib:$(srcdir)/Lib/$(PLATDIR) '$interp
     fi
+    # Used to comment out stuff for rebuilding generated files
+    GENERATED_COMMENT='#'
 elif test "$cross_compiling" = maybe; then
     AC_MSG_ERROR([Cross compiling required --host=HOST-TUPLE and --build=ARCH])
 else
     PYTHON_FOR_BUILD='./$(BUILDPYTHON) -E'
+    GENERATED_COMMENT=''
 fi
 AC_SUBST(PYTHON_FOR_BUILD)
+AC_SUBST(GENERATED_COMMENT)
 
 dnl Ensure that if prefix is specified, it does not end in a slash. If
 dnl it does, we get path names containing '//' which is both ugly and
@@ -859,7 +870,7 @@ cat >> conftest.c <<EOF
 
 EOF
 
-if $CPP conftest.c >conftest.out 2>/dev/null; then
+if $CPP $CPPFLAGS conftest.c >conftest.out 2>/dev/null; then
   PLATFORM_TRIPLET=`grep -v '^#' conftest.out | grep -v '^ *$' | tr -d '       '`
   AC_MSG_RESULT([$PLATFORM_TRIPLET])
 else
@@ -1178,23 +1189,6 @@ if test "$cross_compiling" = yes; then
 fi
 AC_SUBST(READELF)
 
-AC_SUBST(ASDLGEN)
-AC_CHECK_PROGS(PYTHON, python$PACKAGE_VERSION python3 python, not-found)
-if test "$PYTHON" = not-found; then
-    ASDLGEN="@echo python: $PYTHON! cannot run \$(srcdir)/Parser/asdl_c.py #"
-else
-    ASDLGEN="$PYTHON"
-fi
-
-AC_SUBST(OPCODEHGEN)
-AC_CHECK_PROGS(PYTHON, python$PACKAGE_VERSION python3 python, not-found)
-if test "$PYTHON" = not-found; then
-    OPCODEHGEN="@echo python: $PYTHON! cannot run Tools/scripts/generate_opcode_h.py"
-else
-    OPCODEHGEN="$PYTHON"
-fi
-
-
 
 case $MACHDEP in
 bsdos*|hp*|HP*)
@@ -1236,6 +1230,36 @@ else AC_MSG_RESULT(no); Py_DEBUG='false'
 fi],
 [AC_MSG_RESULT(no)])
 
+# Enable optimization flags
+AC_SUBST(DEF_MAKE_ALL_RULE)
+AC_SUBST(DEF_MAKE_RULE)
+Py_OPT='false'
+AC_MSG_CHECKING(for --enable-optimizations)
+AC_ARG_ENABLE(optimizations, AS_HELP_STRING([--enable-optimizations], [Enable expensive optimizations (PGO, maybe LTO, etc).  Disabled by default.]),
+[
+if test "$withval" != no
+then
+  Py_OPT='true'
+  AC_MSG_RESULT(yes);
+else
+  Py_OPT='false'
+  AC_MSG_RESULT(no);
+fi],
+[AC_MSG_RESULT(no)])
+if test "$Py_OPT" = 'true' ; then
+  # Intentionally not forcing Py_LTO='true' here.  Too many toolchains do not
+  # compile working code using it and both test_distutils and test_gdb are
+  # broken when you do managed to get a toolchain that works with it.  People
+  # who want LTO need to use --with-lto themselves.
+  DEF_MAKE_ALL_RULE="profile-opt"
+  REQUIRE_PGO="yes"
+  DEF_MAKE_RULE="build_all"
+else
+  DEF_MAKE_ALL_RULE="build_all"
+  REQUIRE_PGO="no"
+  DEF_MAKE_RULE="all"
+fi
+
 # Enable LTO flags
 AC_SUBST(LTOFLAGS)
 AC_MSG_CHECKING(for --with-lto)
@@ -1275,19 +1299,60 @@ AC_SUBST(PGO_PROF_USE_FLAG)
 AC_SUBST(LLVM_PROF_MERGER)
 AC_SUBST(LLVM_PROF_FILE)
 AC_SUBST(LLVM_PROF_ERR)
+# Make this work on systems where llvm tools are not installed with their
+# normal names in the default $PATH (ie: Ubuntu).  They exist under the
+# non-suffixed name in their versioned llvm directory.
+llvm_bin_dir=''
+llvm_path="${PATH}"
+if test "${CC}" = "clang"
+then
+  clang_bin=`which clang`
+  # Some systems install clang elsewhere as a symlink to the real path
+  # which is where the related llvm tools are located.
+  if test -L "${clang_bin}"
+  then
+    clang_dir=`dirname "${clang_bin}"`
+    clang_bin=`readlink "${clang_bin}"`
+    llvm_bin_dir="${clang_dir}/"`dirname "${clang_bin}"`
+    llvm_path="${llvm_path}${PATH_SEPARATOR}${llvm_bin_dir}"
+  fi
+fi
+AC_SUBST(LLVM_PROFDATA)
+AC_PATH_TARGET_TOOL(LLVM_PROFDATA, llvm-profdata, '', ${llvm_path})
 AC_SUBST(LLVM_PROF_FOUND)
-AC_CHECK_PROG(LLVM_PROF_FOUND, llvm-profdata, found, not-found)
+if test -n "${LLVM_PROFDATA}" -a -x "${LLVM_PROFDATA}"
+then
+  LLVM_PROF_FOUND="found"
+else
+  LLVM_PROF_FOUND="not-found"
+fi
+if test "$ac_sys_system" = "Darwin" -a "${LLVM_PROF_FOUND}" = "not-found"
+then
+  found_llvm_profdata=`/usr/bin/xcrun -find llvm-profdata 2>/dev/null`
+  if test -n "${found_llvm_profdata}"
+  then
+    # llvm-profdata isn't directly in $PATH in some cases.
+    # https://apple.stackexchange.com/questions/197053/
+    LLVM_PROFDATA='/usr/bin/xcrun llvm-profdata'
+    LLVM_PROF_FOUND=found
+    AC_MSG_NOTICE([llvm-profdata found via xcrun: ${LLVM_PROFDATA}])
+  fi
+fi
 LLVM_PROF_ERR=no
 case $CC in
   *clang*)
     # Any changes made here should be reflected in the GCC+Darwin case below
     PGO_PROF_GEN_FLAG="-fprofile-instr-generate"
     PGO_PROF_USE_FLAG="-fprofile-instr-use=code.profclangd"
-    LLVM_PROF_MERGER="llvm-profdata merge -output=code.profclangd *.profclangr"
+    LLVM_PROF_MERGER="${LLVM_PROFDATA} merge -output=code.profclangd *.profclangr"
     LLVM_PROF_FILE="LLVM_PROFILE_FILE=\"code-%p.profclangr\""
     if test $LLVM_PROF_FOUND = not-found
     then
       LLVM_PROF_ERR=yes
+      if test "${REQUIRE_PGO}" = "yes"
+      then
+        AC_MSG_ERROR([llvm-profdata is required for a --enable-optimizations build but could not be found.])
+      fi
     fi
     ;;
   *gcc*)
@@ -1295,11 +1360,15 @@ case $CC in
       Darwin*)
         PGO_PROF_GEN_FLAG="-fprofile-instr-generate"
         PGO_PROF_USE_FLAG="-fprofile-instr-use=code.profclangd"
-        LLVM_PROF_MERGER="llvm-profdata merge -output=code.profclangd *.profclangr"
+        LLVM_PROF_MERGER="${LLVM_PROFDATA} merge -output=code.profclangd *.profclangr"
         LLVM_PROF_FILE="LLVM_PROFILE_FILE=\"code-%p.profclangr\""
-        if test $LLVM_PROF_FOUND = not-found
+        if test "${LLVM_PROF_FOUND}" = "not-found"
         then
           LLVM_PROF_ERR=yes
+          if test "${REQUIRE_PGO}" = "yes"
+         then
+           AC_MSG_ERROR([llvm-profdata is required for a --enable-optimizations build but could not be found.])
+         fi
         fi
         ;;
       *)
@@ -1617,7 +1686,7 @@ yes)
         # Calculate an appropriate deployment target for this build:
         # The deployment target value is used explicitly to enable certain
         # features are enabled (such as builtin libedit support for readline)
-        # through the use of Apple's Availabiliy Macros and is used as a
+        # through the use of Apple's Availability Macros and is used as a
         # component of the string returned by distutils.get_platform().
         #
         # Use the value from:
@@ -1877,7 +1946,7 @@ unistd.h utime.h \
 poll.h sys/devpoll.h sys/epoll.h sys/poll.h \
 sys/audioio.h sys/xattr.h sys/bsdtty.h sys/event.h sys/file.h sys/ioctl.h \
 sys/kern_control.h sys/loadavg.h sys/lock.h sys/mkdev.h sys/modem.h \
-sys/param.h sys/select.h sys/sendfile.h sys/socket.h sys/statvfs.h \
+sys/param.h sys/random.h sys/select.h sys/sendfile.h sys/socket.h sys/statvfs.h \
 sys/stat.h sys/syscall.h sys/sys_domain.h sys/termio.h sys/time.h \
 sys/times.h sys/types.h sys/uio.h sys/un.h sys/utsname.h sys/wait.h pty.h \
 libutil.h sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \
@@ -2289,8 +2358,8 @@ if test -z "$LDSHARED"
 then
        case $ac_sys_system/$ac_sys_release in
        AIX*)
-               BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:\$(srcdir)/Modules/python.exp"
-               LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp"
+               BLDSHARED="Modules/ld_so_aix \$(CC) -bI:Modules/python.exp"
+               LDSHARED="\$(LIBPL)/ld_so_aix \$(CC) -bI:\$(LIBPL)/python.exp"
                ;;
        IRIX/5*) LDSHARED="ld -shared";;
        IRIX*/6*) LDSHARED="ld ${SGI_ABI} -shared -all";;
@@ -2551,9 +2620,6 @@ AC_MSG_RESULT($SHLIBS)
 AC_CHECK_LIB(sendfile, sendfile)
 AC_CHECK_LIB(dl, dlopen)       # Dynamic linking for SunOS/Solaris and SYSV
 AC_CHECK_LIB(dld, shl_load)    # Dynamic linking for HP-UX
-AC_CHECK_LIB(crypto, RAND_egd,
-             AC_DEFINE(HAVE_RAND_EGD, 1,
-             [Define if the libcrypto has RAND_egd]))
 
 # only check for sem_init if thread support is requested
 if test "$with_threads" = "yes" -o -z "$with_threads"; then
@@ -3709,6 +3775,8 @@ int main()
         break;
       }
     }
+    freeaddrinfo(aitop);
+    aitop = NULL;
   }
 
   if (!(inet4 == 0 || inet4 == 2))
@@ -5306,3 +5374,13 @@ $SHELL $srcdir/Modules/makesetup -c $srcdir/Modules/config.c.in \
                        -s Modules Modules/Setup.config \
                        Modules/Setup.local Modules/Setup
 mv config.c Modules
+
+if test "$Py_OPT" = 'false' -a "$Py_DEBUG" != 'true'; then
+    echo "" >&AS_MESSAGE_FD
+    echo "" >&AS_MESSAGE_FD
+    echo "If you want a release build with all optimizations active (LTO, PGO, etc),"
+    echo "please run ./configure --enable-optimizations" >&AS_MESSAGE_FD
+    echo "" >&AS_MESSAGE_FD
+    echo "" >&AS_MESSAGE_FD
+fi
+
index 7895535..39ccf53 100644 (file)
 /* Define to 1 if you have the <linux/netlink.h> header file. */
 #undef HAVE_LINUX_NETLINK_H
 
-/* Define to 1 if you have the <linux/tipc.h> header file. */
-#undef HAVE_LINUX_TIPC_H
-
 /* Define to 1 if you have the <linux/random.h> header file. */
 #undef HAVE_LINUX_RANDOM_H
 
+/* Define to 1 if you have the <linux/tipc.h> header file. */
+#undef HAVE_LINUX_TIPC_H
+
 /* Define to 1 if you have the `lockf' function. */
 #undef HAVE_LOCKF
 
 /* Define to 1 if you have the `pwrite' function. */
 #undef HAVE_PWRITE
 
-/* Define if the libcrypto has RAND_egd */
-#undef HAVE_RAND_EGD
-
 /* Define to 1 if you have the `readlink' function. */
 #undef HAVE_READLINK
 
 /* Define to 1 if you have the <sys/poll.h> header file. */
 #undef HAVE_SYS_POLL_H
 
+/* Define to 1 if you have the <sys/random.h> header file. */
+#undef HAVE_SYS_RANDOM_H
+
 /* Define to 1 if you have the <sys/resource.h> header file. */
 #undef HAVE_SYS_RESOURCE_H
 
index 174ce72..40f8bf2 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -8,7 +8,6 @@ import importlib.util
 import sysconfig
 
 from distutils import log
-from distutils import text_file
 from distutils.errors import *
 from distutils.core import Extension, setup
 from distutils.command.build_ext import build_ext
@@ -230,7 +229,12 @@ class PyBuildExt(build_ext):
         headers = [sysconfig.get_config_h_filename()]
         headers += glob(os.path.join(sysconfig.get_path('include'), "*.h"))
 
-        for ext in self.extensions[:]:
+        # The sysconfig variable built by makesetup, listing the already
+        # built modules as configured by the Setup files.
+        modnames = sysconfig.get_config_var('MODNAMES').split()
+
+        removed_modules = []
+        for ext in self.extensions:
             ext.sources = [ find_module_file(filename, moddirlist)
                             for filename in ext.sources ]
             if ext.depends is not None:
@@ -241,26 +245,14 @@ class PyBuildExt(build_ext):
             # re-compile extensions if a header file has been changed
             ext.depends.extend(headers)
 
-            # If a module has already been built statically,
-            # don't build it here
-            if ext.name in sys.builtin_module_names:
-                self.extensions.remove(ext)
-
-        # Parse Modules/Setup and Modules/Setup.local to figure out which
-        # modules are turned on in the file.
-        remove_modules = []
-        for filename in ('Modules/Setup', 'Modules/Setup.local'):
-            input = text_file.TextFile(filename, join_lines=1)
-            while 1:
-                line = input.readline()
-                if not line: break
-                line = line.split()
-                remove_modules.append(line[0])
-            input.close()
-
-        for ext in self.extensions[:]:
-            if ext.name in remove_modules:
-                self.extensions.remove(ext)
+            # If a module has already been built by the Makefile,
+            # don't build it here.
+            if ext.name in modnames:
+                removed_modules.append(ext)
+
+        if removed_modules:
+            self.extensions = [x for x in self.extensions if x not in
+                               removed_modules]
 
         # When you run "make CC=altcc" or something similar, you really want
         # those environment variables passed into the setup.py phase.  Here's
@@ -303,6 +295,13 @@ class PyBuildExt(build_ext):
                   " detect_modules() for the module's name.")
             print()
 
+        if removed_modules:
+            print("The following modules found by detect_modules() in"
+            " setup.py, have been")
+            print("built by the Makefile instead, as configured by the"
+            " Setup files:")
+            print_three_column([ext.name for ext in removed_modules])
+
         if self.failed:
             failed = self.failed[:]
             print()
@@ -1997,14 +1996,16 @@ class PyBuildExt(build_ext):
             ffi_inc = find_file('ffi.h', [], inc_dirs)
         if ffi_inc is not None:
             ffi_h = ffi_inc[0] + '/ffi.h'
-            with open(ffi_h) as fp:
-                while 1:
-                    line = fp.readline()
-                    if not line:
-                        ffi_inc = None
-                        break
-                    if line.startswith('#define LIBFFI_H'):
+            with open(ffi_h) as f:
+                for line in f:
+                    line = line.strip()
+                    if line.startswith(('#define LIBFFI_H',
+                                        '#define ffi_wrapper_h')):
                         break
+                else:
+                    ffi_inc = None
+                    print('Header file {} does not define LIBFFI_H or '
+                          'ffi_wrapper_h'.format(ffi_h))
         ffi_lib = None
         if ffi_inc is not None:
             for lib_name in ('ffi_convenience', 'ffi_pic', 'ffi'):