Keyboard Shortcuts
Thread View
j: Next unread messagek: Previous unread messagej a: Jump to all threadsj l: Jump to MailingList overview
Python-Dev
Download Threads by month- ----- 2026 -----
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2003 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2002 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2001 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2000 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 1999 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
February 2014
- 106 participants
- 77 discussions
by barry@zope.com May 18, 2021
May 18, 2021 It has been a while since I posted a copy of PEP 1 to the mailing lists and newsgroups. I've recently done some updating of a few sections, so in the interest of gaining wider community participation in the Python development process, I'm posting the latest revision of PEP 1 here. A version of the PEP is always available on-line at http://www.python.org/peps/pep-0001.html Enjoy, -Barry -------------------- snip snip -------------------- PEP: 1 Title: PEP Purpose and Guidelines Version: $Revision: 1.36 $ Last-Modified: $Date: 2002/07/29 18:34:59 $ Author: Barry A. Warsaw, Jeremy Hylton Status: Active Type: Informational Created: 13-Jun-2000 Post-History: 21-Mar-2001, 29-Jul-2002 What is a PEP? PEP stands for Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python. The PEP should provide a concise technical specification of the feature and a rationale for the feature. We intend PEPs to be the primary mechanisms for proposing new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Python. The PEP author is responsible for building consensus within the community and documenting dissenting opinions. Because the PEPs are maintained as plain text files under CVS control, their revision history is the historical record of the feature proposal[1]. Kinds of PEPs There are two kinds of PEPs. A standards track PEP describes a new feature or implementation for Python. An informational PEP describes a Python design issue, or provides general guidelines or information to the Python community, but does not propose a new feature. Informational PEPs do not necessarily represent a Python community consensus or recommendation, so users and implementors are free to ignore informational PEPs or follow their advice. PEP Work Flow The PEP editor, Barry Warsaw <peps(a)python.org>, assigns numbers for each PEP and changes its status. The PEP process begins with a new idea for Python. It is highly recommended that a single PEP contain a single key proposal or new idea. The more focussed the PEP, the more successfully it tends to be. The PEP editor reserves the right to reject PEP proposals if they appear too unfocussed or too broad. If in doubt, split your PEP into several well-focussed ones. Each PEP must have a champion -- someone who writes the PEP using the style and format described below, shepherds the discussions in the appropriate forums, and attempts to build community consensus around the idea. The PEP champion (a.k.a. Author) should first attempt to ascertain whether the idea is PEP-able. Small enhancements or patches often don't need a PEP and can be injected into the Python development work flow with a patch submission to the SourceForge patch manager[2] or feature request tracker[3]. The PEP champion then emails the PEP editor <peps(a)python.org> with a proposed title and a rough, but fleshed out, draft of the PEP. This draft must be written in PEP style as described below. If the PEP editor approves, he will assign the PEP a number, label it as standards track or informational, give it status 'draft', and create and check-in the initial draft of the PEP. The PEP editor will not unreasonably deny a PEP. Reasons for denying PEP status include duplication of effort, being technically unsound, not providing proper motivation or addressing backwards compatibility, or not in keeping with the Python philosophy. The BDFL (Benevolent Dictator for Life, Guido van Rossum) can be consulted during the approval phase, and is the final arbitrator of the draft's PEP-ability. If a pre-PEP is rejected, the author may elect to take the pre-PEP to the comp.lang.python newsgroup (a.k.a. python-list(a)python.org mailing list) to help flesh it out, gain feedback and consensus from the community at large, and improve the PEP for re-submission. The author of the PEP is then responsible for posting the PEP to the community forums, and marshaling community support for it. As updates are necessary, the PEP author can check in new versions if they have CVS commit permissions, or can email new PEP versions to the PEP editor for committing. Standards track PEPs consists of two parts, a design document and a reference implementation. The PEP should be reviewed and accepted before a reference implementation is begun, unless a reference implementation will aid people in studying the PEP. Standards Track PEPs must include an implementation - in the form of code, patch, or URL to same - before it can be considered Final. PEP authors are responsible for collecting community feedback on a PEP before submitting it for review. A PEP that has not been discussed on python-list(a)python.org and/or python-dev(a)python.org will not be accepted. However, wherever possible, long open-ended discussions on public mailing lists should be avoided. Strategies to keep the discussions efficient include, setting up a separate SIG mailing list for the topic, having the PEP author accept private comments in the early design phases, etc. PEP authors should use their discretion here. Once the authors have completed a PEP, they must inform the PEP editor that it is ready for review. PEPs are reviewed by the BDFL and his chosen consultants, who may accept or reject a PEP or send it back to the author(s) for revision. Once a PEP has been accepted, the reference implementation must be completed. When the reference implementation is complete and accepted by the BDFL, the status will be changed to `Final.' A PEP can also be assigned status `Deferred.' The PEP author or editor can assign the PEP this status when no progress is being made on the PEP. Once a PEP is deferred, the PEP editor can re-assign it to draft status. A PEP can also be `Rejected'. Perhaps after all is said and done it was not a good idea. It is still important to have a record of this fact. PEPs can also be replaced by a different PEP, rendering the original obsolete. This is intended for Informational PEPs, where version 2 of an API can replace version 1. PEP work flow is as follows: Draft -> Accepted -> Final -> Replaced ^ +----> Rejected v Deferred Some informational PEPs may also have a status of `Active' if they are never meant to be completed. E.g. PEP 1. What belongs in a successful PEP? Each PEP should have the following parts: 1. Preamble -- RFC822 style headers containing meta-data about the PEP, including the PEP number, a short descriptive title (limited to a maximum of 44 characters), the names, and optionally the contact info for each author, etc. 2. Abstract -- a short (~200 word) description of the technical issue being addressed. 3. Copyright/public domain -- Each PEP must either be explicitly labelled as placed in the public domain (see this PEP as an example) or licensed under the Open Publication License[4]. 4. Specification -- The technical specification should describe the syntax and semantics of any new language feature. The specification should be detailed enough to allow competing, interoperable implementations for any of the current Python platforms (CPython, JPython, Python .NET). 5. Motivation -- The motivation is critical for PEPs that want to change the Python language. It should clearly explain why the existing language specification is inadequate to address the problem that the PEP solves. PEP submissions without sufficient motivation may be rejected outright. 6. Rationale -- The rationale fleshes out the specification by describing what motivated the design and why particular design decisions were made. It should describe alternate designs that were considered and related work, e.g. how the feature is supported in other languages. The rationale should provide evidence of consensus within the community and discuss important objections or concerns raised during discussion. 7. Backwards Compatibility -- All PEPs that introduce backwards incompatibilities must include a section describing these incompatibilities and their severity. The PEP must explain how the author proposes to deal with these incompatibilities. PEP submissions without a sufficient backwards compatibility treatise may be rejected outright. 8. Reference Implementation -- The reference implementation must be completed before any PEP is given status 'Final,' but it need not be completed before the PEP is accepted. It is better to finish the specification and rationale first and reach consensus on it before writing code. The final implementation must include test code and documentation appropriate for either the Python language reference or the standard library reference. PEP Template PEPs are written in plain ASCII text, and should adhere to a rigid style. There is a Python script that parses this style and converts the plain text PEP to HTML for viewing on the web[5]. PEP 9 contains a boilerplate[7] template you can use to get started writing your PEP. Each PEP must begin with an RFC822 style header preamble. The headers must appear in the following order. Headers marked with `*' are optional and are described below. All other headers are required. PEP: <pep number> Title: <pep title> Version: <cvs version string> Last-Modified: <cvs date string> Author: <list of authors' real names and optionally, email addrs> * Discussions-To: <email address> Status: <Draft | Active | Accepted | Deferred | Final | Replaced> Type: <Informational | Standards Track> * Requires: <pep numbers> Created: <date created on, in dd-mmm-yyyy format> * Python-Version: <version number> Post-History: <dates of postings to python-list and python-dev> * Replaces: <pep number> * Replaced-By: <pep number> The Author: header lists the names and optionally, the email addresses of all the authors/owners of the PEP. The format of the author entry should be address(a)dom.ain (Random J. User) if the email address is included, and just Random J. User if the address is not given. If there are multiple authors, each should be on a separate line following RFC 822 continuation line conventions. Note that personal email addresses in PEPs will be obscured as a defense against spam harvesters. Standards track PEPs must have a Python-Version: header which indicates the version of Python that the feature will be released with. Informational PEPs do not need a Python-Version: header. While a PEP is in private discussions (usually during the initial Draft phase), a Discussions-To: header will indicate the mailing list or URL where the PEP is being discussed. No Discussions-To: header is necessary if the PEP is being discussed privately with the author, or on the python-list or python-dev email mailing lists. Note that email addresses in the Discussions-To: header will not be obscured. Created: records the date that the PEP was assigned a number, while Post-History: is used to record the dates of when new versions of the PEP are posted to python-list and/or python-dev. Both headers should be in dd-mmm-yyyy format, e.g. 14-Aug-2001. PEPs may have a Requires: header, indicating the PEP numbers that this PEP depends on. PEPs may also have a Replaced-By: header indicating that a PEP has been rendered obsolete by a later document; the value is the number of the PEP that replaces the current document. The newer PEP must have a Replaces: header containing the number of the PEP that it rendered obsolete. PEP Formatting Requirements PEP headings must begin in column zero and the initial letter of each word must be capitalized as in book titles. Acronyms should be in all capitals. The body of each section must be indented 4 spaces. Code samples inside body sections should be indented a further 4 spaces, and other indentation can be used as required to make the text readable. You must use two blank lines between the last line of a section's body and the next section heading. You must adhere to the Emacs convention of adding two spaces at the end of every sentence. You should fill your paragraphs to column 70, but under no circumstances should your lines extend past column 79. If your code samples spill over column 79, you should rewrite them. Tab characters must never appear in the document at all. A PEP should include the standard Emacs stanza included by example at the bottom of this PEP. A PEP must contain a Copyright section, and it is strongly recommended to put the PEP in the public domain. When referencing an external web page in the body of a PEP, you should include the title of the page in the text, with a footnote reference to the URL. Do not include the URL in the body text of the PEP. E.g. Refer to the Python Language web site [1] for more details. ... [1] http://www.python.org When referring to another PEP, include the PEP number in the body text, such as "PEP 1". The title may optionally appear. Add a footnote reference that includes the PEP's title and author. It may optionally include the explicit URL on a separate line, but only in the References section. Note that the pep2html.py script will calculate URLs automatically, e.g.: ... Refer to PEP 1 [7] for more information about PEP style ... References [7] PEP 1, PEP Purpose and Guidelines, Warsaw, Hylton http://www.python.org/peps/pep-0001.html If you decide to provide an explicit URL for a PEP, please use this as the URL template: http://www.python.org/peps/pep-xxxx.html PEP numbers in URLs must be padded with zeros from the left, so as to be exactly 4 characters wide, however PEP numbers in text are never padded. Reporting PEP Bugs, or Submitting PEP Updates How you report a bug, or submit a PEP update depends on several factors, such as the maturity of the PEP, the preferences of the PEP author, and the nature of your comments. For the early draft stages of the PEP, it's probably best to send your comments and changes directly to the PEP author. For more mature, or finished PEPs you may want to submit corrections to the SourceForge bug manager[6] or better yet, the SourceForge patch manager[2] so that your changes don't get lost. If the PEP author is a SF developer, assign the bug/patch to him, otherwise assign it to the PEP editor. When in doubt about where to send your changes, please check first with the PEP author and/or PEP editor. PEP authors who are also SF committers, can update the PEPs themselves by using "cvs commit" to commit their changes. Remember to also push the formatted PEP text out to the web by doing the following: % python pep2html.py -i NUM where NUM is the number of the PEP you want to push out. See % python pep2html.py --help for details. Transferring PEP Ownership It occasionally becomes necessary to transfer ownership of PEPs to a new champion. In general, we'd like to retain the original author as a co-author of the transferred PEP, but that's really up to the original author. A good reason to transfer ownership is because the original author no longer has the time or interest in updating it or following through with the PEP process, or has fallen off the face of the 'net (i.e. is unreachable or not responding to email). A bad reason to transfer ownership is because you don't agree with the direction of the PEP. We try to build consensus around a PEP, but if that's not possible, you can always submit a competing PEP. If you are interested assuming ownership of a PEP, send a message asking to take over, addressed to both the original author and the PEP editor <peps(a)python.org>. If the original author doesn't respond to email in a timely manner, the PEP editor will make a unilateral decision (it's not like such decisions can be reversed. :). References and Footnotes [1] This historical record is available by the normal CVS commands for retrieving older revisions. For those without direct access to the CVS tree, you can browse the current and past PEP revisions via the SourceForge web site at http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/python/nondist/peps/?cvsroot=… [2] http://sourceforge.net/tracker/?group_id=5470&atid=305470 [3] http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse [4] http://www.opencontent.org/openpub/ [5] The script referred to here is pep2html.py, which lives in the same directory in the CVS tree as the PEPs themselves. Try "pep2html.py --help" for details. The URL for viewing PEPs on the web is http://www.python.org/peps/ [6] http://sourceforge.net/tracker/?group_id=5470&atid=305470 [7] PEP 9, Sample PEP Template http://www.python.org/peps/pep-0009.html Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: 8 14
by Raymond Hettinger Jan. 3, 2015
Jan. 3, 2015 The current memory layout for dictionaries is unnecessarily inefficient. It has a sparse table of 24-byte entries containing the hash value, key pointer, and value pointer. Instead, the 24-byte entries should be stored in a dense table referenced by a sparse table of indices. For example, the dictionary: d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'} is currently stored as: entries = [['--', '--', '--'], [-8522787127447073495, 'barry', 'green'], ['--', '--', '--'], ['--', '--', '--'], ['--', '--', '--'], [-9092791511155847987, 'timmy', 'red'], ['--', '--', '--'], [-6480567542315338377, 'guido', 'blue']] Instead, the data should be organized as follows: indices = [None, 1, None, None, None, 0, None, 2] entries = [[-9092791511155847987, 'timmy', 'red'], [-8522787127447073495, 'barry', 'green'], [-6480567542315338377, 'guido', 'blue']] Only the data layout needs to change. The hash table algorithms would stay the same. All of the current optimizations would be kept, including key-sharing dicts and custom lookup functions for string-only dicts. There is no change to the hash functions, the table search order, or collision statistics. The memory savings are significant (from 30% to 95% compression depending on the how full the table is). Small dicts (size 0, 1, or 2) get the most benefit. For a sparse table of size t with n entries, the sizes are: curr_size = 24 * t new_size = 24 * n + sizeof(index) * t In the above timmy/barry/guido example, the current size is 192 bytes (eight 24-byte entries) and the new size is 80 bytes (three 24-byte entries plus eight 1-byte indices). That gives 58% compression. Note, the sizeof(index) can be as small as a single byte for small dicts, two bytes for bigger dicts and up to sizeof(Py_ssize_t) for huge dict. In addition to space savings, the new memory layout makes iteration faster. Currently, keys(), values, and items() loop over the sparse table, skipping-over free slots in the hash table. Now, keys/values/items can loop directly over the dense table, using fewer memory accesses. Another benefit is that resizing is faster and touches fewer pieces of memory. Currently, every hash/key/value entry is moved or copied during a resize. In the new layout, only the indices are updated. For the most part, the hash/key/value entries never move (except for an occasional swap to fill a hole left by a deletion). With the reduced memory footprint, we can also expect better cache utilization. For those wanting to experiment with the design, there is a pure Python proof-of-concept here: http://code.activestate.com/recipes/578375 YMMV: Keep in mind that the above size statics assume a build with 64-bit Py_ssize_t and 64-bit pointers. The space savings percentages are a bit different on other builds. Also, note that in many applications, the size of the data dominates the size of the container (i.e. the weight of a bucket of water is mostly the water, not the bucket). Raymond 27 70
by Eli Bendersky Oct. 15, 2014
Oct. 15, 2014 Hi all, https://github.com/python/cpython is now live as a semi-official, *read only* Github mirror of the CPython Mercurial repository. Let me know if you have any problems/concerns. I still haven't decided how often to update it (considering either just N times a day, or maybe use a Hg hook for batching). Suggestions are welcome. The methodology I used to create it is via hg-fast-export. I also tried to pack and gc the git repo as much as possible before the initial Github push - it went down from almost ~2GB to ~200MB (so this is the size of a fresh clone right now). Eli P.S. thanks Jesse for the keys to https://github.com/python 4 8
by Guido van Rossum Aug. 14, 2014
Aug. 14, 2014 I've received some enthusiastic emails from someone who wants to revive restricted mode. He started out with a bunch of patches to the CPython runtime using ctypes, which he attached to an App Engine bug: http://code.google.com/p/googleappengine/issues/detail?id=671 Based on his code (the file secure.py is all you need, included in secure.tar.gz) it seems he believes the only security leaks are __subclasses__, gi_frame and gi_code. (I have since convinced him that if we add "restricted" guards to these attributes, he doesn't need the functions added to sys.) I don't recall the exploits that Samuele once posted that caused the death of rexec.py -- does anyone recall, or have a pointer to the threads? -- --Guido van Rossum (home page: http://www.python.org/~guido/) 19 35
by Python tracker May 15, 2014
May 15, 2014 ACTIVITY SUMMARY (2014-01-31 - 2014-02-07) Python tracker at http://bugs.python.org/ To view or respond to any of the issues listed below, click on the issue. Do NOT respond to this message. Issues counts and deltas: open 4501 (+17) closed 27813 (+65) total 32314 (+82) Open issues with patches: 2045 Issues opened (65) ================== #12915: Add inspect.locate and inspect.resolve http://bugs.python.org/issue12915 reopened by vinay.sajip #16779: Fix compiler warning when building extension modules on 64-bit http://bugs.python.org/issue16779 reopened by skrah #19363: Python 2.7's future_builtins.map is not compatible with Python http://bugs.python.org/issue19363 reopened by Gareth.Rees #20053: venv and ensurepip are affected by default pip config file http://bugs.python.org/issue20053 reopened by ncoghlan #20461: Argument Clinic included return converters hard code use of `` http://bugs.python.org/issue20461 opened by brett.cannon #20462: Python IDLE auto closed when creating a new file or open exist http://bugs.python.org/issue20462 opened by Bishop #20463: sqlite dumpiter dumps invalid script when virtual tables are u http://bugs.python.org/issue20463 opened by Ronny.Pfannschmidt #20464: Update distutils sample config file in Doc/install/index.rst http://bugs.python.org/issue20464 opened by zach.ware #20465: Upgrade SQLite to 3.8.3 with 3.4.0 Windows and OS X installers http://bugs.python.org/issue20465 opened by ned.deily #20466: Example in Doc/extending/embedding.rst fails to compile cleanl http://bugs.python.org/issue20466 opened by zach.ware #20467: Confusing wording about __init__ http://bugs.python.org/issue20467 opened by BreamoreBoy #20468: resource module documentation is incorrect http://bugs.python.org/issue20468 opened by Kurt.Rose #20469: ssl.getpeercert() should include extensions http://bugs.python.org/issue20469 opened by oninoshiko #20475: pystone.py in 3.4 still uses time.clock(), even though it's ma http://bugs.python.org/issue20475 opened by pfalcon #20476: If new email policies are used, default message factory should http://bugs.python.org/issue20476 opened by r.david.murray #20478: Avoid inadvertently special casing Counter in statistics modul http://bugs.python.org/issue20478 opened by ncoghlan #20479: Efficiently support weight/frequency mappings in the statistic http://bugs.python.org/issue20479 opened by ncoghlan #20480: Add ipaddress property to get name of reverse DNS PTR record http://bugs.python.org/issue20480 opened by leonn #20481: Clarify type coercion rules in statistics module http://bugs.python.org/issue20481 opened by ncoghlan #20482: smtplib.SMTP.sendmail: improve exception message http://bugs.python.org/issue20482 opened by yegle #20483: Missing network resource checks in test_urllib2 & test_smtplib http://bugs.python.org/issue20483 opened by ncoghlan #20484: test_pydoc can alter execution environment causing subsequent http://bugs.python.org/issue20484 opened by ned.deily #20485: Enable non-ASCII extension module names http://bugs.python.org/issue20485 opened by Suzumizaki #20486: msilib: can't close opened database http://bugs.python.org/issue20486 opened by gentoo90 #20487: Odd words in unittest.mock document. http://bugs.python.org/issue20487 opened by naoki #20490: Show clear error message on circular import http://bugs.python.org/issue20490 opened by cool-RR #20491: textwrap: Non-breaking space not honored http://bugs.python.org/issue20491 opened by kunkku #20493: asyncio: OverflowError('timeout is too large') http://bugs.python.org/issue20493 opened by haypo #20495: test_read_pty_output() hangs on FreeBSD 7.2 buildbot http://bugs.python.org/issue20495 opened by haypo #20496: function definition tutorial encourages bad practice http://bugs.python.org/issue20496 opened by aisaac #20497: Unclear word in socket document. http://bugs.python.org/issue20497 opened by naoki #20499: Rounding errors with statistics.variance http://bugs.python.org/issue20499 opened by oscarbenjamin #20500: assertion failed when passing an exception object to sys.exit http://bugs.python.org/issue20500 opened by xdegaye #20501: fileinput module will read whole file into memory when using f http://bugs.python.org/issue20501 opened by gromgull #20503: super behavioru and abstract base classes (either implementati http://bugs.python.org/issue20503 opened by Gerrit.Holl #20504: cgi.FieldStorage, multipart, missing Content-Length http://bugs.python.org/issue20504 opened by srittau #20505: Remove resolution from selectors and granularity from asyncio http://bugs.python.org/issue20505 opened by haypo #20506: Command to display all available Import Library http://bugs.python.org/issue20506 opened by arupchakrav #20507: TypeError from str.join has no message http://bugs.python.org/issue20507 opened by Gareth.Rees #20508: IndexError from ipaddress._BaseNetwork.__getitem__ has no mess http://bugs.python.org/issue20508 opened by Gareth.Rees #20510: Test cases in test_sys don't match the comments http://bugs.python.org/issue20510 opened by Gareth.Rees #20511: asyncio: StreamReader should use bytearray for its internal bu http://bugs.python.org/issue20511 opened by yselivanov #20513: Python 2.7. Script interruption on logoff from 0 session under http://bugs.python.org/issue20513 opened by vScherba #20515: Null pointer dereference in tkinter module http://bugs.python.org/issue20515 opened by christian.heimes #20516: Concurrent.futures base concurrency improvement (with patch) http://bugs.python.org/issue20516 opened by glangford #20517: Support errors with two filenames for errno exceptions http://bugs.python.org/issue20517 opened by larry #20518: multiple inheritance + C extension = possibly unexpected __bas http://bugs.python.org/issue20518 opened by Martin.Teichmann #20519: Replace uuid ctypes usage with an extension module. http://bugs.python.org/issue20519 opened by gustavo #20520: Readline test in test_codecs is broken http://bugs.python.org/issue20520 opened by serhiy.storchaka #20521: [PATCH] Cleanup for "dis" module documentation http://bugs.python.org/issue20521 opened by svenberkvens #20523: global .pdbrc on windows 7 not reachable out of the box http://bugs.python.org/issue20523 opened by mbyt #20524: format error messages should provide context information http://bugs.python.org/issue20524 opened by r.david.murray #20525: Got compiler warning when compiling readline module http://bugs.python.org/issue20525 opened by vajrasky #20526: python: Modules/gcmodule.c:379: visit_decref: Assertion `((gc) http://bugs.python.org/issue20526 opened by haypo #20529: Unittest displays ResourceWarning warnings when running tests, http://bugs.python.org/issue20529 opened by Bernt.Røskar.Brenna #20530: Change the text signature format (again) to be more robust http://bugs.python.org/issue20530 opened by larry #20531: TypeError in e-mail.parser when non-ASCII is present http://bugs.python.org/issue20531 opened by jason.coombs #20532: Mark all tests which use _testcapi as CPython only http://bugs.python.org/issue20532 opened by serhiy.storchaka #20534: Enum tests fail with pickle protocol 4 http://bugs.python.org/issue20534 opened by ethan.furman #20535: run_tests.py: Work around issues 20355 and 20361 http://bugs.python.org/issue20535 opened by Arfrever #20536: statistics._decimal_to_ratio() produces non-integer ratio http://bugs.python.org/issue20536 opened by skrah #20537: logging exc_info parameter should accept exception instances http://bugs.python.org/issue20537 opened by yselivanov #20538: Segfault in UTF-7 incremental decoder http://bugs.python.org/issue20538 opened by serhiy.storchaka #20539: math.factorial may throw OverflowError http://bugs.python.org/issue20539 opened by ncoghlan #20540: Python 3.3/3.4 regression in multiprocessing manager ? http://bugs.python.org/issue20540 opened by Irvin.Probst Most recent 15 issues with no replies (15) ========================================== #20536: statistics._decimal_to_ratio() produces non-integer ratio http://bugs.python.org/issue20536 #20535: run_tests.py: Work around issues 20355 and 20361 http://bugs.python.org/issue20535 #20526: python: Modules/gcmodule.c:379: visit_decref: Assertion `((gc) http://bugs.python.org/issue20526 #20523: global .pdbrc on windows 7 not reachable out of the box http://bugs.python.org/issue20523 #20521: [PATCH] Cleanup for "dis" module documentation http://bugs.python.org/issue20521 #20516: Concurrent.futures base concurrency improvement (with patch) http://bugs.python.org/issue20516 #20513: Python 2.7. Script interruption on logoff from 0 session under http://bugs.python.org/issue20513 #20511: asyncio: StreamReader should use bytearray for its internal bu http://bugs.python.org/issue20511 #20508: IndexError from ipaddress._BaseNetwork.__getitem__ has no mess http://bugs.python.org/issue20508 #20504: cgi.FieldStorage, multipart, missing Content-Length http://bugs.python.org/issue20504 #20503: super behavioru and abstract base classes (either implementati http://bugs.python.org/issue20503 #20500: assertion failed when passing an exception object to sys.exit http://bugs.python.org/issue20500 #20497: Unclear word in socket document. http://bugs.python.org/issue20497 #20496: function definition tutorial encourages bad practice http://bugs.python.org/issue20496 #20486: msilib: can't close opened database http://bugs.python.org/issue20486 Most recent 15 issues waiting for review (15) ============================================= #20540: Python 3.3/3.4 regression in multiprocessing manager ? http://bugs.python.org/issue20540 #20537: logging exc_info parameter should accept exception instances http://bugs.python.org/issue20537 #20535: run_tests.py: Work around issues 20355 and 20361 http://bugs.python.org/issue20535 #20534: Enum tests fail with pickle protocol 4 http://bugs.python.org/issue20534 #20532: Mark all tests which use _testcapi as CPython only http://bugs.python.org/issue20532 #20530: Change the text signature format (again) to be more robust http://bugs.python.org/issue20530 #20525: Got compiler warning when compiling readline module http://bugs.python.org/issue20525 #20523: global .pdbrc on windows 7 not reachable out of the box http://bugs.python.org/issue20523 #20521: [PATCH] Cleanup for "dis" module documentation http://bugs.python.org/issue20521 #20520: Readline test in test_codecs is broken http://bugs.python.org/issue20520 #20519: Replace uuid ctypes usage with an extension module. http://bugs.python.org/issue20519 #20516: Concurrent.futures base concurrency improvement (with patch) http://bugs.python.org/issue20516 #20515: Null pointer dereference in tkinter module http://bugs.python.org/issue20515 #20513: Python 2.7. Script interruption on logoff from 0 session under http://bugs.python.org/issue20513 #20511: asyncio: StreamReader should use bytearray for its internal bu http://bugs.python.org/issue20511 Top 10 most discussed issues (10) ================================= #20480: Add ipaddress property to get name of reverse DNS PTR record http://bugs.python.org/issue20480 21 msgs #20485: Enable non-ASCII extension module names http://bugs.python.org/issue20485 17 msgs #20481: Clarify type coercion rules in statistics module http://bugs.python.org/issue20481 14 msgs #20053: venv and ensurepip are affected by default pip config file http://bugs.python.org/issue20053 13 msgs #20185: Derby #17: Convert 49 sites to Argument Clinic across 13 files http://bugs.python.org/issue20185 12 msgs #20475: pystone.py in 3.4 still uses time.clock(), even though it's ma http://bugs.python.org/issue20475 10 msgs #15216: Support setting the encoding on a text stream after creation http://bugs.python.org/issue15216 9 msgs #20505: Remove resolution from selectors and granularity from asyncio http://bugs.python.org/issue20505 9 msgs #20520: Readline test in test_codecs is broken http://bugs.python.org/issue20520 9 msgs #16296: Patch to fix building on Win32/64 under VS 2010 http://bugs.python.org/issue16296 8 msgs Issues closed (62) ================== #2226: Small _abcoll Bugs / Oddities http://bugs.python.org/issue2226 closed by ncoghlan #7538: HP-UX 11.11 GCC build fails to build modules http://bugs.python.org/issue7538 closed by Arfrever #7717: Compilation fixes for IRIX http://bugs.python.org/issue7717 closed by berker.peksag #11117: Implementing Async IO http://bugs.python.org/issue11117 closed by yselivanov #12187: subprocess.wait() with a timeout uses polling on POSIX http://bugs.python.org/issue12187 closed by haypo #14515: tempfile.TemporaryDirectory documented as returning object but http://bugs.python.org/issue14515 closed by r.david.murray #14665: faulthandler prints tracebacks in reverse order http://bugs.python.org/issue14665 closed by ncoghlan #14854: faulthandler: fatal error with "SystemError: null argument to http://bugs.python.org/issue14854 closed by haypo #17159: Remove explicit type check from inspect.Signature.from_functio http://bugs.python.org/issue17159 closed by yselivanov #17162: Py_LIMITED_API needs a PyType_GenericDealloc http://bugs.python.org/issue17162 closed by loewis #18801: inspect.classify_class_attrs() misclassifies object.__new__() http://bugs.python.org/issue18801 closed by yselivanov #18891: Master patch for content manager addition to email package http://bugs.python.org/issue18891 closed by r.david.murray #19186: expat symbols should be namespaced in pyexpat again http://bugs.python.org/issue19186 closed by python-dev #19320: Tkinter tests ran with wantobjects is false http://bugs.python.org/issue19320 closed by serhiy.storchaka #19334: test_asyncio hanging for 1 hour (non-AIX version) http://bugs.python.org/issue19334 closed by haypo #19652: test_asyncio: test_subprocess_send_signal() hangs on buildbot http://bugs.python.org/issue19652 closed by haypo #19761: test_tk fails on OS X with multiple test case failures with bo http://bugs.python.org/issue19761 closed by serhiy.storchaka #19863: Missing function attributes in 2.7 docs. http://bugs.python.org/issue19863 closed by mark.dickinson #19920: TarFile.list() fails on some files http://bugs.python.org/issue19920 closed by serhiy.storchaka #20029: asyncio.SubprocessProtocol is missing http://bugs.python.org/issue20029 closed by haypo #20102: shutil._make_zipfile possible resource leak http://bugs.python.org/issue20102 closed by python-dev #20136: Logging: StreamHandler does not use OS line separator. http://bugs.python.org/issue20136 closed by vinay.sajip #20137: Logging: RotatingFileHandler computes string length instead of http://bugs.python.org/issue20137 closed by vinay.sajip #20162: Test test_hash_distribution fails on RHEL 6.5 / ppc64 http://bugs.python.org/issue20162 closed by haypo #20311: epoll.poll(timeout) and PollSelector.select(timeout) must roun http://bugs.python.org/issue20311 closed by haypo #20319: concurrent.futures.wait() can block forever even if Futures ha http://bugs.python.org/issue20319 closed by bquinlan #20354: tracemalloc causes segfault in "make profile-opt" http://bugs.python.org/issue20354 closed by haypo #20363: BytesWarnings triggerred by test suite http://bugs.python.org/issue20363 closed by serhiy.storchaka #20368: Tkinter: handle the null character http://bugs.python.org/issue20368 closed by serhiy.storchaka #20400: Add create_read_pipe_protocol/create_write_pipe_protocol to as http://bugs.python.org/issue20400 closed by haypo #20404: Delayed exception using non-text encodings with TextIOWrapper http://bugs.python.org/issue20404 closed by python-dev #20412: Enum and IntEnum classes are not defined in the documentation http://bugs.python.org/issue20412 closed by python-dev #20423: io.StringIO newline param has wrong default http://bugs.python.org/issue20423 closed by pitrou #20426: Compiling a regex with re.DEBUG should force a recompile http://bugs.python.org/issue20426 closed by pitrou #20435: Discrepancy between io.StringIO and _pyio.StringIO with univer http://bugs.python.org/issue20435 closed by pitrou #20445: HAVE_BROKEN_NICE detected incorrectly due to configure.ac typo http://bugs.python.org/issue20445 closed by George.Kouryachy #20452: test_timeout_rounding() of test_asyncio fails on "x86 Ubuntu S http://bugs.python.org/issue20452 closed by haypo #20455: test_asyncio hangs on Windows http://bugs.python.org/issue20455 closed by haypo #20456: Argument Clinic rollup patch, 2014/01/31 http://bugs.python.org/issue20456 closed by larry #20460: Wrong markup in c-api/arg.rst http://bugs.python.org/issue20460 closed by zach.ware #20470: "Fatal Python error: Bus error" on the SPARC Solaris 10 buildb http://bugs.python.org/issue20470 closed by haypo #20471: test_signature_on_class() of test_inspect fails on "AMD64 Free http://bugs.python.org/issue20471 closed by yselivanov #20472: test_write_pty() of test_asyncio fails on "x86 Tiger 3.x" buil http://bugs.python.org/issue20472 closed by haypo #20473: inspect.Signature no longer handles builtin classes correctly http://bugs.python.org/issue20473 closed by yselivanov #20474: test_socket failures on OS X due to fixed "expected failures" http://bugs.python.org/issue20474 closed by ned.deily #20477: Add examples of using the new contentmanager api to the email http://bugs.python.org/issue20477 closed by r.david.murray #20488: importlib title and introduction are out of date http://bugs.python.org/issue20488 closed by brett.cannon #20489: help() fails for zlib Compress and Decompress objects http://bugs.python.org/issue20489 closed by serhiy.storchaka #20492: test_tcl is failing on windows 2.7 http://bugs.python.org/issue20492 closed by serhiy.storchaka #20494: Backport of http://bugs.python.org/issue11849 to Python 2.7 (M http://bugs.python.org/issue20494 closed by python-dev #20498: Update StringIO newline tests http://bugs.python.org/issue20498 closed by serhiy.storchaka #20502: Context.create_decimal_from_float() inconsistent precision for http://bugs.python.org/issue20502 closed by mark.dickinson #20509: logging.config.fileConfig() docs could link to the config file http://bugs.python.org/issue20509 closed by python-dev #20512: Python3.3 segfaults when using big5hkscs encoding http://bugs.python.org/issue20512 closed by ned.deily #20514: Errno 10013 - ipython notebook http://bugs.python.org/issue20514 closed by ned.deily #20522: pandas version 0.13.0 does not give warning when summing float http://bugs.python.org/issue20522 closed by mark.dickinson #20527: multiprocessing.Queue deadlocks after “reader” process dea http://bugs.python.org/issue20527 closed by sbt #20528: fileinput module will read whole file into memory when using f http://bugs.python.org/issue20528 closed by r.david.murray #20533: bug in float arithmetic? http://bugs.python.org/issue20533 closed by zach.ware #20541: os.path.exists() gives wrong answer for Windows special files http://bugs.python.org/issue20541 closed by ncoghlan #20542: Assertion failure in test_readline http://bugs.python.org/issue20542 closed by ncoghlan #1028088: Cookies without values are silently ignored (by design?) http://bugs.python.org/issue1028088 closed by berker.peksag 3 2
by Terry Reedy March 31, 2014
March 31, 2014 I am working through the multiple bugs afflicting tokenize.untokenize, which is described in the tokenize doc and has an even longer docstring. While the function could be implemented as one 70-line function, it happens to be implemented as a 4-line wrapper for a completely undocumented (Untokenizer class with 4 methods. (It is unmentioned in the doc and there are currently no docstrings.) I view the class as a private implementation detail and would like to treat it as such, and perhaps even rename it _Untokenizer to make that clear. The issue arises in #9974. It appears that a fix may require the addition of an instance attribute or .add_whitespace parameter. If there is objection to treating the whole class as private, I would at least like to treat add_whitespace as the private helper that it is. There is no reason to call it directly except for testing. Otherwise, it could just as well have been left inline at the one call site. -- Terry Jan Reedy 3 4
by Serhiy Storchaka March 18, 2014
March 18, 2014 There were several suggestions for naming new macros which replace old value with new value and then (x)decref old value. #define Py_XXX(ptr, value) \ { \ PyObject *__tmp__ = ptr; \ ptr = new_value; \ Py_DECREF(__tmp__); \ } Listed in order of receipt: 1. Py_(X)SETREF. 2. Py_(X)ASSIGN. 3. Py_(X)DECREC_REPLACE. 4. Py_REF_ASSIGN (Py_XREF_ASSIGN? Py_REF_XASSIGN?). 5. Py_(X)REPLACE. 6. Py_(X)STORE 7. Py_CLEAR_AND_SET. 8. Py_SET_AND_(X)DECREF. 9. Py_(X)DECREF_AND_ASSIGN. 10. Py_ASSIGN_AND_(X)DECREF. 11. Other... Let's choose the least confusing names. See discussions at: http://bugs.python.org/issue3081 http://bugs.python.org/issue16447 http://bugs.python.org/issue20440 http://comments.gmane.org/gmane.comp.python.devel/145346 10 20
by Chris Angelico March 13, 2014
March 13, 2014 PEP: 463 Title: Exception-catching expressions Version: $Revision$ Last-Modified: $Date$ Author: Chris Angelico <rosuav(a)gmail.com> Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 15-Feb-2014 Python-Version: 3.5 Post-History: 16-Feb-2014, 21-Feb-2014 Abstract ======== Just as PEP 308 introduced a means of value-based conditions in an expression, this system allows exception-based conditions to be used as part of an expression. Motivation ========== A number of functions and methods have parameters which will cause them to return a specified value instead of raising an exception. The current system is ad-hoc and inconsistent, and requires that each function be individually written to have this functionality; not all support this. * dict.get(key, default) - second positional argument in place of KeyError * next(iter, default) - second positional argument in place of StopIteration * list.pop() - no way to return a default * seq[index] - no way to handle a bounds error * min(sequence, default=default) - keyword argument in place of ValueError * sum(sequence, start=default) - slightly different but can do the same job * statistics.mean(data) - no way to handle an empty iterator Rationale ========= The current system requires that a function author predict the need for a default, and implement support for it. If this is not done, a full try/except block is needed. Since try/except is a statement, it is impossible to catch exceptions in the middle of an expression. Just as if/else does for conditionals and lambda does for function definitions, so does this allow exception catching in an expression context. This provides a clean and consistent way for a function to provide a default: it simply raises an appropriate exception, and the caller catches it. With some situations, an LBYL technique can be used (checking if some sequence has enough length before indexing into it, for instance). This is not safe in all cases, but as it is often convenient, programmers will be tempted to sacrifice the safety of EAFP in favour of the notational brevity of LBYL. Additionally, some LBYL techniques (eg involving getattr with three arguments) warp the code into looking like literal strings rather than attribute lookup, which can impact readability. A convenient EAFP notation solves all of this. There's no convenient way to write a helper function to do this; the nearest is something ugly using either lambda:: def except_(expression, exception_list, default): try: return expression() except exception_list: return default() value = except_(lambda: 1/x, ZeroDivisionError, lambda: float("nan")) which is clunky, and unable to handle multiple exception clauses; or eval:: def except_(expression, exception_list, default): try: return eval(expression, globals_of_caller(), locals_of_caller()) except exception_list as exc: l = locals_of_caller().copy() l['exc'] = exc return eval(default, globals_of_caller(), l) def globals_of_caller(): return sys._getframe(2).f_globals def locals_of_caller(): return sys._getframe(2).f_locals value = except_("""1/x""",ZeroDivisionError,""" "Can't divide by zero" """) which is even clunkier, and relies on implementation-dependent hacks. (Writing globals_of_caller() and locals_of_caller() for interpreters other than CPython is left as an exercise for the reader.) Raymond Hettinger `expresses`__ a desire for such a consistent API. Something similar has been `requested`__ `multiple`__ `times`__ in the past. __ https://mail.python.org/pipermail/python-ideas/2014-February/025443.html __ https://mail.python.org/pipermail/python-ideas/2013-March/019760.html __ https://mail.python.org/pipermail/python-ideas/2009-August/005441.html __ https://mail.python.org/pipermail/python-ideas/2008-August/001801.html Proposal ======== Just as the 'or' operator and the three part 'if-else' expression give short circuiting methods of catching a falsy value and replacing it, this syntax gives a short-circuiting method of catching an exception and replacing it. This currently works:: lst = [1, 2, None, 3] value = lst[2] or "No value" The proposal adds this:: lst = [1, 2] value = lst[2] except IndexError: "No value" Specifically, the syntax proposed is:: expr except exception_list: default where expr, exception_list, and default are all expressions. First, expr is evaluated. If no exception is raised, its value is the value of the overall expression. If any exception is raised, exception_list is evaluated, and should result in either a type or a tuple, just as with the statement form of try/except. Any matching exception will result in the corresponding default expression being evaluated and becoming the value of the expression. As with the statement form of try/except, non-matching exceptions will propagate upward. Note that the current proposal does not allow the exception object to be captured. Where this is needed, the statement form must be used. (See below for discussion and elaboration on this.) This ternary operator would be between lambda and if/else in precedence. Consider this example of a two-level cache:: for key in sequence: x = (lvl1[key] except KeyError: (lvl2[key] except KeyError: f(key))) # do something with x This cannot be rewritten as:: x = lvl1.get(key, lvl2.get(key, f(key))) which, despite being shorter, defeats the purpose of the cache, as it must calculate a default value to pass to get(). The .get() version calculates backwards; the exception-testing version calculates forwards, as would be expected. The nearest useful equivalent would be:: x = lvl1.get(key) or lvl2.get(key) or f(key) which depends on the values being nonzero, as well as depending on the cache object supporting this functionality. Alternative Proposals ===================== Discussion on python-ideas brought up the following syntax suggestions:: value = expr except default if Exception [as e] value = expr except default for Exception [as e] value = expr except default from Exception [as e] value = expr except Exception [as e] return default value = expr except (Exception [as e]: default) value = expr except Exception [as e] try default value = expr except Exception [as e] continue with default value = default except Exception [as e] else expr value = try expr except Exception [as e]: default value = expr except default # Catches anything value = expr except(Exception) default # Catches only the named type(s) value = default if expr raise Exception value = expr or else default if Exception value = expr except Exception [as e] -> default value = expr except Exception [as e] pass default It has also been suggested that a new keyword be created, rather than reusing an existing one. Such proposals fall into the same structure as the last form, but with a different keyword in place of 'pass'. Suggestions include 'then', 'when', and 'use'. Also, in the context of the "default if expr raise Exception" proposal, it was suggested that a new keyword "raises" be used. All forms involving the 'as' capturing clause have been deferred from this proposal in the interests of simplicity, but are preserved in the table above as an accurate record of suggestions. Open Issues =========== Parentheses around the entire expression ---------------------------------------- Generator expressions require parentheses, unless they would be strictly redundant. Ambiguities with except expressions could be resolved in the same way, forcing nested except-in-except trees to be correctly parenthesized and requiring that the outer expression be clearly delineated. `Steven D'Aprano elaborates on the issue.`__ __ https://mail.python.org/pipermail/python-ideas/2014-February/025647.html Example usage ============= For each example, an approximately-equivalent statement form is given, to show how the expression will be parsed. These are not always strictly equivalent, but will accomplish the same purpose. It is NOT safe for the interpreter to translate one into the other. A number of these examples are taken directly from the Python standard library, with file names and line numbers correct as of early Feb 2014. Many of these patterns are extremely common. Retrieve an argument, defaulting to None:: cond = args[1] except IndexError: None # Lib/pdb.py:803: try: cond = args[1] except IndexError: cond = None Fetch information from the system if available:: pwd = os.getcwd() except OSError: None # Lib/tkinter/filedialog.py:210: try: pwd = os.getcwd() except OSError: pwd = None Attempt a translation, falling back on the original:: e.widget = self._nametowidget(W) except KeyError: W # Lib/tkinter/__init__.py:1222: try: e.widget = self._nametowidget(W) except KeyError: e.widget = W Read from an iterator, continuing with blank lines once it's exhausted:: line = readline() except StopIteration: '' # Lib/lib2to3/pgen2/tokenize.py:370: try: line = readline() except StopIteration: line = '' Retrieve platform-specific information (note the DRY improvement); this particular example could be taken further, turning a series of separate assignments into a single large dict initialization:: # sys.abiflags may not be defined on all platforms. _CONFIG_VARS['abiflags'] = sys.abiflags except AttributeError: '' # Lib/sysconfig.py:529: try: _CONFIG_VARS['abiflags'] = sys.abiflags except AttributeError: # sys.abiflags may not be defined on all platforms. _CONFIG_VARS['abiflags'] = '' Retrieve an indexed item, defaulting to None (similar to dict.get):: def getNamedItem(self, name): return self._attrs[name] except KeyError: None # Lib/xml/dom/minidom.py:573: def getNamedItem(self, name): try: return self._attrs[name] except KeyError: return None Translate numbers to names, falling back on the numbers:: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: tarinfo.gid u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: tarinfo.uid # Lib/tarfile.py:2198: try: g = grp.getgrnam(tarinfo.gname)[2] except KeyError: g = tarinfo.gid try: u = pwd.getpwnam(tarinfo.uname)[2] except KeyError: u = tarinfo.uid Perform some lengthy calculations in EAFP mode, handling division by zero as a sort of sticky NaN:: value = calculate(x) except ZeroDivisionError: float("nan") try: value = calculate(x) except ZeroDivisionError: value = float("nan") Calculate the mean of a series of numbers, falling back on zero:: value = statistics.mean(lst) except statistics.StatisticsError: 0 try: value = statistics.mean(lst) except statistics.StatisticsError: value = 0 Retrieving a message from either a cache or the internet, with auth check:: logging.info("Message shown to user: %s",((cache[k] except LookupError: (backend.read(k) except OSError: 'Resource not available') ) if check_permission(k) else 'Access denied' ) except BaseException: "This is like a bare except clause") try: if check_permission(k): try: _ = cache[k] except LookupError: try: _ = backend.read(k) except OSError: _ = 'Resource not available' else: _ = 'Access denied' except BaseException: _ = "This is like a bare except clause" logging.info("Message shown to user: %s", _) Looking up objects in a sparse list of overrides:: (overrides[x] or default except IndexError: default).ping() try: (overrides[x] or default).ping() except IndexError: default.ping() Narrowing of exception-catching scope ------------------------------------- The following examples, taken directly from Python's standard library, demonstrate how the scope of the try/except can be conveniently narrowed. To do this with the statement form of try/except would require a temporary variable, but it's far cleaner as an expression. Lib/ipaddress.py:343:: try: ips.append(ip.ip) except AttributeError: ips.append(ip.network_address) Becomes:: ips.append(ip.ip except AttributeError: ip.network_address) The expression form is nearly equivalent to this:: try: _ = ip.ip except AttributeError: _ = ip.network_address ips.append(_) Lib/tempfile.py:130:: try: dirlist.append(_os.getcwd()) except (AttributeError, OSError): dirlist.append(_os.curdir) Becomes:: dirlist.append(_os.getcwd() except (AttributeError, OSError): _os.curdir) Lib/asyncore.py:264:: try: status.append('%s:%d' % self.addr) except TypeError: status.append(repr(self.addr)) Becomes:: status.append('%s:%d' % self.addr except TypeError: repr(self.addr)) Comparisons with other languages ================================ (With thanks to Andrew Barnert for compiling this section.) `Ruby's`__ "begin…rescue…rescue…else…ensure…end" is an expression (potentially with statements inside it). It has the equivalent of an "as" clause, and the equivalent of bare except. And it uses no punctuation or keyword between the bare except/exception class/exception class with as clause and the value. (And yes, it's ambiguous unless you understand Ruby's statement/expression rules.) __ http://www.skorks.com/2009/09/ruby-exceptions-and-exception-handling/ :: x = begin computation() rescue MyException => e default(e) end; x = begin computation() rescue MyException default() end; x = begin computation() rescue default() end; x = begin computation() rescue MyException default() rescue OtherException other() end; In terms of this PEP:: x = computation() except MyException as e default(e) x = computation() except MyException default(e) x = computation() except default(e) x = computation() except MyException default() except OtherException other() `Erlang`__ has a try expression that looks like this:: __ http://erlang.org/doc/reference_manual/expressions.html#id79284 x = try computation() catch MyException:e -> default(e) end; x = try computation() catch MyException:e -> default(e); OtherException:e -> other(e) end; The class and "as" name are mandatory, but you can use "_" for either. There's also an optional "when" guard on each, and a "throw" clause that you can catch, which I won't get into. To handle multiple exceptions, you just separate the clauses with semicolons, which I guess would map to commas in Python. So:: x = try computation() except MyException as e -> default(e) x = try computation() except MyException as e -> default(e), OtherException as e->other_default(e) Erlang also has a "catch" expression, which, despite using the same keyword, is completely different, and you don't want to know about it. The ML family has two different ways of dealing with this, "handle" and "try"; the difference between the two is that "try" pattern-matches the exception, which gives you the effect of multiple except clauses and as clauses. In either form, the handler clause is punctuated by "=>" in some dialects, "->" in others. To avoid confusion, I'll write the function calls in Python style. Here's `SML's`__ "handle":: __ http://www.cs.cmu.edu/~rwh/introsml/core/exceptions.htm let x = computation() handle MyException => default();; Here's `OCaml's`__ "try":: __ http://www2.lib.uchicago.edu/keith/ocaml-class/exceptions.html let x = try computation() with MyException explanation -> default(explanation);; let x = try computation() with MyException(e) -> default(e) | MyOtherException() -> other_default() | (e) -> fallback(e);; In terms of this PEP, these would be something like:: x = computation() except MyException => default() x = try computation() except MyException e -> default() x = (try computation() except MyException as e -> default(e) except MyOtherException -> other_default() except BaseException as e -> fallback(e)) Many ML-inspired but not-directly-related languages from academia mix things up, usually using more keywords and fewer symbols. So, the `Oz`__ would map to Python as:: __ http://mozart.github.io/mozart-v1/doc-1.4.0/tutorial/node5.html x = try computation() catch MyException as e then default(e) Many Lisp-derived languages, like `Clojure,`__ implement try/catch as special forms (if you don't know what that means, think function-like macros), so you write, effectively:: __ http://clojure.org/special_forms#Special%20Forms--(try%20expr*%20catch-clau… try(computation(), catch(MyException, explanation, default(explanation))) try(computation(), catch(MyException, explanation, default(explanation)), catch(MyOtherException, explanation, other_default(explanation))) In Common Lisp, this is done with a slightly clunkier `"handler-case" macro,`__ but the basic idea is the same. __ http://clhs.lisp.se/Body/m_hand_1.htm The Lisp style is, surprisingly, used by some languages that don't have macros, like Lua, where `xpcall`__ takes functions. Writing lambdas Python-style instead of Lua-style:: __ http://www.gammon.com.au/scripts/doc.php?lua=xpcall x = xpcall(lambda: expression(), lambda e: default(e)) This actually returns (true, expression()) or (false, default(e)), but I think we can ignore that part. Haskell is actually similar to Lua here (except that it's all done with monads, of course):: x = do catch(lambda: expression(), lambda e: default(e)) You can write a pattern matching expression within the function to decide what to do with it; catching and re-raising exceptions you don't want is cheap enough to be idiomatic. But Haskell infixing makes this nicer:: x = do expression() `catch` lambda: default() x = do expression() `catch` lambda e: default(e) And that makes the parallel between the lambda colon and the except colon in the proposal much more obvious:: x = expression() except Exception: default() x = expression() except Exception as e: default(e) `Tcl`__ has the other half of Lua's xpcall; catch is a function which returns true if an exception was caught, false otherwise, and you get the value out in other ways. And it's all built around the the implicit quote-and-exec that everything in Tcl is based on, making it even harder to describe in Python terms than Lisp macros, but something like:: __ http://wiki.tcl.tk/902 if {[ catch("computation()") "explanation"]} { default(explanation) } `Smalltalk`__ is also somewhat hard to map to Python. The basic version would be:: __ http://smalltalk.gnu.org/wiki/exceptions x := computation() on:MyException do:default() … but that's basically Smalltalk's passing-arguments-with-colons syntax, not its exception-handling syntax. Deferred sub-proposals ====================== Multiple except clauses ----------------------- An examination of use-cases shows that this is not needed as often as it would be with the statement form, and as its syntax is a point on which consensus has not been reached, the entire feature is deferred. In order to ensure compatibility with future versions, ensure that any consecutive except operators are parenthesized to guarantee the interpretation you expect. Multiple 'except' keywords can be used, and they will all catch exceptions raised in the original expression (only):: # Will catch any of the listed exceptions thrown by expr; # any exception thrown by a default expression will propagate. value = (expr except Exception1 [as e]: default1 except Exception2 [as e]: default2 # ... except ExceptionN [as e]: defaultN ) Using parentheses to force an alternative interpretation works as expected:: # Will catch an Exception2 thrown by either expr or default1 value = ( (expr except Exception1: default1) except Exception2: default2 ) # Will catch an Exception2 thrown by default1 only value = (expr except Exception1: (default1 except Exception2: default2) ) This last form is confusing and should be discouraged by PEP 8, but it is syntactically legal: you can put any sort of expression inside a ternary-except; ternary-except is an expression; therefore you can put a ternary-except inside a ternary-except. Open question: Where there are multiple except clauses, should they be separated by commas? It may be easier for the parser, that way:: value = (expr except Exception1 [as e]: default1, except Exception2 [as e]: default2, # ... except ExceptionN [as e]: defaultN, ) with an optional comma after the last, as per tuple rules. Downside: Omitting the comma would be syntactically valid, and would have almost identical semantics, but would nest the entire preceding expression in its exception catching rig - a matching exception raised in the default clause would be caught by the subsequent except clause. As this difference is so subtle, it runs the risk of being a major bug magnet. As a mitigation of this risk, this form:: value = expr except Exception1: default1 except Exception2: default2 could be syntactically forbidden, and parentheses required if the programmer actually wants that behaviour:: value = (expr except Exception1: default1) except Exception2: default2 This would prevent the accidental omission of a comma from changing the expression's meaning. Capturing the exception object ------------------------------ In a try/except block, the use of 'as' to capture the exception object creates a local name binding, and implicitly deletes that binding in a finally clause. As 'finally' is not a part of this proposal (see below), this makes it tricky to describe; also, this use of 'as' gives a way to create a name binding in an expression context. Should the default clause have an inner scope in which the name exists, shadowing anything of the same name elsewhere? Should it behave the same way the statement try/except does, and unbind the name? Should it bind the name and leave it bound? (Almost certainly not; this behaviour was changed in Python 3 for good reason.) Additionally, this syntax would allow a convenient way to capture exceptions in interactive Python; returned values are captured by "_", but exceptions currently are not. This could be spelled: >>> expr except Exception as e: e (The inner scope idea is tempting, but currently CPython handles list comprehensions with a nested function call, as this is considered easier. It may be of value to simplify both comprehensions and except expressions, but that is a completely separate proposal to this PEP; alternatively, it may be better to stick with what's known to work. `Nick Coghlan elaborates.`__) __ https://mail.python.org/pipermail/python-ideas/2014-February/025702.html An examination of the Python standard library shows that, while the use of 'as' is fairly common (occurring in roughly one except clause in five), it is extremely *uncommon* in the cases which could logically be converted into the expression form. Its few uses can simply be left unchanged. Consequently, in the interests of simplicity, the 'as' clause is not included in this proposal. A subsequent Python version can add this without breaking any existing code, as 'as' is already a keyword. One example where this could possibly be useful is Lib/imaplib.py:568:: try: typ, dat = self._simple_command('LOGOUT') except: typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]] This could become:: typ, dat = (self._simple_command('LOGOUT') except BaseException as e: ('NO', '%s: %s' % (type(e), e))) Or perhaps some other variation. This is hardly the most compelling use-case, but an intelligent look at this code could tidy it up significantly. In the absence of further examples showing any need of the exception object, I have opted to defer indefinitely the recommendation. Rejected sub-proposals ====================== finally clause -------------- The statement form try... finally or try... except... finally has no logical corresponding expression form. Therefore the finally keyword is not a part of this proposal, in any way. Bare except having different meaning ------------------------------------ With several of the proposed syntaxes, omitting the exception type name would be easy and concise, and would be tempting. For convenience's sake, it might be advantageous to have a bare 'except' clause mean something more useful than "except BaseException". Proposals included having it catch Exception, or some specific set of "common exceptions" (subclasses of a new type called ExpressionError), or have it look for a tuple named ExpressionError in the current scope, with a built-in default such as (ValueError, UnicodeError, AttributeError, EOFError, IOError, OSError, LookupError, NameError, ZeroDivisionError). All of these were rejected, for severa reasons. * First and foremost, consistency with the statement form of try/except would be broken. Just as a list comprehension or ternary if expression can be explained by "breaking it out" into its vertical statement form, an expression-except should be able to be explained by a relatively mechanical translation into a near-equivalent statement. Any form of syntax common to both should therefore have the same semantics in each, and above all should not have the subtle difference of catching more in one than the other, as it will tend to attract unnoticed bugs. * Secondly, the set of appropriate exceptions to catch would itself be a huge point of contention. It would be impossible to predict exactly which exceptions would "make sense" to be caught; why bless some of them with convenient syntax and not others? * And finally (this partly because the recommendation was that a bare except should be actively encouraged, once it was reduced to a "reasonable" set of exceptions), any situation where you catch an exception you don't expect to catch is an unnecessary bug magnet. Consequently, the use of a bare 'except' is down to two possibilities: either it is syntactically forbidden in the expression form, or it is permitted with the exact same semantics as in the statement form (namely, that it catch BaseException and be unable to capture it with 'as'). Bare except clauses ------------------- PEP 8 rightly advises against the use of a bare 'except'. While it is syntactically legal in a statement, and for backward compatibility must remain so, there is little value in encouraging its use. In an expression except clause, "except:" is a SyntaxError; use the equivalent long-hand form "except BaseException:" instead. A future version of Python MAY choose to reinstate this, which can be done without breaking compatibility. Parentheses around the except clauses ------------------------------------- Should it be legal to parenthesize the except clauses, separately from the expression that could raise? Example:: value = expr ( except Exception1 [as e]: default1 except Exception2 [as e]: default2 # ... except ExceptionN [as e]: defaultN ) This is more compelling when one or both of the deferred sub-proposals of multiple except clauses and/or exception capturing is included. In their absence, the parentheses would be thus:: value = expr except ExceptionType: default value = expr (except ExceptionType: default) The advantage is minimal, and the potential to confuse a reader into thinking the except clause is separate from the expression, or into thinking this is a function call, makes this non-compelling. The expression can, of course, be parenthesized if desired, as can the default:: value = (expr) except ExceptionType: (default) Short-hand for "except: pass" ----------------------------- The following was been suggested as a similar short-hand, though not technically an expression:: statement except Exception: pass try: statement except Exception: pass For instance, a common use-case is attempting the removal of a file:: os.unlink(some_file) except OSError: pass There is an equivalent already in Python 3.4, however, in contextlib:: from contextlib import suppress with suppress(OSError): os.unlink(some_file) As this is already a single line (or two with a break after the colon), there is little need of new syntax and a confusion of statement vs expression to achieve this. Copyright ========= This document has been placed in the public domain. .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 coding: utf-8 End: 32 176
by Kristján Valur Jónsson March 4, 2014
March 4, 2014 Hi there. The discussion on http://bugs.python.org/issue20440 started me thinking that much of this bikeshedding could be avoided if we weren't constrained to writing macros for all of this stuff. For example, a Py_INLINE(PyObject *) Py_Incref(PyObject *obj) { Py_INCREF(obj); return obj; } could be used in a Py_Assign() function, if a new reference were wanted: Py_INLINE(void) Py_Assign(PyObject ** target, PyObject *obj) { PyObject *tmp = *target; *target = tmp; Py_DECREF(tmp); } So that you could then safely write code like Py_Assign(&MyVar, Py_Incref(obj)); This would also allow you to stop writing various super macros to try to cater to all possible permutations. Now, Larry Hastings pointed out that we support C89 which doesn't support Inlines. Rather than suggesting here that we update that compatibility requirement, how about adding a Py_INLINE() macro.? This would be like Py_LOCAL_INLINE() except that it would drop the "static" keyword, unless inline isn't supported: #if defined(_MSC_VER) #define Py_INLINE(type) __inline type #elif defined(USE_INLINE) #define Py_INLINE(type) inline type #else #define Py_INLINE(type) static type #endif The only question is with the last line. How many platforms actually _do_not_ have inlines? Would writing stuff like this be considered problematic for those platforms? Note, that I'm not suggesting replacing macros all over the place, only for new code. Another question is: Is "static inline" in any practical way different from "inline"? It would be great to get rid of macros in code. It would be great for debugging too! K 9 14
by Burgoon, Jason March 1, 2014
March 1, 2014 Good day Python Dev Team - One of our users has reported the following: I have installed the given msi on 64 bit as per the install instructions document. One of the shortcuts 'Start Menu\Programs\Python 3.3\ Module Docs' is not getting launched. When I launch this shortcut, it is not opening any window. I have tried with admin user and non-admin user. Is this expected behavior? Please advise and thanks for your help. Jason [http://intranet.ds.global/technology/employees/Documents/Communication%20Re…] Jason Burgoon Application Management Services - Coordinator 4333 Edgewood Rd NE, Cedar Rapids, IA 52499 Phone: (319) 355-4534 Email: jason.burgoon(a)transamerica.com<mailto:jason.burgoon@transamerica.com> Click here<http://intranet.ds.global/technology/Pages/default.aspx> to visit the AGT Website 3 2