Convert 10 PEPs to reSt (#180)

This commit is contained in:
Mariatta 2017-01-19 10:00:30 -08:00 committed by Brett Cannon
parent fdc405df22
commit 87dc92a34e
10 changed files with 1198 additions and 1042 deletions

View File

@ -5,12 +5,14 @@ Last-Modified: $Date$
Author: nowonder@nowonder.de (Peter Schneider-Kamp) Author: nowonder@nowonder.de (Peter Schneider-Kamp)
Status: Deferred Status: Deferred
Type: Standards Track Type: Standards Track
Content-Type: text/x-rst
Created: 22-Aug-2000 Created: 22-Aug-2000
Python-Version: 2.1 Python-Version: 2.1
Post-History: Post-History:
Introduction Introduction
============
This PEP describes the often proposed feature of exposing the loop This PEP describes the often proposed feature of exposing the loop
counter in for-loops. This PEP tracks the status and ownership of counter in for-loops. This PEP tracks the status and ownership of
@ -22,9 +24,10 @@ Introduction
Motivation Motivation
==========
Standard for-loops in Python iterate over the elements of a Standard for-loops in Python iterate over the elements of a
sequence[1]. Often it is desirable to loop over the indices or sequence [1]_. Often it is desirable to loop over the indices or
both the elements and the indices instead. both the elements and the indices instead.
The common idioms used to accomplish this are unintuitive. This The common idioms used to accomplish this are unintuitive. This
@ -32,54 +35,58 @@ Motivation
Loop counter iteration Loop counter iteration
======================
The current idiom for looping over the indices makes use of the The current idiom for looping over the indices makes use of the
built-in 'range' function: built-in ``range`` function::
for i in range(len(sequence)): for i in range(len(sequence)):
# work with index i # work with index i
Looping over both elements and indices can be achieved either by the Looping over both elements and indices can be achieved either by the
old idiom or by using the new 'zip' built-in function[2]: old idiom or by using the new ``zip`` built-in function [2]_::
for i in range(len(sequence)): for i in range(len(sequence)):
e = sequence[i] e = sequence[i]
# work with index i and element e # work with index i and element e
or or::
for i, e in zip(range(len(sequence)), sequence): for i, e in zip(range(len(sequence)), sequence):
# work with index i and element e # work with index i and element e
The Proposed Solutions The Proposed Solutions
======================
There are three solutions that have been discussed. One adds a There are three solutions that have been discussed. One adds a
non-reserved keyword, the other adds two built-in functions. non-reserved keyword, the other adds two built-in functions.
A third solution adds methods to sequence objects. A third solution adds methods to sequence objects.
Non-reserved keyword 'indexing' Non-reserved keyword ``indexing``
=================================
This solution would extend the syntax of the for-loop by adding This solution would extend the syntax of the for-loop by adding
an optional '<variable> indexing' clause which can also be used an optional ``<variable> indexing`` clause which can also be used
instead of the '<variable> in' clause.. instead of the ``<variable> in`` clause.
Looping over the indices of a sequence would thus become: Looping over the indices of a sequence would thus become::
for i indexing sequence: for i indexing sequence:
# work with index i # work with index i
Looping over both indices and elements would similarly be: Looping over both indices and elements would similarly be::
for i indexing e in sequence: for i indexing e in sequence:
# work with index i and element e # work with index i and element e
Built-in functions 'indices' and 'irange' Built-in functions ``indices`` and ``irange``
=============================================
This solution adds two built-in functions 'indices' and 'irange'. This solution adds two built-in functions ``indices`` and ``irange``.
The semantics of these can be described as follows: The semantics of these can be described as follows::
def indices(sequence): def indices(sequence):
return range(len(sequence)) return range(len(sequence))
@ -92,7 +99,7 @@ Built-in functions 'indices' and 'irange'
argument. argument.
The use of these functions would simplify the idioms for looping The use of these functions would simplify the idioms for looping
over the indices and over both elements and indices: over the indices and over both elements and indices::
for i in indices(sequence): for i in indices(sequence):
# work with index i # work with index i
@ -102,14 +109,15 @@ Built-in functions 'indices' and 'irange'
Methods for sequence objects Methods for sequence objects
============================
This solution proposes the addition of 'indices', 'items' This solution proposes the addition of ``indices``, ``items``
and 'values' methods to sequences, which enable looping over and ``values`` methods to sequences, which enable looping over
indices only, both indices and elements, and elements only indices only, both indices and elements, and elements only
respectively. respectively.
This would immensely simplify the idioms for looping over indices This would immensely simplify the idioms for looping over indices
and for looping over both elements and indices: and for looping over both elements and indices::
for i in sequence.indices(): for i in sequence.indices():
# work with index i # work with index i
@ -118,28 +126,30 @@ Methods for sequence objects
# work with index i and element e # work with index i and element e
Additionally it would allow to do looping over the elements Additionally it would allow to do looping over the elements
of sequences and dicitionaries in a consistent way: of sequences and dictionaries in a consistent way::
for e in sequence_or_dict.values(): for e in sequence_or_dict.values():
# do something with element e # do something with element e
Implementations Implementations
===============
For all three solutions some more or less rough patches exist For all three solutions some more or less rough patches exist
as patches at SourceForge: as patches at SourceForge:
'for i indexing a in l': exposing the for-loop counter[3] - ``for i indexing a in l``: exposing the for-loop counter [3]_
add indices() and irange() to built-ins[4] - add ``indices()`` and ``irange()`` to built-ins [4]_
add items() method to listobject[5] - add ``items()`` method to listobject [5]_
All of them have been pronounced on and rejected by the BDFL. All of them have been pronounced on and rejected by the BDFL.
Note that the 'indexing' keyword is only a NAME in the Note that the ``indexing`` keyword is only a ``NAME`` in the
grammar and so does not hinder the general use of 'indexing'. grammar and so does not hinder the general use of ``indexing``.
Backward Compatibility Issues Backward Compatibility Issues
=============================
As no keywords are added and the semantics of existing code As no keywords are added and the semantics of existing code
remains unchanged, all three solutions can be implemented remains unchanged, all three solutions can be implemented
@ -147,20 +157,27 @@ Backward Compatibility Issues
Copyright Copyright
=========
This document has been placed in the public domain. This document has been placed in the public domain.
References References
==========
[1] http://docs.python.org/reference/compound_stmts.html#for .. [1] http://docs.python.org/reference/compound_stmts.html#for
[2] Lockstep Iteration, PEP 201
[3] http://sourceforge.net/patch/download.php?id=101138 .. [2] Lockstep Iteration, PEP 201
[4] http://sourceforge.net/patch/download.php?id=101129
[5] http://sourceforge.net/patch/download.php?id=101178 .. [3] http://sourceforge.net/patch/download.php?id=101138
.. [4] http://sourceforge.net/patch/download.php?id=101129
.. [5] http://sourceforge.net/patch/download.php?id=101178
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil

View File

@ -5,23 +5,28 @@ Last-Modified: $Date$
Author: moshez@zadka.site.co.il (Moshe Zadka) Author: moshez@zadka.site.co.il (Moshe Zadka)
Status: Rejected Status: Rejected
Type: Informational Type: Informational
Content-Type: text/x-rst
Created: 31-Jul-2000 Created: 31-Jul-2000
Post-History: Post-History:
Superseded-By: 287 Superseded-By: 287
Notice Notice
======
This PEP is rejected by the author. It has been superseded by PEP This PEP is rejected by the author. It has been superseded by PEP
287. 287.
Abstract Abstract
========
Named Python objects, such as modules, classes and functions, have a Named Python objects, such as modules, classes and functions, have a
string attribute called __doc__. If the first expression inside string attribute called ``__doc__``. If the first expression inside
the definition is a literal string, that string is assigned the definition is a literal string, that string is assigned
to the __doc__ attribute. to the ``__doc__`` attribute.
The __doc__ attribute is called a documentation string, or docstring. The ``__doc__`` attribute is called a documentation string, or docstring.
It is often used to summarize the interface of the module, class or It is often used to summarize the interface of the module, class or
function. However, since there is no common format for documentation function. However, since there is no common format for documentation
string, tools for extracting docstrings and transforming those into string, tools for extracting docstrings and transforming those into
@ -29,7 +34,9 @@ Abstract
up in abundance, and those that do exist are for the most part up in abundance, and those that do exist are for the most part
unmaintained and unused. unmaintained and unused.
Perl Documentation Perl Documentation
==================
In Perl, most modules are documented in a format called POD -- Plain In Perl, most modules are documented in a format called POD -- Plain
Old Documentation. This is an easy-to-type, very low level format Old Documentation. This is an easy-to-type, very low level format
@ -37,7 +44,9 @@ Perl Documentation
POD documentation into other formats: info, HTML and man pages, among POD documentation into other formats: info, HTML and man pages, among
others. However, in Perl, the information is not available at run-time. others. However, in Perl, the information is not available at run-time.
Java Documentation Java Documentation
==================
In Java, special comments before classes and functions function to In Java, special comments before classes and functions function to
document the code. A program to extract these, and turn them into document the code. A program to extract these, and turn them into
@ -45,7 +54,9 @@ Java Documentation
Java distribution. However, the only output format that is supported Java distribution. However, the only output format that is supported
is HTML, and JavaDoc has a very intimate relationship with HTML. is HTML, and JavaDoc has a very intimate relationship with HTML.
Python Docstring Goals Python Docstring Goals
======================
Python documentation string are easy to spot during parsing, and are Python documentation string are easy to spot during parsing, and are
also available to the runtime interpreter. This double purpose is also available to the runtime interpreter. This double purpose is
@ -57,7 +68,9 @@ Python Docstring Goals
better documentation-extraction tools, since it causes docstrings to better documentation-extraction tools, since it causes docstrings to
contain little information, which is hard to parse. contain little information, which is hard to parse.
High Level Solutions High Level Solutions
====================
To counter the objection that the strings take up place in the running To counter the objection that the strings take up place in the running
program, it is suggested that documentation extraction tools will program, it is suggested that documentation extraction tools will
@ -66,9 +79,11 @@ High Level Solutions
in the interactive interpreter, so it should contain a few summary in the interactive interpreter, so it should contain a few summary
lines. lines.
Docstring Format Goals
These are the goals for the docstring format, as discussed ad neasum Docstring Format Goals
======================
These are the goals for the docstring format, as discussed ad nauseam
in the doc-sig. in the doc-sig.
1. It must be easy to type with any standard text editor. 1. It must be easy to type with any standard text editor.
@ -80,42 +95,50 @@ Docstring Format Goals
5. It must be possible to write a module's entire documentation in 5. It must be possible to write a module's entire documentation in
docstrings, without feeling hampered by the markup language. docstrings, without feeling hampered by the markup language.
Docstring Contents Docstring Contents
==================
For requirement 5. above, it is needed to specify what must be For requirement 5. above, it is needed to specify what must be
in docstrings. in docstrings.
At least the following must be available: At least the following must be available:
a. A tag that means "this is a Python ``something'', guess what" a. A tag that means "this is a Python `something`, guess what"
Example: In the sentence "The POP3 class", we need to markup "POP3" Example: In the sentence "The POP3 class", we need to markup "POP3"
so. The parser will be able to guess it is a class from the contents so. The parser will be able to guess it is a class from the contents
of the poplib module, but we need to make it guess. of the ``poplib`` module, but we need to make it guess.
b. Tags that mean "this is a Python class/module/class var/instance var..." b. Tags that mean "this is a Python class/module/class var/instance var..."
Example: The usual Python idiom for singleton class A is to have _A Example: The usual Python idiom for singleton class ``A`` is to have ``_A``
as the class, and A a function which returns _A objects. It's usual as the class, and ``A`` a function which returns ``_A`` objects. It's usual
to document the class, nonetheless, as being A. This requires the to document the class, nonetheless, as being ``A``. This requires the
strength to say "The class A" and have A hyperlinked and marked-up strength to say "The class ``A``" and have ``A`` hyperlinked and marked-up
as a class. as a class.
c. An easy way to include Python source code/Python interactive sessions c. An easy way to include Python source code/Python interactive sessions
d. Emphasis/bold d. Emphasis/bold
e. List/tables e. List/tables
Docstring Basic Structure Docstring Basic Structure
=========================
The documentation strings will be in StructuredTextNG The documentation strings will be in StructuredTextNG
(http://www.zope.org/Members/jim/StructuredTextWiki/StructuredTextNG) (http://www.zope.org/Members/jim/StructuredTextWiki/StructuredTextNG)
Since StructuredText is not yet strong enough to handle (a) and (b) Since StructuredText is not yet strong enough to handle (a) and (b)
above, we will need to extend it. I suggest using above, we will need to extend it. I suggest using
'[<optional description>:python identifier]'. ``[<optional description>:python identifier]``.
E.g.: [class:POP3], [:POP3.list], etc. If the description is missing, E.g.: ``[class:POP3]``, ``[:POP3.list]``, etc. If the description is missing,
a guess will be made from the text. a guess will be made from the text.
Unresolved Issues Unresolved Issues
=================
Is there a way to escape characters in ST? If so, how? Is there a way to escape characters in ST? If so, how?
(example: * at the beginning of a line without being bullet symbol) (example: * at the beginning of a line without being bullet symbol)
@ -130,13 +153,15 @@ Unresolved Issues
What are the guesser rules? What are the guesser rules?
Rejected Suggestions Rejected Suggestions
====================
XML -- it's very hard to type, and too cluttered to read it XML -- it's very hard to type, and too cluttered to read it comfortably.
comfortably.
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil

View File

@ -5,12 +5,14 @@ Last-Modified: $Date$
Author: gmcm@hypernet.com (Gordon McMillan) Author: gmcm@hypernet.com (Gordon McMillan)
Status: Deferred Status: Deferred
Type: Standards Track Type: Standards Track
Content-Type: text/x-rst
Created: 14-Aug-2000 Created: 14-Aug-2000
Python-Version: 2.1 Python-Version: 2.1
Post-History: Post-History:
Introduction Introduction
============
This PEP discusses changes required to core Python in order to This PEP discusses changes required to core Python in order to
efficiently support generators, microthreads and coroutines. It is efficiently support generators, microthreads and coroutines. It is
@ -18,11 +20,11 @@ Introduction
to support these facilities. The focus of this PEP is strictly on to support these facilities. The focus of this PEP is strictly on
the changes required to allow these extensions to work. the changes required to allow these extensions to work.
While these PEPs are based on Christian Tismer's Stackless[1] While these PEPs are based on Christian Tismer's Stackless [1]_
implementation, they do not regard Stackless as a reference implementation, they do not regard Stackless as a reference
implementation. Stackless (with an extension module) implements implementation. Stackless (with an extension module) implements
continuations, and from continuations one can implement continuations, and from continuations one can implement
coroutines, microthreads (as has been done by Will Ware[2]) and coroutines, microthreads (as has been done by Will Ware [2]_) and
generators. But in more that a year, no one has found any other generators. But in more that a year, no one has found any other
productive use of continuations, so there seems to be no demand productive use of continuations, so there seems to be no demand
for their support. for their support.
@ -34,10 +36,11 @@ Introduction
Background Background
==========
Generators and coroutines have been implemented in a number of Generators and coroutines have been implemented in a number of
languages in a number of ways. Indeed, Tim Peters has done pure languages in a number of ways. Indeed, Tim Peters has done pure
Python implementations of generators[3] and coroutines[4] using Python implementations of generators [3]_ and coroutines [4]_ using
threads (and a thread-based coroutine implementation exists for threads (and a thread-based coroutine implementation exists for
Java). However, the horrendous overhead of a thread-based Java). However, the horrendous overhead of a thread-based
implementation severely limits the usefulness of this approach. implementation severely limits the usefulness of this approach.
@ -62,6 +65,7 @@ Background
Discussion Discussion
==========
The first thing to note is that Python, while it mingles The first thing to note is that Python, while it mingles
interpreter data (normal C stack usage) with Python data (the interpreter data (normal C stack usage) with Python data (the
@ -91,6 +95,7 @@ Discussion
Problems Problems
========
The major difficulty with this approach is C calling Python. The The major difficulty with this approach is C calling Python. The
problem is that the C stack now holds a nested execution of the problem is that the C stack now holds a nested execution of the
@ -121,22 +126,22 @@ Problems
it's not quite as obvious when we're done. While Stackless is not it's not quite as obvious when we're done. While Stackless is not
implemented this way, it has to deal with the same issues. implemented this way, it has to deal with the same issues.
In normal Python, PyEval_EvalCode is used to build a frame and In normal Python, ``PyEval_EvalCode`` is used to build a frame and
execute it. Stackless Python introduces the concept of a execute it. Stackless Python introduces the concept of a
FrameDispatcher. Like PyEval_EvalCode, it executes one frame. But ``FrameDispatcher``. Like ``PyEval_EvalCode``, it executes one frame. But
the interpreter may signal the FrameDispatcher that a new frame the interpreter may signal the ``FrameDispatcher`` that a new frame
has been swapped in, and the new frame should be executed. When a has been swapped in, and the new frame should be executed. When a
frame completes, the FrameDispatcher follows the back pointer to frame completes, the ``FrameDispatcher`` follows the back pointer to
resume the "calling" frame. resume the "calling" frame.
So Stackless transforms recursions into a loop, but it is not the So Stackless transforms recursions into a loop, but it is not the
FrameDispatcher that manages the frames. This is done by the ``FrameDispatcher`` that manages the frames. This is done by the
interpreter (or an extension that knows what it's doing). interpreter (or an extension that knows what it's doing).
The general idea is that where C code needs to execute Python The general idea is that where C code needs to execute Python
code, it creates a frame for the Python code, setting its back code, it creates a frame for the Python code, setting its back
pointer to the current frame. Then it swaps in the frame, signals pointer to the current frame. Then it swaps in the frame, signals
the FrameDispatcher and gets out of the way. The C stack is now the ``FrameDispatcher`` and gets out of the way. The C stack is now
clean - the Python code can transfer control to any other frame clean - the Python code can transfer control to any other frame
(if an extension gives it the means to do so). (if an extension gives it the means to do so).
@ -160,6 +165,7 @@ Problems
Advantages Advantages
==========
For normal Python, the advantage to this approach is that C stack For normal Python, the advantage to this approach is that C stack
usage becomes much smaller and more predictable. Unbounded usage becomes much smaller and more predictable. Unbounded
@ -177,14 +183,16 @@ Advantages
References References
==========
[1] http://www.stackless.com .. [1] http://www.stackless.com
[2] http://world.std.com/~wware/uthread.html .. [2] http://web.archive.org/web/20000815070602/http://world.std.com/~wware/uthread.html
[3] Demo/threads/Generator.py in the source distribution .. [3] Demo/threads/Generator.py in the source distribution
[4] http://www.stackless.com/coroutines.tim.peters.html .. [4] http://www.stackless.com/coroutines.tim.peters.html
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil

View File

@ -5,17 +5,19 @@ Last-Modified: $Date$
Author: moshez@zadka.site.co.il (Moshe Zadka), guido@python.org (Guido van Rossum) Author: moshez@zadka.site.co.il (Moshe Zadka), guido@python.org (Guido van Rossum)
Status: Withdrawn Status: Withdrawn
Type: Standards Track Type: Standards Track
Content-Type: text/x-rst
Created: 4-Nov-2000 Created: 4-Nov-2000
Python-Version: ??
Post-History: Post-History:
Withdrawal Withdrawal
==========
This PEP has been withdrawn in favor of PEP 3141. This PEP has been withdrawn in favor of PEP 3141.
Abstract Abstract
========
Today, Python's numerical model is similar to the C numeric model: Today, Python's numerical model is similar to the C numeric model:
there are several unrelated numerical types, and when operations there are several unrelated numerical types, and when operations
@ -30,16 +32,18 @@ Abstract
Rationale Rationale
=========
In usability studies, one of the least usable aspect of Python was In usability studies, one of the least usable aspect of Python was
the fact that integer division returns the floor of the division. the fact that integer division returns the floor of the division.
This makes it hard to program correctly, requiring casts to This makes it hard to program correctly, requiring casts to
float() in various parts through the code. Python's numerical ``float()`` in various parts through the code. Python's numerical
model stems from C, while a model that might be easier to work with model stems from C, while a model that might be easier to work with
can be based on the mathematical understanding of numbers. can be based on the mathematical understanding of numbers.
Other Numerical Models Other Numerical Models
======================
Perl's numerical model is that there is one type of numbers -- Perl's numerical model is that there is one type of numbers --
floating point numbers. While it is consistent and superficially floating point numbers. While it is consistent and superficially
@ -52,67 +56,72 @@ Other Numerical Models
Suggested Interface For Python's Numerical Model Suggested Interface For Python's Numerical Model
================================================
While coercion rules will remain for add-on types and classes, the While coercion rules will remain for add-on types and classes, the
built in type system will have exactly one Python type -- a built in type system will have exactly one Python type -- a
number. There are several things which can be considered "number number. There are several things which can be considered "number
methods": methods":
1. isnatural() 1. ``isnatural()``
2. isintegral() 2. ``isintegral()``
3. isrational() 3. ``isrational()``
4. isreal() 4. ``isreal()``
5. iscomplex() 5. ``iscomplex()``
6. ``isexact()``
a. isexact()
Obviously, a number which answers true to a question from 1 to 5, will Obviously, a number which answers true to a question from 1 to 5, will
also answer true to any following question. If "isexact()" is not true, also answer true to any following question. If ``isexact()`` is not true,
then any answer might be wrong. then any answer might be wrong.
(But not horribly wrong: it's close to the truth.) (But not horribly wrong: it's close to the truth.)
Now, there is two thing the models promises for the field operations Now, there is two thing the models promises for the field operations
(+, -, /, *): (+, -, /, \*):
- If both operands satisfy isexact(), the result satisfies - If both operands satisfy ``isexact()``, the result satisfies
isexact(). ``isexact()``.
- All field rules are true, except that for not-isexact() numbers, - All field rules are true, except that for not-``isexact()`` numbers,
they might be only approximately true. they might be only approximately true.
One consequence of these two rules is that all exact calcutions One consequence of these two rules is that all exact calcutions
are done as (complex) rationals: since the field laws must hold, are done as (complex) rationals: since the field laws must hold,
then then::
(a/b)*b == a (a/b)*b == a
must hold. must hold.
There is built-in function, inexact() which takes a number There is built-in function, ``inexact()`` which takes a number
and returns an inexact number which is a good approximation. and returns an inexact number which is a good approximation.
Inexact numbers must be as least as accurate as if they were Inexact numbers must be as least as accurate as if they were
using IEEE-754. using IEEE-754.
Several of the classical Python functions will return exact numbers Several of the classical Python functions will return exact numbers
even when given inexact numbers: e.g, int(). even when given inexact numbers: e.g, ``int()``.
Coercion Coercion
========
The number type does not define nb_coerce The number type does not define ``nb_coerce``
Any numeric operation slot, when receiving something other then PyNumber, Any numeric operation slot, when receiving something other then ``PyNumber``,
refuses to implement it. refuses to implement it.
Inexact Operations
The functions in the "math" module will be allowed to return Inexact Operations
==================
The functions in the ``math`` module will be allowed to return
inexact results for exact values. However, they will never return inexact results for exact values. However, they will never return
a non-real number. The functions in the "cmath" module are also a non-real number. The functions in the ``cmath`` module are also
allowed to return an inexact result for an exact argument, and are allowed to return an inexact result for an exact argument, and are
furthermore allowed to return a complex result for a real furthermore allowed to return a complex result for a real
argument. argument.
Numerical Python Issues Numerical Python Issues
=======================
People who use Numerical Python do so for high-performance vector People who use Numerical Python do so for high-performance vector
operations. Therefore, NumPy should keep its hardware based operations. Therefore, NumPy should keep its hardware based
@ -120,6 +129,7 @@ Numerical Python Issues
Unresolved Issues Unresolved Issues
=================
Which number literals will be exact, and which inexact? Which number literals will be exact, and which inexact?
@ -133,11 +143,13 @@ Unresolved Issues
Copyright Copyright
=========
This document has been placed in the public domain. This document has been placed in the public domain.
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil

View File

@ -5,12 +5,14 @@ Last-Modified: $Date$
Author: Tim Peters <tim.peters@gmail.com> Author: Tim Peters <tim.peters@gmail.com>
Status: Final Status: Final
Type: Standards Track Type: Standards Track
Content-Type: text/x-rst
Created: Created:
Python-Version: 2.1 Python-Version: 2.1
Post-History: 16 February 2001 Post-History: 16 February 2001
Note Note
====
This is essentially a retroactive PEP: the issue came up too late This is essentially a retroactive PEP: the issue came up too late
in the 2.1 release process to solicit wide opinion before deciding in the 2.1 release process to solicit wide opinion before deciding
@ -19,11 +21,12 @@ Note
Motivation Motivation
==========
File systems vary across platforms in whether or not they preserve File systems vary across platforms in whether or not they preserve
the case of filenames, and in whether or not the platform C the case of filenames, and in whether or not the platform C
library file-opening functions do or don't insist on library file-opening functions do or don't insist on
case-sensitive matches: case-sensitive matches::
case-preserving case-destroying case-preserving case-destroying
+-------------------+------------------+ +-------------------+------------------+
@ -36,20 +39,20 @@ Motivation
+-------------------+------------------+ +-------------------+------------------+
In the upper left box, if you create "fiLe" it's stored as "fiLe", In the upper left box, if you create "fiLe" it's stored as "fiLe",
and only open("fiLe") will open it (open("file") will not, nor and only ``open("fiLe")`` will open it ``(open("file")`` will not, nor
will the 14 other variations on that theme). will the 14 other variations on that theme).
In the lower right box, if you create "fiLe", there's no telling In the lower right box, if you create "fiLe", there's no telling
what it's stored as -- but most likely as "FILE" -- and any of the what it's stored as -- but most likely as "FILE" -- and any of the
16 obvious variations on open("FilE") will open it. 16 obvious variations on ``open("FilE")`` will open it.
The lower left box is a mix: creating "fiLe" stores "fiLe" in the The lower left box is a mix: creating "fiLe" stores "fiLe" in the
platform directory, but you don't have to match case when opening platform directory, but you don't have to match case when opening
it; any of the 16 obvious variations on open("FILe") work. it; any of the 16 obvious variations on ``open("FILe")`` work.
NONE OF THAT IS CHANGING! Python will continue to follow platform NONE OF THAT IS CHANGING! Python will continue to follow platform
conventions w.r.t. whether case is preserved when creating a file, conventions w.r.t. whether case is preserved when creating a file,
and w.r.t. whether open() requires a case-sensitive match. In and w.r.t. whether ``open()`` requires a case-sensitive match. In
practice, you should always code as if matches were practice, you should always code as if matches were
case-sensitive, else your program won't be portable. case-sensitive, else your program won't be portable.
@ -58,6 +61,7 @@ Motivation
Current Lower-Left Semantics Current Lower-Left Semantics
============================
Support for MacOSX HFS+, and for Cygwin, is new in 2.1, so nothing Support for MacOSX HFS+, and for Cygwin, is new in 2.1, so nothing
is changing there. What's changing is Windows behavior. Here are is changing there. What's changing is Windows behavior. Here are
@ -65,27 +69,27 @@ Current Lower-Left Semantics
1. Despite that the filesystem is case-insensitive, Python insists 1. Despite that the filesystem is case-insensitive, Python insists
on a case-sensitive match. But not in the way the upper left on a case-sensitive match. But not in the way the upper left
box works: if you have two files, FiLe.py and file.py on box works: if you have two files, ``FiLe.py`` and ``file.py`` on
sys.path, and do ``sys.path``, and do::
import file import file
then if Python finds FiLe.py first, it raises a NameError. It then if Python finds ``FiLe.py`` first, it raises a ``NameError``. It
does *not* go on to find file.py; indeed, it's impossible to does *not* go on to find ``file.py``; indeed, it's impossible to
import any but the first case-insensitive match on sys.path, import any but the first case-insensitive match on ``sys.path``,
and then only if case matches exactly in the first and then only if case matches exactly in the first
case-insensitive match. case-insensitive match.
2. An ugly exception: if the first case-insensitive match on 2. An ugly exception: if the first case-insensitive match on
sys.path is for a file whose name is entirely in upper case ``sys.path`` is for a file whose name is entirely in upper case
(FILE.PY or FILE.PYC or FILE.PYO), then the import silently (``FILE.PY`` or ``FILE.PYC`` or ``FILE.PYO``), then the import silently
grabs that, no matter what mixture of case was used in the grabs that, no matter what mixture of case was used in the
import statement. This is apparently to cater to miserable old import statement. This is apparently to cater to miserable old
filesystems that really fit in the lower right box. But this filesystems that really fit in the lower right box. But this
exception is unique to Windows, for reasons that may or may not exception is unique to Windows, for reasons that may or may not
exist. exist.
3. And another exception: if the environment variable PYTHONCASEOK 3. And another exception: if the environment variable ``PYTHONCASEOK``
exists, Python silently grabs the first case-insensitive match exists, Python silently grabs the first case-insensitive match
of any kind. of any kind.
@ -110,15 +114,16 @@ Current Lower-Left Semantics
Proposed Semantics Proposed Semantics
==================
The proposed new semantics for the lower left box: The proposed new semantics for the lower left box:
A. If the PYTHONCASEOK environment variable exists, same as A. If the ``PYTHONCASEOK`` environment variable exists, same as
before: silently accept the first case-insensitive match of any before: silently accept the first case-insensitive match of any
kind; raise ImportError if none found. kind; raise ImportError if none found.
B. Else search sys.path for the first case-sensitive match; raise B. Else search ``sys.path`` for the first case-sensitive match; raise
ImportError if none found. ``ImportError`` if none found.
#B is the same rule as is used on Unix, so this will improve cross- #B is the same rule as is used on Unix, so this will improve cross-
platform portability. That's good. #B is also the rule the Mac platform portability. That's good. #B is also the rule the Mac
@ -127,10 +132,10 @@ Proposed Semantics
can't cause any existing non-exceptional Windows import to fail, can't cause any existing non-exceptional Windows import to fail,
because any existing non-exceptional Windows import finds a because any existing non-exceptional Windows import finds a
case-sensitive match first in the path -- and it still will. An case-sensitive match first in the path -- and it still will. An
exceptional Windows import currently blows up with a NameError or exceptional Windows import currently blows up with a ``NameError`` or
ImportError, in which latter case it still will, or in which ``ImportError``, in which latter case it still will, or in which
former case will continue searching, and either succeed or blow up former case will continue searching, and either succeed or blow up
with an ImportError. with an ``ImportError``.
#A is needed to cater to case-destroying filesystems mounted on Windows, #A is needed to cater to case-destroying filesystems mounted on Windows,
and *may* also be used by people so enamored of "natural" Windows and *may* also be used by people so enamored of "natural" Windows
@ -139,14 +144,15 @@ Proposed Semantics
just because I'm not clear on how I *could* do so efficiently (I'm just because I'm not clear on how I *could* do so efficiently (I'm
not going to slow imports under Unix just for theoretical purity). not going to slow imports under Unix just for theoretical purity).
The potential damage is here: #2 (matching on ALLCAPS.PY) is The potential damage is here: #2 (matching on ``ALLCAPS.PY``) is
proposed to be dropped. Case-destroying filesystems are a proposed to be dropped. Case-destroying filesystems are a
vanishing breed, and support for them is ugly. We're already vanishing breed, and support for them is ugly. We're already
supporting (and will continue to support) PYTHONCASEOK for their supporting (and will continue to support) ``PYTHONCASEOK`` for their
benefit, but they don't deserve multiple hacks in 2001. benefit, but they don't deserve multiple hacks in 2001.
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil

View File

@ -5,37 +5,40 @@ Last-Modified: $Date$
Author: jriehl@spaceship.com (Jonathan Riehl) Author: jriehl@spaceship.com (Jonathan Riehl)
Status: Deferred Status: Deferred
Type: Standards Track Type: Standards Track
Content-Type: text/x-rst
Created: 24-Aug-2001 Created: 24-Aug-2001
Python-Version: 2.2 Python-Version: 2.2
Post-History: Post-History:
Abstract Abstract
========
Much like the parser module exposes the Python parser, this PEP Much like the parser module exposes the Python parser, this PEP
proposes that the parser generator used to create the Python proposes that the parser generator used to create the Python
parser, pgen, be exposed as a module in Python. parser, ``pgen``, be exposed as a module in Python.
Rationale Rationale
=========
Through the course of Pythonic history, there have been numerous Through the course of Pythonic history, there have been numerous
discussions about the creation of a Python compiler [1]. These discussions about the creation of a Python compiler [1]_. These
have resulted in several implementations of Python parsers, most have resulted in several implementations of Python parsers, most
notably the parser module currently provided in the Python notably the parser module currently provided in the Python
standard library[2] and Jeremy Hylton's compiler module[3]. standard library [2]_ and Jeremy Hylton's compiler module [3]_.
However, while multiple language changes have been proposed However, while multiple language changes have been proposed
[4][5], experimentation with the Python syntax has lacked the [4]_ [5]_, experimentation with the Python syntax has lacked the
benefit of a Python binding to the actual parser generator used to benefit of a Python binding to the actual parser generator used to
build Python. build Python.
By providing a Python wrapper analogous to Fred Drake Jr.'s parser By providing a Python wrapper analogous to Fred Drake Jr.'s parser
wrapper, but targeted at the pgen library, the following wrapper, but targeted at the ``pgen`` library, the following
assertions are made: assertions are made:
1. Reference implementations of syntax changes will be easier to 1. Reference implementations of syntax changes will be easier to
develop. Currently, a reference implementation of a syntax develop. Currently, a reference implementation of a syntax
change would require the developer to use the pgen tool from change would require the developer to use the ``pgen`` tool from
the command line. The resulting parser data structure would the command line. The resulting parser data structure would
then either have to be reworked to interface with a custom then either have to be reworked to interface with a custom
CPython implementation, or wrapped as a C extension module. CPython implementation, or wrapped as a C extension module.
@ -59,12 +62,16 @@ Rationale
Specification Specification
=============
The proposed module will be called pgen. The pgen module will The proposed module will be called ``pgen``. The ``pgen`` module will
contain the following functions: contain the following functions:
parseGrammarFile (fileName) -> AST
The parseGrammarFile() function will read the file pointed to ``parseGrammarFile (fileName) -> AST``
--------------------------------------
The ``parseGrammarFile()`` function will read the file pointed to
by fileName and create an AST object. The AST nodes will by fileName and create an AST object. The AST nodes will
contain the nonterminal, numeric values of the parser contain the nonterminal, numeric values of the parser
generator meta-grammar. The output AST will be an instance of generator meta-grammar. The output AST will be an instance of
@ -72,60 +79,80 @@ Specification
Syntax errors in the input file will cause the SyntaxError Syntax errors in the input file will cause the SyntaxError
exception to be raised. exception to be raised.
parseGrammarString (text) -> AST
The parseGrammarString() function will follow the semantics of ``parseGrammarString (text) -> AST``
the parseGrammarFile(), but accept the grammar text as a ------------------------------------
The ``parseGrammarString()`` function will follow the semantics of
the ``parseGrammarFile()``, but accept the grammar text as a
string for input, as opposed to the file name. string for input, as opposed to the file name.
buildParser (grammarAst) -> DFA
The buildParser() function will accept an AST object for input ``buildParser (grammarAst) -> DFA``
-----------------------------------
The ``buildParser()`` function will accept an AST object for input
and return a DFA (deterministic finite automaton) data and return a DFA (deterministic finite automaton) data
structure. The DFA data structure will be a C extension structure. The DFA data structure will be a C extension
class, much like the AST structure is provided in the parser class, much like the AST structure is provided in the parser
module. If the input AST does not conform to the nonterminal module. If the input AST does not conform to the nonterminal
codes defined for the pgen meta-grammar, buildParser() will codes defined for the ``pgen`` meta-grammar, ``buildParser()`` will
throw a ValueError exception. throw a ``ValueError`` exception.
parseFile (fileName, dfa, start) -> AST
The parseFile() function will essentially be a wrapper for the ``parseFile (fileName, dfa, start) -> AST``
PyParser_ParseFile() C API function. The wrapper code will -------------------------------------------
The ``parseFile()`` function will essentially be a wrapper for the
``PyParser_ParseFile()`` C API function. The wrapper code will
accept the DFA C extension class, and the file name. An AST accept the DFA C extension class, and the file name. An AST
instance that conforms to the lexical values in the token instance that conforms to the lexical values in the token
module and the nonterminal values contained in the DFA will be module and the nonterminal values contained in the DFA will be
output. output.
parseString (text, dfa, start) -> AST
The parseString() function will operate in a similar fashion
to the parseFile() function, but accept the parse text as an
argument. Much like parseFile() will wrap the
PyParser_ParseFile() C API function, parseString() will wrap
the PyParser_ParseString() function.
symbolToStringMap (dfa) -> dict ``parseString (text, dfa, start) -> AST``
The symbolToStringMap() function will accept a DFA instance -----------------------------------------
The ``parseString()`` function will operate in a similar fashion
to the ``parseFile()`` function, but accept the parse text as an
argument. Much like ``parseFile()`` will wrap the
``PyParser_ParseFile()`` C API function, ``parseString()`` will wrap
the ``PyParser_ParseString()`` function.
``symbolToStringMap (dfa) -> dict``
-----------------------------------
The ``symbolToStringMap()`` function will accept a DFA instance
and return a dictionary object that maps from the DFA's and return a dictionary object that maps from the DFA's
numeric values for its nonterminals to the string names of the numeric values for its nonterminals to the string names of the
nonterminals as found in the original grammar specification nonterminals as found in the original grammar specification
for the DFA. for the DFA.
stringToSymbolMap (dfa) -> dict
The stringToSymbolMap() function output a dictionary mapping ``stringToSymbolMap (dfa) -> dict``
-----------------------------------
The ``stringToSymbolMap()`` function output a dictionary mapping
the nonterminal names of the input DFA to their corresponding the nonterminal names of the input DFA to their corresponding
numeric values. numeric values.
Extra credit will be awarded if the map generation functions and Extra credit will be awarded if the map generation functions and
parsing functions are also methods of the DFA extension class. parsing functions are also methods of the DFA extension class.
Implementation Plan Implementation Plan
===================
A cunning plan has been devised to accomplish this enhancement: A cunning plan has been devised to accomplish this enhancement:
1. Rename the pgen functions to conform to the CPython naming 1. Rename the ``pgen`` functions to conform to the CPython naming
standards. This action may involve adding some header files to standards. This action may involve adding some header files to
the Include subdirectory. the Include subdirectory.
2. Move the pgen C modules in the Makefile.pre.in from unique pgen 2. Move the ``pgen`` C modules in the Makefile.pre.in from unique ``pgen``
elements to the Python C library. elements to the Python C library.
3. Make any needed changes to the parser module so the AST 3. Make any needed changes to the parser module so the AST
@ -142,6 +169,7 @@ Implementation Plan
Limitations Limitations
===========
Under this proposal, would be designers of Python 3000 will still Under this proposal, would be designers of Python 3000 will still
be constrained to Python's lexical conventions. The addition, be constrained to Python's lexical conventions. The addition,
@ -150,6 +178,7 @@ Limitations
Reference Implementation Reference Implementation
========================
No reference implementation is currently provided. A patch No reference implementation is currently provided. A patch
was provided at some point in was provided at some point in
@ -158,29 +187,32 @@ Reference Implementation
References References
==========
[1] The (defunct) Python Compiler-SIG .. [1] The (defunct) Python Compiler-SIG
http://www.python.org/sigs/compiler-sig/ http://www.python.org/sigs/compiler-sig/
[2] Parser Module Documentation .. [2] Parser Module Documentation
http://docs.python.org/library/parser.html http://docs.python.org/library/parser.html
[3] Hylton, Jeremy. .. [3] Hylton, Jeremy.
http://docs.python.org/library/compiler.html http://docs.python.org/library/compiler.html
[4] Pelletier, Michel. "Python Interface Syntax", PEP-245. .. [4] Pelletier, Michel. "Python Interface Syntax", PEP-245.
http://www.python.org/dev/peps/pep-0245/ http://www.python.org/dev/peps/pep-0245/
[5] The Python Types-SIG .. [5] The Python Types-SIG
http://www.python.org/sigs/types-sig/ http://www.python.org/sigs/types-sig/
Copyright Copyright
=========
This document has been placed in the public domain. This document has been placed in the public domain.
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil

View File

@ -5,18 +5,21 @@ Last-Modified: $Date$
Author: python@rcn.com (Raymond Hettinger) Author: python@rcn.com (Raymond Hettinger)
Status: Withdrawn Status: Withdrawn
Type: Standards Track Type: Standards Track
Content-Type: text/x-rst
Created: 21-Mar-2002 Created: 21-Mar-2002
Python-Version: 2.5 Python-Version: 2.5
Post-History: Post-History:
Abstract Abstract
========
This PEP proposes to enhance generators by providing mechanisms for This PEP proposes to enhance generators by providing mechanisms for
raising exceptions and sharing data with running generators. raising exceptions and sharing data with running generators.
Status Status
======
This PEP is withdrawn. The exception raising mechanism was extended This PEP is withdrawn. The exception raising mechanism was extended
and subsumed into PEP 343. The attribute passing capability and subsumed into PEP 343. The attribute passing capability
@ -26,6 +29,7 @@ Status
Rationale Rationale
=========
Currently, only class based iterators can provide attributes and Currently, only class based iterators can provide attributes and
exception handling. However, class based iterators are harder to exception handling. However, class based iterators are harder to
@ -50,11 +54,12 @@ Rationale
Specification for Generator Attributes Specification for Generator Attributes
======================================
Essentially, the proposal is to emulate attribute writing for classes. Essentially, the proposal is to emulate attribute writing for classes.
The only wrinkle is that generators lack a way to refer to instances of The only wrinkle is that generators lack a way to refer to instances of
themselves. So, the proposal is to provide a function for discovering themselves. So, the proposal is to provide a function for discovering
the reference. For example: the reference. For example::
def mygen(filename): def mygen(filename):
self = sys.get_generator() self = sys.get_generator()
@ -78,7 +83,7 @@ Specification for Generator Attributes
data groups). data groups).
3. Writing lazy consumers with complex execution states 3. Writing lazy consumers with complex execution states
(an arithmetic encoder output stream for example). (an arithmetic encoder output stream for example).
4. Writing co-routines (as demonstrated in Dr. Mertz's articles [1]). 4. Writing co-routines (as demonstrated in Dr. Mertz's articles [1]_).
The control flow of 'yield' and 'next' is unchanged by this The control flow of 'yield' and 'next' is unchanged by this
proposal. The only change is that data can passed to and from the proposal. The only change is that data can passed to and from the
@ -87,9 +92,10 @@ Specification for Generator Attributes
Specification for Generator Exception Passing: Specification for Generator Exception Passing
=============================================
Add a .throw(exception) method to the generator interface: Add a .throw(exception) method to the generator interface::
def logger(): def logger():
start = time.time() start = time.time()
@ -113,7 +119,7 @@ Specification for Generator Exception Passing:
Generator exception passing also helps address an intrinsic Generator exception passing also helps address an intrinsic
limitation on generators, the prohibition against their using limitation on generators, the prohibition against their using
try/finally to trigger clean-up code [2]. try/finally to trigger clean-up code [2]_.
Note A: The name of the throw method was selected for several Note A: The name of the throw method was selected for several
reasons. Raise is a keyword and so cannot be used as a method reasons. Raise is a keyword and so cannot be used as a method
@ -123,39 +129,42 @@ Specification for Generator Exception Passing:
putting the exception in another location. The word throw is putting the exception in another location. The word throw is
already associated with exceptions in other languages. already associated with exceptions in other languages.
Alternative method names were considered: resolve(), signal(), Alternative method names were considered: ``resolve()``, ``signal()``,
genraise(), raiseinto(), and flush(). None of these fit as well ``genraise()``, ``raiseinto()``, and ``flush()``. None of these fit as well
as throw(). as ``throw()``.
Note B: To keep the throw() syntax simple only the instance Note B: To keep the ``throw()`` syntax simple only the instance
version of the raise syntax would be supported (no variants for version of the raise syntax would be supported (no variants for
"raise string" or "raise class, instance"). "raise string" or "raise class, instance").
Calling "g.throw(instance)" would correspond to writing Calling ``g.throw(instance)`` would correspond to writing
"raise instance" immediately after the most recent yield. ``raise instance`` immediately after the most recent yield.
References References
==========
[1] Dr. David Mertz's draft columns for Charming Python: .. [1] Dr. David Mertz's draft columns for Charming Python
http://gnosis.cx/publish/programming/charming_python_b5.txt http://gnosis.cx/publish/programming/charming_python_b5.txt
http://gnosis.cx/publish/programming/charming_python_b7.txt http://gnosis.cx/publish/programming/charming_python_b7.txt
[2] PEP 255 Simple Generators: .. [2] PEP 255 Simple Generators
http://www.python.org/dev/peps/pep-0255/ http://www.python.org/dev/peps/pep-0255/
[3] Proof-of-concept recipe: .. [3] Proof-of-concept recipe
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/164044 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/164044
Copyright Copyright
=========
This document has been placed in the public domain. This document has been placed in the public domain.
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil

