Skip to content

Commit 58cdb97

Browse files
committed
Add a bunch of docs in ReST format
1 parent dddea7c commit 58cdb97

13 files changed

Lines changed: 879 additions & 0 deletions
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
Automatic conversion
2+
====================
3+
4+
There is an experimental script included called ``futurize`` to aid in making
5+
either Python 2 code or Python 3 code compatible with both platforms using the
6+
``future`` module. It is based on 2to3 and uses fixers from ``lib2to3``,
7+
``lib3to2``, and ``python-modernize``.
8+
9+
For Python 2 code (the default), it runs the code through all the
10+
appropriate 2to3 fixers to turn it into valid Python 3 code, and then
11+
adds ``__future__`` and ``future`` package imports. For Python 3 code
12+
(with the ``--from3`` command-line option), it fixes Py3-only syntax
13+
(e.g. metaclasses) and adds ``__future__`` and ``future`` imports to the
14+
top of each module. In both cases, the result should be relatively clean
15+
Py3-style code semantics that (hopefully) runs unchanged on both Python 2
16+
and Python 3.
17+
18+
Forwards: 2 to both
19+
--------------------
20+
For example, running ``futurize`` turns this Python 2 code::
21+
22+
import ConfigParser
23+
24+
class Blah(object):
25+
pass
26+
print 'Hello',
27+
28+
into this code which runs on both Py2 and Py3::
29+
30+
from __future__ import print_function
31+
from future import standard_library
32+
33+
import configparser
34+
35+
class Blah(object):
36+
pass
37+
print('Hello', end=' ')
38+
39+
40+
Backwards: 3 to both
41+
--------------------
42+
Running ``futurize --from3`` turns this Python 3 code::
43+
44+
import configparser
45+
46+
class Blah:
47+
pass
48+
print('Hello', end=None)
49+
50+
into this code which runs on both Py2 and Py3::
51+
52+
from __future__ import print_function
53+
from future import standard_library
54+
55+
import configparser
56+
57+
class Blah(object):
58+
pass
59+
print('Hello', end=None)
60+
61+
Notice that in both cases ``futurize`` forces a new-style class and
62+
imports the renamed stdlib module under its Py3 name.
63+
64+
It also handles the following Python 3 features:
65+
66+
- keyword-only arguments
67+
- metaclasses (using ``future.utils.with_metaclass``)
68+
69+
70+

‎docs/source/bind_method.rst‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
Binding a method to a class
2+
---------------------------
3+
4+
Python 2 draws a distinction between bound and unbound methods, whereas in Python
5+
3 this distinction is gone: unbound methods have been removed from the
6+
language. To bind a method to a class compatibly across Python 3 and Python 2,
7+
you can use this helper function::
8+
9+
from future.utils import bind_method
10+
11+
class Greeter(object):
12+
pass
13+
14+
def greet(self, message):
15+
print(message)
16+
17+
bind_method(Greeter, 'greet', greet)
18+
19+
g = Greeter()
20+
g.greet('Hi!')
21+
22+
23+
On Python 3, calling ``bind_method(cls, name, func)`` is equivalent to calling
24+
``setattr(cls, name, func)``. On Python 2 it is equivalent to::
25+
26+
import types
27+
setattr(cls, name, types.MethodType(func, None, cls))

‎docs/source/bytes_object.rst‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
bytes object
2+
============
3+
4+
Handling ``bytes`` consistently and correctly has been one of the most
5+
difficult tasks in writing a Py3/2 compatible codebase. This is because the
6+
Python 2 ``bytes`` object is (unfortunately) simply an alias for Python 2's
7+
``str``, whereas the Python 3 ``bytes`` object is substantially different. For example:
8+
9+
- bytes objects print with a b'' prefix like b'ABCD' on Py3.
10+
11+
- Python 3 often raises TypeErrors to guard against implicit type conversions
12+
from byte-strings to Unicode.
13+
14+
``future`` contains a backport of the ``bytes`` object from Python 3 which
15+
passes most of the Python 3 tests for ``bytes``. You can use it as follows::
16+
17+
from future.builtins import bytes
18+
19+
b = bytes(b'ABCD')
20+
21+
This object inherits from Python 2's ``str``, but it enforces the much stricter
22+
separation from unicode strings that Python 3's ``bytes`` requires::
23+
24+
>>> b + u'EFGH' # TypeError
25+
Traceback (most recent call last):
26+
File "<stdin>", line 1, in <module>
27+
TypeError: argument can't be unicode string
28+
29+
>>> bytes(b',').join([u'Fred', u'Bill'])
30+
Traceback (most recent call last):
31+
File "<stdin>", line 1, in <module>
32+
TypeError: sequence item 0: expected bytes, found unicode string
33+
34+
In most other ways, these ``bytes`` objects have identical behaviours to Python 3's ``bytes``::
35+
36+
b = bytes(b'ABCD')
37+
assert list(b) == [65, 66, 67, 68]
38+
assert repr(b) == "b'ABCD'"
39+
assert b.split(b'b') == [b'A', b'CD']
40+
41+
The easiest way to ensure identical use of byte-strings compatibly between Python 3 and 2 is to wrap all byte-string literals ``b'...'`` in a ``bytes()`` call, as follows::
42+
43+
from future.builtins import *
44+
45+
# ...
46+
47+
b = bytes(b'This is my bytestring')
48+
49+
# ...
50+

