##// END OF EJS Templates
Document single codebase Python 3 compatibility
Thomas Kluyver -
Show More
@@ -0,0 +1,122 b''
1 Writing code for Python 2 and 3
2 ===============================
3
4 Iterators
5 ---------
6
7 Many built in functions and methods in Python 2 come in pairs, one
8 returning a list, and one returning an iterator (e.g. :func:`range` and
9 :func:`xrange`). In Python 3, there is usually only the iterator form,
10 but it has the name which gives a list in Python 2 (e.g. :func:`range`).
11
12 The way to write compatible code depends on what you need:
13
14 * A list, e.g. for serialisation, or to test if something is in it.
15 * Iteration, but it will never be used for very many items, so efficiency
16 isn't especially important.
17 * Iteration over many items, where efficiency is important.
18
19 ================ ================= =======================
20 list iteration (small) iteration(large)
21 ================ ================= =======================
22 list(range(n)) range(n) py3compat.xrange(n)
23 list(map(f, it)) map(f, it) --
24 list(zip(a, b)) zip(a, b) --
25 list(d.items()) d.items() py3compat.iteritems(d)
26 list(d.values()) d.values() py3compat.itervalues(d)
27 ================ ================= =======================
28
29 Iterating over a dictionary yields its keys, so there is rarely a need
30 to use :meth:`dict.keys` or :meth:`dict.iterkeys`.
31
32 Avoid using :func:`map` to cause function side effects. This is more
33 clearly written with a simple for loop.
34
35 Changed standard library locations
36 ----------------------------------
37
38 Several parts of the standard library have been renamed and moved. This
39 is a short list of things that we're using. A couple of them have names
40 in :mod:`IPython.utils.py3compat`, so you don't need both
41 imports in each module that uses them.
42
43 ================== ============ ===========
44 Python 2 Python 3 py3compat
45 ================== ============ ===========
46 :func:`raw_input` input input
47 :mod:`__builtin__` builtins builtin_mod
48 :mod:`StringIO` io
49 :mod:`Queue` queue
50 :mod:`cPickle` pickle
51 :mod:`thread` _thread
52 :mod:`copy_reg` copyreg
53 :mod:`urlparse` urllib.parse
54 :mod:`repr` reprlib
55 :mod:`Tkinter` tkinter
56 :mod:`Cookie` http.cookie
57 :mod:`_winreg` winreg
58 ================== ============ ===========
59
60 Be careful with StringIO: :class:`io.StringIO` is available in Python 2.7,
61 but it behaves differently from :class:`StringIO.StringIO`, and much of
62 our code assumes the use of the latter on Python 2. So a try/except on
63 the import may cause problems.
64
65 Unicode
66 -------
67
68 Always be explicit about what is text (unicode) and what is bytes.
69 *Encoding* goes from unicode to bytes, and *decoding* goes from bytes
70 to unicode.
71
72 To open files for reading or writing text, use :func:`io.open`, which is
73 the Python 3 builtin ``open`` function, available on Python 2 as well.
74 We almost always need to specify the encoding parameter, because the
75 default is platform dependent.
76
77 Relative imports
78 ----------------
79
80 ::
81
82 # This makes Python 2 behave like Python 3:
83 from __future__ import absolute_import
84
85 import io # Imports the standard library io module
86 from . import io # Import the io module from the package
87 # containing the current module
88 from .io import foo # foo from the io module next to this module
89 from IPython.utils import io # This still works
90
91 Print function
92 --------------
93
94 ::
95
96 # Support the print function on Python 2:
97 from __future__ import print_function
98
99 print(a, b)
100 print(foo, file=sys.stderr)
101 print(bar, baz, sep='\t', end='')
102
103 Metaclasses
104 -----------
105
106 The syntax for declaring a class with a metaclass is different in
107 Python 2 and 3. In most cases, the helper function
108 :func:`~IPython.utils.py3compat.with_metaclass` (copied from the six
109 library) can be used like this::
110
111 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
112 ...
113
114 Combining inheritance between Qt and the traitlets system, however, does
115 not work with this. Instead, we do this::
116
117 class QtKernelClientMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
118 ...
119
120 This gives the new class a metaclass of :class:`~IPython.qt.util.MetaQObjectHasTraits`,
121 and the parent classes :class:`~IPython.utils.traitlets.HasTraits` and
122 :class:`~IPython.qt.util.SuperQObject`.
@@ -0,0 +1,8 b''
1 Single codebase Python 3 support
2 --------------------------------
3
4 IPython previously supported Python 3 by running 2to3 during setup. We
5 have now switched to a single codebase which runs natively on Python 2.7
6 and 3.3.
7
8 For notes on how to maintain this, see :doc:`/development/pycompat`.
@@ -1,237 +1,239 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 #
2 #
3 # IPython documentation build configuration file.
3 # IPython documentation build configuration file.
4
4
5 # NOTE: This file has been edited manually from the auto-generated one from
5 # NOTE: This file has been edited manually from the auto-generated one from
6 # sphinx. Do NOT delete and re-generate. If any changes from sphinx are
6 # sphinx. Do NOT delete and re-generate. If any changes from sphinx are
7 # needed, generate a scratch one and merge by hand any new fields needed.
7 # needed, generate a scratch one and merge by hand any new fields needed.
8
8
9 #
9 #
10 # This file is execfile()d with the current directory set to its containing dir.
10 # This file is execfile()d with the current directory set to its containing dir.
11 #
11 #
12 # The contents of this file are pickled, so don't put values in the namespace
12 # The contents of this file are pickled, so don't put values in the namespace
13 # that aren't pickleable (module imports are okay, they're removed automatically).
13 # that aren't pickleable (module imports are okay, they're removed automatically).
14 #
14 #
15 # All configuration values have a default value; values that are commented out
15 # All configuration values have a default value; values that are commented out
16 # serve to show the default value.
16 # serve to show the default value.
17
17
18 import sys, os
18 import sys, os
19
19
20 ON_RTD = os.environ.get('READTHEDOCS', None) == 'True'
20 ON_RTD = os.environ.get('READTHEDOCS', None) == 'True'
21
21
22 if ON_RTD:
22 if ON_RTD:
23 # Mock the presence of matplotlib, which we don't have on RTD
23 # Mock the presence of matplotlib, which we don't have on RTD
24 # see
24 # see
25 # http://read-the-docs.readthedocs.org/en/latest/faq.html
25 # http://read-the-docs.readthedocs.org/en/latest/faq.html
26 tags.add('rtd')
26 tags.add('rtd')
27
27
28 # If your extensions are in another directory, add it here. If the directory
28 # If your extensions are in another directory, add it here. If the directory
29 # is relative to the documentation root, use os.path.abspath to make it
29 # is relative to the documentation root, use os.path.abspath to make it
30 # absolute, like shown here.
30 # absolute, like shown here.
31 sys.path.insert(0, os.path.abspath('../sphinxext'))
31 sys.path.insert(0, os.path.abspath('../sphinxext'))
32
32
33 # We load the ipython release info into a dict by explicit execution
33 # We load the ipython release info into a dict by explicit execution
34 iprelease = {}
34 iprelease = {}
35 execfile('../../IPython/core/release.py',iprelease)
35 execfile('../../IPython/core/release.py',iprelease)
36
36
37 # General configuration
37 # General configuration
38 # ---------------------
38 # ---------------------
39
39
40 # Add any Sphinx extension module names here, as strings. They can be extensions
40 # Add any Sphinx extension module names here, as strings. They can be extensions
41 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
41 # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
42 extensions = [
42 extensions = [
43 'matplotlib.sphinxext.mathmpl',
43 'matplotlib.sphinxext.mathmpl',
44 'matplotlib.sphinxext.only_directives',
44 'matplotlib.sphinxext.only_directives',
45 'matplotlib.sphinxext.plot_directive',
45 'matplotlib.sphinxext.plot_directive',
46 'sphinx.ext.autodoc',
46 'sphinx.ext.autodoc',
47 'sphinx.ext.doctest',
47 'sphinx.ext.doctest',
48 'sphinx.ext.inheritance_diagram',
48 'sphinx.ext.inheritance_diagram',
49 'sphinx.ext.intersphinx',
49 'IPython.sphinxext.ipython_console_highlighting',
50 'IPython.sphinxext.ipython_console_highlighting',
50 'IPython.sphinxext.ipython_directive',
51 'IPython.sphinxext.ipython_directive',
51 'numpydoc', # to preprocess docstrings
52 'numpydoc', # to preprocess docstrings
52 'github', # for easy GitHub links
53 'github', # for easy GitHub links
53 ]
54 ]
54
55
55 if ON_RTD:
56 if ON_RTD:
56 # Remove extensions not currently supported on RTD
57 # Remove extensions not currently supported on RTD
57 extensions.remove('matplotlib.sphinxext.only_directives')
58 extensions.remove('matplotlib.sphinxext.only_directives')
58 extensions.remove('matplotlib.sphinxext.mathmpl')
59 extensions.remove('matplotlib.sphinxext.mathmpl')
59 extensions.remove('matplotlib.sphinxext.plot_directive')
60 extensions.remove('matplotlib.sphinxext.plot_directive')
60 extensions.remove('IPython.sphinxext.ipython_directive')
61 extensions.remove('IPython.sphinxext.ipython_directive')
61 extensions.remove('IPython.sphinxext.ipython_console_highlighting')
62 extensions.remove('IPython.sphinxext.ipython_console_highlighting')
62
63
63 # Add any paths that contain templates here, relative to this directory.
64 # Add any paths that contain templates here, relative to this directory.
64 templates_path = ['_templates']
65 templates_path = ['_templates']
65
66
66 # The suffix of source filenames.
67 # The suffix of source filenames.
67 source_suffix = '.rst'
68 source_suffix = '.rst'
68
69
69 if iprelease['_version_extra']:
70 if iprelease['_version_extra']:
70 rst_prolog = """
71 rst_prolog = """
71 .. note::
72 .. note::
72
73
73 This documentation is for a development version of IPython. There may be
74 This documentation is for a development version of IPython. There may be
74 significant differences from the latest stable release (1.1.0).
75 significant differences from the latest stable release (1.1.0).
75
76
76 """
77 """
77
78
78 # The master toctree document.
79 # The master toctree document.
79 master_doc = 'index'
80 master_doc = 'index'
80
81
81 # General substitutions.
82 # General substitutions.
82 project = 'IPython'
83 project = 'IPython'
83 copyright = '2008, The IPython Development Team'
84 copyright = '2008, The IPython Development Team'
84
85
85 # ghissue config
86 # ghissue config
86 github_project_url = "https://github.com/ipython/ipython"
87 github_project_url = "https://github.com/ipython/ipython"
87
88
88 # The default replacements for |version| and |release|, also used in various
89 # The default replacements for |version| and |release|, also used in various
89 # other places throughout the built documents.
90 # other places throughout the built documents.
90 #
91 #
91 # The full version, including alpha/beta/rc tags.
92 # The full version, including alpha/beta/rc tags.
92 codename = iprelease['codename']
93 codename = iprelease['codename']
93 release = "%s: %s" % (iprelease['version'], codename)
94 release = "%s: %s" % (iprelease['version'], codename)
94 # Just the X.Y.Z part, no '-dev'
95 # Just the X.Y.Z part, no '-dev'
95 version = iprelease['version'].split('-', 1)[0]
96 version = iprelease['version'].split('-', 1)[0]
96
97
97
98
98 # There are two options for replacing |today|: either, you set today to some
99 # There are two options for replacing |today|: either, you set today to some
99 # non-false value, then it is used:
100 # non-false value, then it is used:
100 #today = ''
101 #today = ''
101 # Else, today_fmt is used as the format for a strftime call.
102 # Else, today_fmt is used as the format for a strftime call.
102 today_fmt = '%B %d, %Y'
103 today_fmt = '%B %d, %Y'
103
104
104 # List of documents that shouldn't be included in the build.
105 # List of documents that shouldn't be included in the build.
105 #unused_docs = []
106 #unused_docs = []
106
107
107 # List of directories, relative to source directories, that shouldn't be searched
108 # List of directories, relative to source directories, that shouldn't be searched
108 # for source files.
109 # for source files.
109 exclude_dirs = ['attic']
110 exclude_dirs = ['attic']
110
111
111 # If true, '()' will be appended to :func: etc. cross-reference text.
112 # If true, '()' will be appended to :func: etc. cross-reference text.
112 #add_function_parentheses = True
113 #add_function_parentheses = True
113
114
114 # If true, the current module name will be prepended to all description
115 # If true, the current module name will be prepended to all description
115 # unit titles (such as .. function::).
116 # unit titles (such as .. function::).
116 #add_module_names = True
117 #add_module_names = True
117
118
118 # If true, sectionauthor and moduleauthor directives will be shown in the
119 # If true, sectionauthor and moduleauthor directives will be shown in the
119 # output. They are ignored by default.
120 # output. They are ignored by default.
120 #show_authors = False
121 #show_authors = False
121
122
122 # The name of the Pygments (syntax highlighting) style to use.
123 # The name of the Pygments (syntax highlighting) style to use.
123 pygments_style = 'sphinx'
124 pygments_style = 'sphinx'
124
125
125
126
126 # Options for HTML output
127 # Options for HTML output
127 # -----------------------
128 # -----------------------
128
129
129 # The style sheet to use for HTML and HTML Help pages. A file of that name
130 # The style sheet to use for HTML and HTML Help pages. A file of that name
130 # must exist either in Sphinx' static/ path, or in one of the custom paths
131 # must exist either in Sphinx' static/ path, or in one of the custom paths
131 # given in html_static_path.
132 # given in html_static_path.
132 html_style = 'default.css'
133 html_style = 'default.css'
133
134
134 # The name for this set of Sphinx documents. If None, it defaults to
135 # The name for this set of Sphinx documents. If None, it defaults to
135 # "<project> v<release> documentation".
136 # "<project> v<release> documentation".
136 #html_title = None
137 #html_title = None
137
138
138 # The name of an image file (within the static path) to place at the top of
139 # The name of an image file (within the static path) to place at the top of
139 # the sidebar.
140 # the sidebar.
140 #html_logo = None
141 #html_logo = None
141
142
142 # Add any paths that contain custom static files (such as style sheets) here,
143 # Add any paths that contain custom static files (such as style sheets) here,
143 # relative to this directory. They are copied after the builtin static files,
144 # relative to this directory. They are copied after the builtin static files,
144 # so a file named "default.css" will overwrite the builtin "default.css".
145 # so a file named "default.css" will overwrite the builtin "default.css".
145 html_static_path = ['_static']
146 html_static_path = ['_static']
146
147
147 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
148 # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
148 # using the given strftime format.
149 # using the given strftime format.
149 html_last_updated_fmt = '%b %d, %Y'
150 html_last_updated_fmt = '%b %d, %Y'
150
151
151 # If true, SmartyPants will be used to convert quotes and dashes to
152 # If true, SmartyPants will be used to convert quotes and dashes to
152 # typographically correct entities.
153 # typographically correct entities.
153 #html_use_smartypants = True
154 #html_use_smartypants = True
154
155
155 # Custom sidebar templates, maps document names to template names.
156 # Custom sidebar templates, maps document names to template names.
156 #html_sidebars = {}
157 #html_sidebars = {}
157
158
158 # Additional templates that should be rendered to pages, maps page names to
159 # Additional templates that should be rendered to pages, maps page names to
159 # template names.
160 # template names.
160 html_additional_pages = {
161 html_additional_pages = {
161 'interactive/htmlnotebook': 'htmlnotebook.html',
162 'interactive/htmlnotebook': 'htmlnotebook.html',
162 }
163 }
163
164
164 # If false, no module index is generated.
165 # If false, no module index is generated.
165 #html_use_modindex = True
166 #html_use_modindex = True
166
167
167 # If true, the reST sources are included in the HTML build as _sources/<name>.
168 # If true, the reST sources are included in the HTML build as _sources/<name>.
168 #html_copy_source = True
169 #html_copy_source = True
169
170
170 # If true, an OpenSearch description file will be output, and all pages will
171 # If true, an OpenSearch description file will be output, and all pages will
171 # contain a <link> tag referring to it. The value of this option must be the
172 # contain a <link> tag referring to it. The value of this option must be the
172 # base URL from which the finished HTML is served.
173 # base URL from which the finished HTML is served.
173 #html_use_opensearch = ''
174 #html_use_opensearch = ''
174
175
175 # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
176 # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
176 #html_file_suffix = ''
177 #html_file_suffix = ''
177
178
178 # Output file base name for HTML help builder.
179 # Output file base name for HTML help builder.
179 htmlhelp_basename = 'ipythondoc'
180 htmlhelp_basename = 'ipythondoc'
180
181
182 intersphinx_mapping = {'http://docs.python.org/2/': None}
181
183
182 # Options for LaTeX output
184 # Options for LaTeX output
183 # ------------------------
185 # ------------------------
184
186
185 # The paper size ('letter' or 'a4').
187 # The paper size ('letter' or 'a4').
186 latex_paper_size = 'letter'
188 latex_paper_size = 'letter'
187
189
188 # The font size ('10pt', '11pt' or '12pt').
190 # The font size ('10pt', '11pt' or '12pt').
189 latex_font_size = '11pt'
191 latex_font_size = '11pt'
190
192
191 # Grouping the document tree into LaTeX files. List of tuples
193 # Grouping the document tree into LaTeX files. List of tuples
192 # (source start file, target name, title, author, document class [howto/manual]).
194 # (source start file, target name, title, author, document class [howto/manual]).
193
195
194 latex_documents = [
196 latex_documents = [
195 ('index', 'ipython.tex', 'IPython Documentation',
197 ('index', 'ipython.tex', 'IPython Documentation',
196 ur"""The IPython Development Team""", 'manual', True),
198 ur"""The IPython Development Team""", 'manual', True),
197 ('parallel/winhpc_index', 'winhpc_whitepaper.tex',
199 ('parallel/winhpc_index', 'winhpc_whitepaper.tex',
198 'Using IPython on Windows HPC Server 2008',
200 'Using IPython on Windows HPC Server 2008',
199 ur"Brian E. Granger", 'manual', True)
201 ur"Brian E. Granger", 'manual', True)
200 ]
202 ]
201
203
202 # The name of an image file (relative to this directory) to place at the top of
204 # The name of an image file (relative to this directory) to place at the top of
203 # the title page.
205 # the title page.
204 #latex_logo = None
206 #latex_logo = None
205
207
206 # For "manual" documents, if this is true, then toplevel headings are parts,
208 # For "manual" documents, if this is true, then toplevel headings are parts,
207 # not chapters.
209 # not chapters.
208 #latex_use_parts = False
210 #latex_use_parts = False
209
211
210 # Additional stuff for the LaTeX preamble.
212 # Additional stuff for the LaTeX preamble.
211 #latex_preamble = ''
213 #latex_preamble = ''
212
214
213 # Documents to append as an appendix to all manuals.
215 # Documents to append as an appendix to all manuals.
214 #latex_appendices = []
216 #latex_appendices = []
215
217
216 # If false, no module index is generated.
218 # If false, no module index is generated.
217 latex_use_modindex = True
219 latex_use_modindex = True
218
220
219
221
220 # Options for texinfo output
222 # Options for texinfo output
221 # --------------------------
223 # --------------------------
222
224
223 texinfo_documents = [
225 texinfo_documents = [
224 (master_doc, 'ipython', 'IPython Documentation',
226 (master_doc, 'ipython', 'IPython Documentation',
225 'The IPython Development Team',
227 'The IPython Development Team',
226 'IPython',
228 'IPython',
227 'IPython Documentation',
229 'IPython Documentation',
228 'Programming',
230 'Programming',
229 1),
231 1),
230 ]
232 ]
231
233
232
234
233 # Cleanup
235 # Cleanup
234 # -------
236 # -------
235 # delete release info to avoid pickling errors from sphinx
237 # delete release info to avoid pickling errors from sphinx
236
238
237 del iprelease
239 del iprelease
@@ -1,26 +1,27 b''
1 .. _developer_guide:
1 .. _developer_guide:
2
2
3 =========================
3 =========================
4 IPython developer's guide
4 IPython developer's guide
5 =========================
5 =========================
6
6
7 This are two categories of developer focused documentation:
7 This are two categories of developer focused documentation:
8
8
9 1. Documentation for developers of *IPython itself*.
9 1. Documentation for developers of *IPython itself*.
10 2. Documentation for developers of third party tools and libraries
10 2. Documentation for developers of third party tools and libraries
11 that use IPython.
11 that use IPython.
12
12
13 This part of our documentation only contains information in the second category.
13 This part of our documentation only contains information in the second category.
14
14
15 Developers interested in working on IPython itself should consult
15 Developers interested in working on IPython itself should consult
16 our `developer information <https://github.com/ipython/ipython/wiki/Dev:-Index>`_
16 our `developer information <https://github.com/ipython/ipython/wiki/Dev:-Index>`_
17 on the IPython GitHub wiki.
17 on the IPython GitHub wiki.
18
18
19 .. toctree::
19 .. toctree::
20 :maxdepth: 1
20 :maxdepth: 1
21
21
22
22
23 gitwash/index
23 gitwash/index
24 messaging
24 messaging
25 parallel_messages
25 parallel_messages
26 parallel_connections
26 parallel_connections
27 pycompat
General Comments 0
You need to be logged in to leave comments. Login now