View File

@ -5,31 +5,36 @@ Last-Modified: $Date$
Author: Roman Suzi <rnd@onego.ru>, Alex Martelli <aleaxit@gmail.com> Author: Roman Suzi <rnd@onego.ru>, Alex Martelli <aleaxit@gmail.com>
Status: Deferred Status: Deferred
Type: Standards Track Type: Standards Track
Content-Type: text/plain Content-Type: text/x-rst
Created: 11-Feb-2003 Created: 11-Feb-2003
Python-Version: 2.4 Python-Version: 2.4
Post-History: Post-History:
Abstract Abstract
========
This PEP proposes to make argumentless lambda keyword optional in This PEP proposes to make argumentless lambda keyword optional in
some cases where it is not grammatically ambiguous. some cases where it is not grammatically ambiguous.
Deferral Deferral
========
The BDFL hates the unary colon syntax. This PEP needs to go back The BDFL hates the unary colon syntax. This PEP needs to go back
to the drawing board and find a more Pythonic syntax (perhaps an to the drawing board and find a more Pythonic syntax (perhaps an
alternative unary operator). See python-dev discussion on alternative unary operator). See python-dev discussion on
17 June 2005. 17 June 2005 [1]_.
Also, it is probably a good idea to eliminate the alternative Also, it is probably a good idea to eliminate the alternative
propositions which have no chance at all. The examples section propositions which have no chance at all. The examples section
is good and highlights the readability improvements. It would is good and highlights the readability improvements. It would
carry more weight with additional examples and with real-world carry more weight with additional examples and with real-world
referents (instead of the abstracted dummy calls to :A and :B). referents (instead of the abstracted dummy calls to ``:A`` and ``:B``).
Motivation Motivation
==========
Lambdas are useful for defining anonymous functions, e.g. for use Lambdas are useful for defining anonymous functions, e.g. for use
as callbacks or (pseudo)-lazy evaluation schemes. Often, lambdas as callbacks or (pseudo)-lazy evaluation schemes. Often, lambdas
@ -41,6 +46,7 @@ Motivation
Rationale Rationale
=========
Sometimes people do not use lambdas because they fear to introduce Sometimes people do not use lambdas because they fear to introduce
a term with a theory behind it. This proposal makes introducing a term with a theory behind it. This proposal makes introducing
@ -52,6 +58,7 @@ Rationale
Syntax Syntax
======
An argumentless "lambda" keyword can be omitted in the following An argumentless "lambda" keyword can be omitted in the following
cases: cases:
@ -70,8 +77,9 @@ Syntax
Examples of Use Examples of Use
===============
1) Inline "if": 1) Inline ``if``::
def ifelse(cond, true_part, false_part): def ifelse(cond, true_part, false_part):
if cond: if cond:
@ -88,7 +96,7 @@ Examples of Use
# parts A and B may require extensive processing, as in: # parts A and B may require extensive processing, as in:
print ifelse(a < b, :ext_proc1(A), :ext_proc2(B)) print ifelse(a < b, :ext_proc1(A), :ext_proc2(B))
2) Locking: 2) Locking::
def with(alock, acallable): def with(alock, acallable):
alock.acquire() alock.acquire()
@ -101,6 +109,7 @@ Examples of Use
Implementation Implementation
==============
Implementation requires some tweaking of the Grammar/Grammar file Implementation requires some tweaking of the Grammar/Grammar file
in the Python sources, and some adjustment of in the Python sources, and some adjustment of
@ -109,7 +118,7 @@ Implementation
(Some grammar/parser guru is needed to make a full (Some grammar/parser guru is needed to make a full
implementation.) implementation.)
Here are the changes needed to Grammar to allow implicit lambda: Here are the changes needed to Grammar to allow implicit lambda::
varargslist: (fpdef ['=' imptest] ',')* ('*' NAME [',' '**' varargslist: (fpdef ['=' imptest] ',')* ('*' NAME [',' '**'
NAME] | '**' NAME) | fpdef ['=' imptest] (',' fpdef ['=' NAME] | '**' NAME) | fpdef ['=' imptest] (',' fpdef ['='
@ -126,9 +135,9 @@ Implementation
argument: [test '='] imptest argument: [test '='] imptest
Three new non-terminals are needed: imptest for the place where Three new non-terminals are needed: ``imptest`` for the place where
implicit lambda may occur, implambdef for the implicit lambda implicit lambda may occur, ``implambdef`` for the implicit lambda
definition itself, imptestlist for a place where imptest's may definition itself, ``imptestlist`` for a place where ``imptest``'s may
occur. occur.
This implementation is not complete. First, because some files in This implementation is not complete. First, because some files in
@ -137,6 +146,7 @@ Implementation
Discussion Discussion
==========
This feature is not a high-visibility one (the only novel part is This feature is not a high-visibility one (the only novel part is
the absence of lambda). The feature is intended to make null-ary the absence of lambda). The feature is intended to make null-ary
@ -147,14 +157,14 @@ Discussion
There is an alternative proposition for implicit lambda: implicit There is an alternative proposition for implicit lambda: implicit
lambda with unused arguments. In this case the function defined by lambda with unused arguments. In this case the function defined by
such lambda can accept any parameters, i.e. be equivalent to: such lambda can accept any parameters, i.e. be equivalent to:
lambda *args: expr. This form would be more powerful. Grep in the ``lambda *args: expr``. This form would be more powerful. Grep in the
standard library revealed that such lambdas are indeed in use. standard library revealed that such lambdas are indeed in use.
One more extension can provide a way to have a list of parameters One more extension can provide a way to have a list of parameters
passed to a function defined by implicit lambda. However, such passed to a function defined by implicit lambda. However, such
parameters need some special name to be accessed and are unlikely parameters need some special name to be accessed and are unlikely
to be included in the language. Possible local names for such to be included in the language. Possible local names for such
parameters are: _, __args__, __. For example: parameters are: ``_``, ``__args__``, ``__``. For example::
reduce(:_[0] + _[1], [1,2,3], 0) reduce(:_[0] + _[1], [1,2,3], 0)
reduce(:__[0] + __[1], [1,2,3], 0) reduce(:__[0] + __[1], [1,2,3], 0)
@ -165,18 +175,32 @@ Discussion
Credits Credits
=======
The idea of dropping lambda was first coined by Paul Rubin at 08 The idea of dropping lambda was first coined by Paul Rubin at 08
Feb 2003 16:39:30 -0800 in comp.lang.python while discussing the Feb 2003 16:39:30 -0800 in comp.lang.python while discussing the
thread "For review: PEP 308 - If-then-else expression". thread "For review: PEP 308 - If-then-else expression" [2]_.
References
==========
.. [1] Guido van Rossum, Recommend accepting PEP 312 -- Simple Implicit Lambda
https://mail.python.org/pipermail/python-dev/2005-June/054304.html
.. [2] Guido van Rossum, For review: PEP 308 - If-then-else expression
https://mail.python.org/pipermail/python-dev/2003-February/033178.html
Copyright Copyright
=========
This document has been placed in the public domain. This document has been placed in the public domain.
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil

View File

@ -2,17 +2,17 @@ PEP: 315
Title: Enhanced While Loop Title: Enhanced While Loop
Version: $Revision$ Version: $Revision$
Last-Modified: $Date$ Last-Modified: $Date$
Author: Raymond Hettinger <python@rcn.com> Author: Raymond Hettinger <python@rcn.com>, W Isaac Carroll <icarroll@pobox.com>
W Isaac Carroll <icarroll@pobox.com>
Status: Rejected Status: Rejected
Type: Standards Track Type: Standards Track
Content-Type: text/plain Content-Type: text/x-rst
Created: 25-Apr-2003 Created: 25-Apr-2003
Python-Version: 2.5 Python-Version: 2.5
Post-History: Post-History:
Abstract Abstract
========
This PEP proposes adding an optional "do" clause to the beginning This PEP proposes adding an optional "do" clause to the beginning
of the while loop to make loop code clearer and reduce errors of the while loop to make loop code clearer and reduce errors
@ -20,16 +20,15 @@ Abstract
Notice Notice
======
Rejected; see Rejected; see [1]_.
http://mail.python.org/pipermail/python-ideas/2013-June/021610.html
This PEP has been deferred since 2006; see This PEP has been deferred since 2006; see [2]_.
http://mail.python.org/pipermail/python-dev/2006-February/060718.html
Subsequent efforts to revive the PEP in April 2009 did not Subsequent efforts to revive the PEP in April 2009 did not
meet with success because no syntax emerged that could meet with success because no syntax emerged that could
compete with the following form: compete with the following form::
while True: while True:
<setup code> <setup code>
@ -39,7 +38,7 @@ Notice
A syntax alternative to the one proposed in the PEP was found for A syntax alternative to the one proposed in the PEP was found for
a basic do-while loop but it gained little support because the a basic do-while loop but it gained little support because the
condition was at the top: condition was at the top::
do ... while <cond>: do ... while <cond>:
<loop body> <loop body>
@ -49,11 +48,12 @@ Notice
Motivation Motivation
==========
It is often necessary for some code to be executed before each It is often necessary for some code to be executed before each
evaluation of the while loop condition. This code is often evaluation of the while loop condition. This code is often
duplicated outside the loop, as setup code that executes once duplicated outside the loop, as setup code that executes once
before entering the loop: before entering the loop::
<setup code> <setup code>
while <condition>: while <condition>:
@ -68,7 +68,7 @@ Motivation
It is possible to prevent code duplication by moving the loop It is possible to prevent code duplication by moving the loop
condition into a helper function, or an if statement in the loop condition into a helper function, or an if statement in the loop
body. However, separating the loop condition from the while body. However, separating the loop condition from the while
keyword makes the behavior of the loop less clear: keyword makes the behavior of the loop less clear::
def helper(args): def helper(args):
<setup code> <setup code>
@ -79,7 +79,7 @@ Motivation
This last form has the additional drawback of requiring the loop's This last form has the additional drawback of requiring the loop's
else clause to be added to the body of the if statement, further else clause to be added to the body of the if statement, further
obscuring the loop's behavior: obscuring the loop's behavior::
while True: while True:
<setup code> <setup code>
@ -88,7 +88,7 @@ Motivation
This PEP proposes to solve these problems by adding an optional This PEP proposes to solve these problems by adding an optional
clause to the while loop, which allows the setup code to be clause to the while loop, which allows the setup code to be
expressed in a natural way: expressed in a natural way::
do: do:
<setup code> <setup code>
@ -100,13 +100,14 @@ Motivation
Syntax Syntax
======
The syntax of the while statement The syntax of the while statement::
while_stmt : "while" expression ":" suite while_stmt : "while" expression ":" suite
["else" ":" suite] ["else" ":" suite]
is extended as follows: is extended as follows::
while_stmt : ["do" ":" suite] while_stmt : ["do" ":" suite]
"while" expression ":" suite "while" expression ":" suite
@ -114,6 +115,7 @@ Syntax
Semantics of break and continue Semantics of break and continue
===============================
In the do-while loop the break statement will behave the same as In the do-while loop the break statement will behave the same as
in the standard while loop: It will immediately terminate the loop in the standard while loop: It will immediately terminate the loop
@ -133,8 +135,9 @@ Semantics of break and continue
Future Statement Future Statement
================
Because of the new keyword "do", the statement Because of the new keyword "do", the statement::
from __future__ import do_while from __future__ import do_while
@ -142,17 +145,30 @@ Future Statement
Implementation Implementation
==============
The first implementation of this PEP can compile the do-while loop The first implementation of this PEP can compile the do-while loop
as an infinite loop with a test that exits the loop. as an infinite loop with a test that exits the loop.
References
==========
.. [1] Guido van Rossum, PEP 315: do-while
https://mail.python.org/pipermail/python-ideas/2013-June/021610.html
.. [2] Raymond Hettinger, release plan for 2.5 ?
https://mail.python.org/pipermail/python-dev/2006-February/060718.html
Copyright Copyright
=========
This document is placed in the public domain. This document is placed in the public domain.
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil

View File

@ -5,13 +5,14 @@ Last-Modified: $Date$
Author: Talin <viridia@gmail.com> Author: Talin <viridia@gmail.com>
Status: Final Status: Final
Type: Standards Track Type: Standards Track
Content-Type: text/plain Content-Type: text/x-rst
Created: 22-Apr-2006 Created: 22-Apr-2006
Python-Version: 3.0 Python-Version: 3.0
Post-History: 28-Apr-2006, May-19-2006 Post-History: 28-Apr-2006, May-19-2006
Abstract Abstract
========
This PEP proposes a change to the way that function arguments are This PEP proposes a change to the way that function arguments are
assigned to named parameter slots. In particular, it enables the assigned to named parameter slots. In particular, it enables the
@ -21,6 +22,7 @@ Abstract
Rationale Rationale
=========
The current Python function-calling paradigm allows arguments to The current Python function-calling paradigm allows arguments to
be specified either by position or by keyword. An argument can be be specified either by position or by keyword. An argument can be
@ -28,7 +30,7 @@ Rationale
There are often cases where it is desirable for a function to take There are often cases where it is desirable for a function to take
a variable number of arguments. The Python language supports this a variable number of arguments. The Python language supports this
using the 'varargs' syntax ('*name'), which specifies that any using the 'varargs' syntax (``*name``), which specifies that any
'left over' arguments be passed into the varargs parameter as a 'left over' arguments be passed into the varargs parameter as a
tuple. tuple.
@ -39,15 +41,16 @@ Rationale
which takes a variable number of arguments, but also takes one which takes a variable number of arguments, but also takes one
or more 'options' in the form of keyword arguments. Currently, or more 'options' in the form of keyword arguments. Currently,
the only way to do this is to define both a varargs argument, the only way to do this is to define both a varargs argument,
and a 'keywords' argument (**kwargs), and then manually extract and a 'keywords' argument (``**kwargs``), and then manually extract
the desired keywords from the dictionary. the desired keywords from the dictionary.
Specification Specification
=============
Syntactically, the proposed changes are fairly simple. The first Syntactically, the proposed changes are fairly simple. The first
change is to allow regular arguments to appear after a varargs change is to allow regular arguments to appear after a varargs
argument: argument::
def sortwords(*wordlist, case_sensitive=False): def sortwords(*wordlist, case_sensitive=False):
... ...
@ -67,21 +70,21 @@ Specification
The second syntactical change is to allow the argument name to The second syntactical change is to allow the argument name to
be omitted for a varargs argument. The meaning of this is to be omitted for a varargs argument. The meaning of this is to
allow for keyword-only arguments for functions that would not allow for keyword-only arguments for functions that would not
otherwise take a varargs argument: otherwise take a varargs argument::
def compare(a, b, *, key=None): def compare(a, b, *, key=None):
... ...
The reasoning behind this change is as follows. Imagine for a The reasoning behind this change is as follows. Imagine for a
moment a function which takes several positional arguments, as moment a function which takes several positional arguments, as
well as a keyword argument: well as a keyword argument::
def compare(a, b, key=None): def compare(a, b, key=None):
... ...
Now, suppose you wanted to have 'key' be a keyword-only argument. Now, suppose you wanted to have 'key' be a keyword-only argument.
Under the above syntax, you could accomplish this by adding a Under the above syntax, you could accomplish this by adding a
varargs argument immediately before the keyword argument: varargs argument immediately before the keyword argument::
def compare(a, b, *ignore, key=None): def compare(a, b, *ignore, key=None):
... ...
@ -89,7 +92,7 @@ Specification
Unfortunately, the 'ignore' argument will also suck up any Unfortunately, the 'ignore' argument will also suck up any
erroneous positional arguments that may have been supplied by the erroneous positional arguments that may have been supplied by the
caller. Given that we'd prefer any unwanted arguments to raise an caller. Given that we'd prefer any unwanted arguments to raise an
error, we could do this: error, we could do this::
def compare(a, b, *ignore, key=None): def compare(a, b, *ignore, key=None):
if ignore: # If ignore is not empty if ignore: # If ignore is not empty
@ -104,6 +107,7 @@ Specification
Function Calling Behavior Function Calling Behavior
=========================
The previous section describes the difference between the old The previous section describes the difference between the old
behavior and the new. However, it is also useful to have a behavior and the new. However, it is also useful to have a
@ -129,47 +133,48 @@ Function Calling Behavior
- For each positional argument: - For each positional argument:
o Attempt to bind the argument to the first unfilled * Attempt to bind the argument to the first unfilled
parameter slot. If the slot is not a vararg slot, then parameter slot. If the slot is not a vararg slot, then
mark the slot as 'filled'. mark the slot as 'filled'.
o If the next unfilled slot is a vararg slot, and it does * If the next unfilled slot is a vararg slot, and it does
not have a name, then it is an error. not have a name, then it is an error.
o Otherwise, if the next unfilled slot is a vararg slot then * Otherwise, if the next unfilled slot is a vararg slot then
all remaining non-keyword arguments are placed into the all remaining non-keyword arguments are placed into the
vararg slot. vararg slot.
- For each keyword argument: - For each keyword argument:
o If there is a parameter with the same name as the keyword, * If there is a parameter with the same name as the keyword,
then the argument value is assigned to that parameter slot. then the argument value is assigned to that parameter slot.
However, if the parameter slot is already filled, then that However, if the parameter slot is already filled, then that
is an error. is an error.
o Otherwise, if there is a 'keyword dictionary' argument, * Otherwise, if there is a 'keyword dictionary' argument,
the argument is added to the dictionary using the keyword the argument is added to the dictionary using the keyword
name as the dictionary key, unless there is already an name as the dictionary key, unless there is already an
entry with that key, in which case it is an error. entry with that key, in which case it is an error.
o Otherwise, if there is no keyword dictionary, and no * Otherwise, if there is no keyword dictionary, and no
matching named parameter, then it is an error. matching named parameter, then it is an error.
- Finally: - Finally:
o If the vararg slot is not yet filled, assign an empty tuple * If the vararg slot is not yet filled, assign an empty tuple
as its value. as its value.
o For each remaining empty slot: if there is a default value * For each remaining empty slot: if there is a default value
for that slot, then fill the slot with the default value. for that slot, then fill the slot with the default value.
If there is no default value, then it is an error. If there is no default value, then it is an error.
In accordance with the current Python implementation, any errors In accordance with the current Python implementation, any errors
encountered will be signaled by raising TypeError. (If you want encountered will be signaled by raising ``TypeError``. (If you want
something different, that's a subject for a different PEP.) something different, that's a subject for a different PEP.)
Backwards Compatibility Backwards Compatibility
=======================
The function calling behavior specified in this PEP is a superset The function calling behavior specified in this PEP is a superset
of the existing behavior - that is, it is expected that any of the existing behavior - that is, it is expected that any
@ -177,10 +182,12 @@ Backwards Compatibility
Copyright Copyright
=========
This document has been placed in the public domain. This document has been placed in the public domain.
..
Local Variables: Local Variables:
mode: indented-text mode: indented-text
indent-tabs-mode: nil indent-tabs-mode: nil