‎docs/source/credits.rst‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
Credits
2+
=======
3+
:Author: Ed Schofield
4+
:Sponsor: Python Charmers Pty Ltd, Australia, and Python Charmers Pte
5+
Ltd, Singapore. http://pythoncharmers.com
6+
:Others: - ``future`` incorporates the ``six`` module by Benjamin
7+
Peterson.
8+
- The ``futurize`` script uses ``lib2to3``, ``lib3to2``, and
9+
parts of Armin Ronacher's ``python-modernize`` code.
10+
- The backported ``super()`` and ``range()`` functions are
11+
derived from Ryan Kelly's ``magicsuper`` module and Dan Crosta's
12+
``xrange`` module.
13+
- The ``python_2_unicode_compatible`` decorator is from Django. The
14+
``implements_iterator`` decorator is from a blog post by Armin
15+
Ronacher.
16+
17+
18+
Licensing
19+
---------
20+
The software is distributed under an MIT licence. The text is as follows
21+
(from LICENSE.txt):
22+
23+
Copyright (c) 2013 Python Charmers Pty Ltd, Australia
24+
25+
Permission is hereby granted, free of charge, to any person obtaining a copy
26+
of this software and associated documentation files (the "Software"), to deal
27+
in the Software without restriction, including without limitation the rights
28+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
29+
copies of the Software, and to permit persons to whom the Software is
30+
furnished to do so, subject to the following conditions:
31+
32+
The above copyright notice and this permission notice shall be included in
33+
all copies or substantial portions of the Software.
34+
35+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
38+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
41+
THE SOFTWARE.
42+

‎docs/source/custom_iterator.rst‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
Custom iterators
2+
----------------
3+
4+
If you define your own iterator, there is an incompatibility in the method name
5+
across Py3 and Py2. On Python 3 it is ``__next__``, whereas on Python 2 it is
6+
``next``.
7+
8+
Use the following decorator to allow Py3-style iterators to work
9+
identically on Py2::
10+
11+
from future.utils import implements_iterator
12+
13+
@implements_iterator
14+
class Upper(object):
15+
def __init__(self, iterable):
16+
self._iter = iter(iterable)
17+
def __next__(self): # note the Py3 interface
18+
return next(self._iter).upper()
19+
def __iter__(self):
20+
return self
21+
22+
print(list(Upper('hello')))
23+
# prints ['H', 'E', 'L', 'L', 'O']
24+
25+
On Python 3 this decorator does nothing (no-op).
26+

‎docs/source/dictmethods.rst‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
dictionary iterator methods
2+
-----------------------------
3+
4+
Python 3 dictionaries have ``.keys()``, ``.values()``, and ``.items()`` methods which
5+
return memory-efficient set-like objects, not lists. (See PEP 3106.)
6+
7+
If your dictionaries are small enough that the memory overhead of extra list
8+
creation is not significant, stick with standard Python 3 code in your Py3/2
9+
compatible codebase::
10+
11+
for item in d:
12+
# code here
13+
14+
for item in d.items():
15+
# code here
16+
17+
for value in d.values():
18+
# code here
19+
20+
21+
If your dictionaries are large, or if you want to use the Python 3 set-like
22+
behaviour on both Py3 and Python 2.7, then use the ``viewkeys`` etc. functions
23+
from ``future.utils``::
24+
25+
from future.utils import viewkeys, viewvalues, viewitems
26+
27+
for (key, value) in viewitems(hugedictionary):
28+
# some code here
29+
30+
# Set intersection:
31+
d = {i**2: i for i in range(1000)}
32+
both = viewkeys(d) & set(range(0, 1000, 7))
33+
34+
# Set union:
35+
both = viewvalues(d1) | viewvalues(d2)
36+
37+
38+
[ref]: http://www.python.org/dev/peps/pep-3106/

‎docs/source/explicit_imports.rst‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
Explicit imports
2+
----------------
3+
If you prefer explicit imports, the explicit equivalent of the ``from
4+
future.builtins import *`` line is::
5+
6+
from future.builtins import (zip, map, filter,
7+
ascii, oct, hex, chr, input,
8+
bytes, range, super, round,
9+
apply, cmp, coerce, execfile, file, long,
10+
raw_input, reduce, reload, unicode, xrange,
11+
str, StandardError)
12+
13+
To understand what each of these does, see the docs for these modules:
14+
15+
- future.builtins
16+
- future.builtins.iterators
17+
- future.builtins.misc
18+
- future.builtins.backports
19+
- future.builtins.disabled
20+
- future.builtins.str_is_unicode
21+
22+
The internal API is currently as follows::
23+
24+
from future.builtins.iterators import zip, map, filter
25+
from future.builtins.misc import ascii, oct, hex, chr, input
26+
from future.builtins.backports import bytes, range, super, round
27+
from future.builtins.disabled import (apply, cmp, coerce,
28+
execfile, file, long, raw_input, reduce, reload, unicode,
29+
xrange, StandardError)
30+
from future.builtins.str_is_unicode import str
31+
32+
But please note that this internal API is still evolving rapidly.
33+

0 commit comments

Comments
 (0)