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)
Status: Deferred
Type: Standards Track
Content-Type: text/x-rst
Created: 22-Aug-2000
Python-Version: 2.1
Post-History:
Introduction
============
This PEP describes the often proposed feature of exposing the loop
counter in for-loops. This PEP tracks the status and ownership of
@ -22,9 +24,10 @@ Introduction
Motivation
==========
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.
The common idioms used to accomplish this are unintuitive. This
@ -32,54 +35,58 @@ Motivation
Loop counter iteration
======================
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)):
# work with index i
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)):
e = sequence[i]
# work with index i and element e
or
or::
for i, e in zip(range(len(sequence)), sequence):
# work with index i and element e
The Proposed Solutions
======================
There are three solutions that have been discussed. One adds a
non-reserved keyword, the other adds two built-in functions.
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
an optional '<variable> indexing' clause which can also be used
instead of the '<variable> in' clause..
an optional ``<variable> indexing`` clause which can also be used
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:
# 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:
# 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'.
The semantics of these can be described as follows:
This solution adds two built-in functions ``indices`` and ``irange``.
The semantics of these can be described as follows::
def indices(sequence):
return range(len(sequence))
@ -92,7 +99,7 @@ Built-in functions 'indices' and 'irange'
argument.
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):
# work with index i
@ -102,14 +109,15 @@ Built-in functions 'indices' and 'irange'
Methods for sequence objects
============================
This solution proposes the addition of 'indices', 'items'
and 'values' methods to sequences, which enable looping over
This solution proposes the addition of ``indices``, ``items``
and ``values`` methods to sequences, which enable looping over
indices only, both indices and elements, and elements only
respectively.
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():
# work with index i
@ -118,28 +126,30 @@ Methods for sequence objects
# work with index i and element e
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():
# do something with element e
Implementations
===============
For all three solutions some more or less rough patches exist
as patches at SourceForge:
'for i indexing a in l': exposing the for-loop counter[3]
add indices() and irange() to built-ins[4]
add items() method to listobject[5]
- ``for i indexing a in l``: exposing the for-loop counter [3]_
- add ``indices()`` and ``irange()`` to built-ins [4]_
- add ``items()`` method to listobject [5]_
All of them have been pronounced on and rejected by the BDFL.
Note that the 'indexing' keyword is only a NAME in the
grammar and so does not hinder the general use of 'indexing'.
Note that the ``indexing`` keyword is only a ``NAME`` in the
grammar and so does not hinder the general use of ``indexing``.
Backward Compatibility Issues
=============================
As no keywords are added and the semantics of existing code
remains unchanged, all three solutions can be implemented
@ -147,20 +157,27 @@ Backward Compatibility Issues
Copyright
=========
This document has been placed in the public domain.
References
==========
[1] http://docs.python.org/reference/compound_stmts.html#for
[2] Lockstep Iteration, PEP 201
[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
.. [1] http://docs.python.org/reference/compound_stmts.html#for
.. [2] Lockstep Iteration, PEP 201
.. [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:
mode: indented-text
indent-tabs-mode: nil

View File

@ -5,23 +5,28 @@ Last-Modified: $Date$
Author: moshez@zadka.site.co.il (Moshe Zadka)
Status: Rejected
Type: Informational
Content-Type: text/x-rst
Created: 31-Jul-2000
Post-History:
Superseded-By: 287
Notice
======
This PEP is rejected by the author. It has been superseded by PEP
287.
Abstract
========
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
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
function. However, since there is no common format for documentation
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
unmaintained and unused.
Perl Documentation
==================
In Perl, most modules are documented in a format called POD -- Plain
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
others. However, in Perl, the information is not available at run-time.
Java Documentation
==================
In Java, special comments before classes and functions function to
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
is HTML, and JavaDoc has a very intimate relationship with HTML.
Python Docstring Goals
======================
Python documentation string are easy to spot during parsing, and are
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
contain little information, which is hard to parse.
High Level Solutions
====================
To counter the objection that the strings take up place in the running
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
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.
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
docstrings, without feeling hampered by the markup language.
Docstring Contents
==================
For requirement 5. above, it is needed to specify what must be
in docstrings.
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"
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..."
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
to document the class, nonetheless, as being A. This requires the
strength to say "The class A" and have A hyperlinked and marked-up
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
to document the class, nonetheless, as being ``A``. This requires the
strength to say "The class ``A``" and have ``A`` hyperlinked and marked-up
as a class.
c. An easy way to include Python source code/Python interactive sessions
d. Emphasis/bold
e. List/tables
Docstring Basic Structure
=========================
The documentation strings will be in StructuredTextNG
(http://www.zope.org/Members/jim/StructuredTextWiki/StructuredTextNG)
Since StructuredText is not yet strong enough to handle (a) and (b)
above, we will need to extend it. I suggest using
'[<optional description>:python identifier]'.
E.g.: [class:POP3], [:POP3.list], etc. If the description is missing,
``[<optional description>:python identifier]``.
E.g.: ``[class:POP3]``, ``[:POP3.list]``, etc. If the description is missing,
a guess will be made from the text.
Unresolved Issues
=================
Is there a way to escape characters in ST? If so, how?
(example: * at the beginning of a line without being bullet symbol)
@ -130,13 +153,15 @@ Unresolved Issues
What are the guesser rules?
Rejected Suggestions
====================
XML -- it's very hard to type, and too cluttered to read it
comfortably.
XML -- it's very hard to type, and too cluttered to read it comfortably.
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil

View File

@ -5,12 +5,14 @@ Last-Modified: $Date$
Author: gmcm@hypernet.com (Gordon McMillan)
Status: Deferred
Type: Standards Track
Content-Type: text/x-rst
Created: 14-Aug-2000
Python-Version: 2.1
Post-History:
Introduction
============
This PEP discusses changes required to core Python in order to
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
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. Stackless (with an extension module) implements
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
productive use of continuations, so there seems to be no demand
for their support.
@ -34,10 +36,11 @@ Introduction
Background
==========
Generators and coroutines have been implemented in a number of
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
Java). However, the horrendous overhead of a thread-based
implementation severely limits the usefulness of this approach.
@ -62,6 +65,7 @@ Background
Discussion
==========
The first thing to note is that Python, while it mingles
interpreter data (normal C stack usage) with Python data (the
@ -91,6 +95,7 @@ Discussion
Problems
========
The major difficulty with this approach is C calling Python. 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
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
FrameDispatcher. Like PyEval_EvalCode, it executes one frame. But
the interpreter may signal the FrameDispatcher that a new frame
``FrameDispatcher``. Like ``PyEval_EvalCode``, it executes one frame. But
the interpreter may signal the ``FrameDispatcher`` that a new frame
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.
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).
The general idea is that where C code needs to execute Python
code, it creates a frame for the Python code, setting its back
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
(if an extension gives it the means to do so).
@ -160,6 +165,7 @@ Problems
Advantages
==========
For normal Python, the advantage to this approach is that C stack
usage becomes much smaller and more predictable. Unbounded
@ -177,14 +183,16 @@ Advantages
References
==========
[1] http://www.stackless.com
[2] http://world.std.com/~wware/uthread.html
[3] Demo/threads/Generator.py in the source distribution
[4] http://www.stackless.com/coroutines.tim.peters.html
.. [1] http://www.stackless.com
.. [2] http://web.archive.org/web/20000815070602/http://world.std.com/~wware/uthread.html
.. [3] Demo/threads/Generator.py in the source distribution
.. [4] http://www.stackless.com/coroutines.tim.peters.html
..
Local Variables:
mode: indented-text
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)
Status: Withdrawn
Type: Standards Track
Content-Type: text/x-rst
Created: 4-Nov-2000
Python-Version: ??
Post-History:
Withdrawal
==========
This PEP has been withdrawn in favor of PEP 3141.
Abstract
========
Today, Python's numerical model is similar to the C numeric model:
there are several unrelated numerical types, and when operations
@ -30,16 +32,18 @@ Abstract
Rationale
=========
In usability studies, one of the least usable aspect of Python was
the fact that integer division returns the floor of the division.
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
can be based on the mathematical understanding of numbers.
Other Numerical Models
======================
Perl's numerical model is that there is one type of numbers --
floating point numbers. While it is consistent and superficially
@ -52,67 +56,72 @@ Other Numerical Models
Suggested Interface For Python's Numerical Model
================================================
While coercion rules will remain for add-on types and classes, the
built in type system will have exactly one Python type -- a
number. There are several things which can be considered "number
methods":
1. isnatural()
2. isintegral()
3. isrational()
4. isreal()
5. iscomplex()
a. isexact()
1. ``isnatural()``
2. ``isintegral()``
3. ``isrational()``
4. ``isreal()``
5. ``iscomplex()``
6. ``isexact()``
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.
(But not horribly wrong: it's close to the truth.)
Now, there is two thing the models promises for the field operations
(+, -, /, *):
(+, -, /, \*):
- If both operands satisfy isexact(), the result satisfies
isexact().
- If both operands satisfy ``isexact()``, the result satisfies
``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.
One consequence of these two rules is that all exact calcutions
are done as (complex) rationals: since the field laws must hold,
then
then::
(a/b)*b == a
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.
Inexact numbers must be as least as accurate as if they were
using IEEE-754.
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
========
The number type does not define nb_coerce
Any numeric operation slot, when receiving something other then PyNumber,
The number type does not define ``nb_coerce``
Any numeric operation slot, when receiving something other then ``PyNumber``,
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
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
furthermore allowed to return a complex result for a real
argument.
Numerical Python Issues
=======================
People who use Numerical Python do so for high-performance vector
operations. Therefore, NumPy should keep its hardware based
@ -120,6 +129,7 @@ Numerical Python Issues
Unresolved Issues
=================
Which number literals will be exact, and which inexact?
@ -133,11 +143,13 @@ Unresolved Issues
Copyright
=========
This document has been placed in the public domain.
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil

View File

@ -5,12 +5,14 @@ Last-Modified: $Date$
Author: Tim Peters <tim.peters@gmail.com>
Status: Final
Type: Standards Track
Content-Type: text/x-rst
Created:
Python-Version: 2.1
Post-History: 16 February 2001
Note
====
This is essentially a retroactive PEP: the issue came up too late
in the 2.1 release process to solicit wide opinion before deciding
@ -19,11 +21,12 @@ Note
Motivation
==========
File systems vary across platforms in whether or not they preserve
the case of filenames, and in whether or not the platform C
library file-opening functions do or don't insist on
case-sensitive matches:
case-sensitive matches::
case-preserving case-destroying
+-------------------+------------------+
@ -36,20 +39,20 @@ Motivation
+-------------------+------------------+
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).
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
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
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
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
case-sensitive, else your program won't be portable.
@ -58,6 +61,7 @@ Motivation
Current Lower-Left Semantics
============================
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
@ -65,27 +69,27 @@ Current Lower-Left Semantics
1. Despite that the filesystem is case-insensitive, Python insists
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
sys.path, and do
box works: if you have two files, ``FiLe.py`` and ``file.py`` on
``sys.path``, and do::
import file
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
import any but the first case-insensitive match on sys.path,
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
import any but the first case-insensitive match on ``sys.path``,
and then only if case matches exactly in the first
case-insensitive match.
2. An ugly exception: if the first case-insensitive match on
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
``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
grabs that, no matter what mixture of case was used in the
import statement. This is apparently to cater to miserable old
filesystems that really fit in the lower right box. But this
exception is unique to Windows, for reasons that may or may not
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
of any kind.
@ -110,15 +114,16 @@ Current Lower-Left Semantics
Proposed Semantics
==================
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
kind; raise ImportError if none found.
B. Else search sys.path for the first case-sensitive match; raise
ImportError if none found.
B. Else search ``sys.path`` for the first case-sensitive match; raise
``ImportError`` if none found.
#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
@ -127,10 +132,10 @@ Proposed Semantics
can't cause any existing non-exceptional Windows import to fail,
because any existing non-exceptional Windows import finds a
case-sensitive match first in the path -- and it still will. An
exceptional Windows import currently blows up with a NameError or
ImportError, in which latter case it still will, or in which
exceptional Windows import currently blows up with a ``NameError`` or
``ImportError``, in which latter case it still will, or in which
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,
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
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
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.
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil

View File

@ -5,37 +5,40 @@ Last-Modified: $Date$
Author: jriehl@spaceship.com (Jonathan Riehl)
Status: Deferred
Type: Standards Track
Content-Type: text/x-rst
Created: 24-Aug-2001
Python-Version: 2.2
Post-History:
Abstract
========
Much like the parser module exposes the Python parser, this PEP
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
=========
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
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
[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
build Python.
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:
1. Reference implementations of syntax changes will be easier to
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
then either have to be reworked to interface with a custom
CPython implementation, or wrapped as a C extension module.
@ -59,12 +62,16 @@ Rationale
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:
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
contain the nonterminal, numeric values of the parser
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
exception to be raised.
parseGrammarString (text) -> AST
The parseGrammarString() function will follow the semantics of
the parseGrammarFile(), but accept the grammar text as a
``parseGrammarString (text) -> AST``
------------------------------------
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.
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
structure. The DFA data structure will be a C extension
class, much like the AST structure is provided in the parser
module. If the input AST does not conform to the nonterminal
codes defined for the pgen meta-grammar, buildParser() will
throw a ValueError exception.
codes defined for the ``pgen`` meta-grammar, ``buildParser()`` will
throw a ``ValueError`` exception.
parseFile (fileName, dfa, start) -> AST
The parseFile() function will essentially be a wrapper for the
PyParser_ParseFile() C API function. The wrapper code will
``parseFile (fileName, dfa, start) -> AST``
-------------------------------------------
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
instance that conforms to the lexical values in the token
module and the nonterminal values contained in the DFA will be
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
The symbolToStringMap() function will accept a DFA instance
``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``
-----------------------------------
The ``symbolToStringMap()`` function will accept a DFA instance
and return a dictionary object that maps from the DFA's
numeric values for its nonterminals to the string names of the
nonterminals as found in the original grammar specification
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
numeric values.
Extra credit will be awarded if the map generation functions and
parsing functions are also methods of the DFA extension class.
Implementation Plan
===================
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
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.
3. Make any needed changes to the parser module so the AST
@ -142,6 +169,7 @@ Implementation Plan
Limitations
===========
Under this proposal, would be designers of Python 3000 will still
be constrained to Python's lexical conventions. The addition,
@ -150,6 +178,7 @@ Limitations
Reference Implementation
========================
No reference implementation is currently provided. A patch
was provided at some point in
@ -158,29 +187,32 @@ Reference Implementation
References
==========
[1] The (defunct) Python Compiler-SIG
.. [1] The (defunct) Python Compiler-SIG
http://www.python.org/sigs/compiler-sig/
[2] Parser Module Documentation
.. [2] Parser Module Documentation
http://docs.python.org/library/parser.html
[3] Hylton, Jeremy.
.. [3] Hylton, Jeremy.
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/
[5] The Python Types-SIG
.. [5] The Python Types-SIG
http://www.python.org/sigs/types-sig/
Copyright
=========
This document has been placed in the public domain.
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil

View File

@ -5,18 +5,21 @@ Last-Modified: $Date$
Author: python@rcn.com (Raymond Hettinger)
Status: Withdrawn
Type: Standards Track
Content-Type: text/x-rst
Created: 21-Mar-2002
Python-Version: 2.5
Post-History:
Abstract
========
This PEP proposes to enhance generators by providing mechanisms for
raising exceptions and sharing data with running generators.
Status
======
This PEP is withdrawn. The exception raising mechanism was extended
and subsumed into PEP 343. The attribute passing capability
@ -26,6 +29,7 @@ Status
Rationale
=========
Currently, only class based iterators can provide attributes and
exception handling. However, class based iterators are harder to
@ -50,11 +54,12 @@ Rationale
Specification for Generator Attributes
======================================
Essentially, the proposal is to emulate attribute writing for classes.
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
the reference. For example:
the reference. For example::
def mygen(filename):
self = sys.get_generator()
@ -78,7 +83,7 @@ Specification for Generator Attributes
data groups).
3. Writing lazy consumers with complex execution states
(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
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():
start = time.time()
@ -113,7 +119,7 @@ Specification for Generator Exception Passing:
Generator exception passing also helps address an intrinsic
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
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
already associated with exceptions in other languages.
Alternative method names were considered: resolve(), signal(),
genraise(), raiseinto(), and flush(). None of these fit as well
as throw().
Alternative method names were considered: ``resolve()``, ``signal()``,
``genraise()``, ``raiseinto()``, and ``flush()``. None of these fit as well
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
"raise string" or "raise class, instance").
Calling "g.throw(instance)" would correspond to writing
"raise instance" immediately after the most recent yield.
Calling ``g.throw(instance)`` would correspond to writing
``raise instance`` immediately after the most recent yield.
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_b7.txt
[2] PEP 255 Simple Generators:
.. [2] PEP 255 Simple Generators
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
Copyright
=========
This document has been placed in the public domain.
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil

View File

@ -5,31 +5,36 @@ Last-Modified: $Date$
Author: Roman Suzi <rnd@onego.ru>, Alex Martelli <aleaxit@gmail.com>
Status: Deferred
Type: Standards Track
Content-Type: text/plain
Content-Type: text/x-rst
Created: 11-Feb-2003
Python-Version: 2.4
Post-History:
Abstract
========
This PEP proposes to make argumentless lambda keyword optional in
some cases where it is not grammatically ambiguous.
Deferral
========
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
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
propositions which have no chance at all. The examples section
is good and highlights the readability improvements. It would
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
==========
Lambdas are useful for defining anonymous functions, e.g. for use
as callbacks or (pseudo)-lazy evaluation schemes. Often, lambdas
@ -41,6 +46,7 @@ Motivation
Rationale
=========
Sometimes people do not use lambdas because they fear to introduce
a term with a theory behind it. This proposal makes introducing
@ -52,6 +58,7 @@ Rationale
Syntax
======
An argumentless "lambda" keyword can be omitted in the following
cases:
@ -70,8 +77,9 @@ Syntax
Examples of Use
===============
1) Inline "if":
1) Inline ``if``::
def ifelse(cond, true_part, false_part):
if cond:
@ -88,7 +96,7 @@ Examples of Use
# parts A and B may require extensive processing, as in:
print ifelse(a < b, :ext_proc1(A), :ext_proc2(B))
2) Locking:
2) Locking::
def with(alock, acallable):
alock.acquire()
@ -101,6 +109,7 @@ Examples of Use
Implementation
==============
Implementation requires some tweaking of the Grammar/Grammar file
in the Python sources, and some adjustment of
@ -109,7 +118,7 @@ Implementation
(Some grammar/parser guru is needed to make a full
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 [',' '**'
NAME] | '**' NAME) | fpdef ['=' imptest] (',' fpdef ['='
@ -126,9 +135,9 @@ Implementation
argument: [test '='] imptest
Three new non-terminals are needed: imptest for the place where
implicit lambda may occur, implambdef for the implicit lambda
definition itself, imptestlist for a place where imptest's may
Three new non-terminals are needed: ``imptest`` for the place where
implicit lambda may occur, ``implambdef`` for the implicit lambda
definition itself, ``imptestlist`` for a place where ``imptest``'s may
occur.
This implementation is not complete. First, because some files in
@ -137,6 +146,7 @@ Implementation
Discussion
==========
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
@ -147,14 +157,14 @@ Discussion
There is an alternative proposition for implicit lambda: implicit
lambda with unused arguments. In this case the function defined by
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.
One more extension can provide a way to have a list of parameters
passed to a function defined by implicit lambda. However, such
parameters need some special name to be accessed and are unlikely
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)
@ -165,18 +175,32 @@ Discussion
Credits
=======
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
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
=========
This document has been placed in the public domain.
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil

View File

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

View File

@ -5,13 +5,14 @@ Last-Modified: $Date$
Author: Talin <viridia@gmail.com>
Status: Final
Type: Standards Track
Content-Type: text/plain
Content-Type: text/x-rst
Created: 22-Apr-2006
Python-Version: 3.0
Post-History: 28-Apr-2006, May-19-2006
Abstract
========
This PEP proposes a change to the way that function arguments are
assigned to named parameter slots. In particular, it enables the
@ -21,6 +22,7 @@ Abstract
Rationale
=========
The current Python function-calling paradigm allows arguments to
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
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
tuple.
@ -39,15 +41,16 @@ Rationale
which takes a variable number of arguments, but also takes one
or more 'options' in the form of keyword arguments. Currently,
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.
Specification
=============
Syntactically, the proposed changes are fairly simple. The first
change is to allow regular arguments to appear after a varargs
argument:
argument::
def sortwords(*wordlist, case_sensitive=False):
...
@ -67,21 +70,21 @@ Specification
The second syntactical change is to allow the argument name to
be omitted for a varargs argument. The meaning of this is to
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):
...
The reasoning behind this change is as follows. Imagine for a
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):
...
Now, suppose you wanted to have 'key' be a keyword-only argument.
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):
...
@ -89,7 +92,7 @@ Specification
Unfortunately, the 'ignore' argument will also suck up any
erroneous positional arguments that may have been supplied by the
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):
if ignore: # If ignore is not empty
@ -104,6 +107,7 @@ Specification
Function Calling Behavior
=========================
The previous section describes the difference between the old
behavior and the new. However, it is also useful to have a
@ -129,47 +133,48 @@ Function Calling Behavior
- 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
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.
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
vararg slot.
- 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.
However, if the parameter slot is already filled, then that
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
name as the dictionary key, unless there is already an
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.
- 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.
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.
If there is no default value, then it is an error.
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.)
Backwards Compatibility
=======================
The function calling behavior specified in this PEP is a superset
of the existing behavior - that is, it is expected that any
@ -177,10 +182,12 @@ Backwards Compatibility
Copyright
=========
This document has been placed in the public domain.
..
Local Variables:
mode: indented-text
indent-tabs-mode: nil