Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Notebook examples - Python 2 and 3 compatible #2627

Closed
wants to merge 2 commits into from

5 participants

@takluyver
Owner

Make the example notebooks Python 2 and 3 compatible, so that Python 3 users can get started easily too.

Along the way, I found a couple of other minor issues in the notebooks, and a problem with Image() objects when created with data=b'...'.

Closes #2622.

@ellisonbg
Owner
@pleabargain

@ellisonbg Brian, as I'm new to the block, would I have to install .14 dev in order to take advantage of your rewritten notebooks?

@bfroehle

Wow that's great. Everything looks good to me. +1 for merging.

@ellisonbg #2537 already does not merge cleanly... how much effort is required in rebasing it and fixing the conflicts?

@takluyver takluyver referenced this pull request in ellisonbg/ipython
Merged

Examples py3 compat #6

@ellisonbg
Owner
@takluyver
Owner
@bfroehle

I have no opinion on the matter (docs/examples vs. examples).

@ellisonbg
Owner
@minrk
Owner

I don't care about moving the examples out of the docs directory (benefit is negligible, and cost is minor), but in doing so, you must also take care of the literalinclude calls that currently depend on examples (update the paths, duplicate the files, or some such). An earlier rewrite of an example (options pricer, I think?) already broke one of these, so clearly people are not paying attention to this.

@ellisonbg
Owner
@bfroehle

Thanks @takluyver for the work here. Unless @ellisonbg thinks he will get to the notebook restructuring soon, I think we should consider merging this now.

@takluyver
Owner
@ellisonbg
Owner
@ellisonbg
Owner

@takluyver I have merged your PR against my branch. I am going to finish the work on my branch now so we can merge it. Does this PR have anything in addition or can it be closed?

@takluyver
Owner

Thanks Brian. Nope, it should be the same stuff. Closing this one.

@takluyver takluyver closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
View
6 IPython/core/display.py
@@ -28,6 +28,8 @@
publish_javascript, publish_jpeg
)
+from IPython.utils.py3compat import string_types
+
#-----------------------------------------------------------------------------
# Main functions
#-----------------------------------------------------------------------------
@@ -254,7 +256,7 @@ def __init__(self, data=None, url=None, filename=None):
filename : unicode
Path to a local file to load the data from.
"""
- if data is not None and data.startswith('http'):
+ if data is not None and isinstance(data, string_types) and data.startswith('http'):
self.url = data
self.filename = None
self.data = None
@@ -475,7 +477,7 @@ def __init__(self, data=None, url=None, filename=None, format=u'png', embed=None
ext = self._find_ext(url)
elif data is None:
raise ValueError("No image data found. Expecting filename, url, or data.")
- elif data.startswith('http'):
+ elif isinstance(data, string_types) and data.startswith('http'):
ext = self._find_ext(data)
else:
ext = None
View
4 IPython/utils/py3compat.py
@@ -62,6 +62,8 @@ def wrapper(func_or_str):
bytes_to_str = decode
cast_bytes_py2 = no_code
+ string_types = (str,)
+
def isidentifier(s, dotted=False):
if dotted:
return all(isidentifier(a) for a in s.split("."))
@@ -110,6 +112,8 @@ def u_format(s):
bytes_to_str = no_code
cast_bytes_py2 = cast_bytes
+ string_types = (str, unicode)
+
import re
_name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
def isidentifier(s, dotted=False):
View
9 docs/examples/notebooks/00_notebook_tour.ipynb
@@ -163,7 +163,7 @@
"input": [
">>> the_world_is_flat = 1\n",
">>> if the_world_is_flat:\n",
- "... print \"Be careful not to fall off!\""
+ "... print(\"Be careful not to fall off!\")"
],
"language": "python",
"metadata": {},
@@ -262,7 +262,7 @@
"input": [
"import time, sys\n",
"for i in range(8):\n",
- " print i,\n",
+ " print(i)\n",
" time.sleep(0.5)"
],
"language": "python",
@@ -344,7 +344,7 @@
"import sys\n",
"from ctypes import CDLL\n",
"# This will crash a Linux or Mac system; equivalent calls can be made on Windows\n",
- "dll = 'dylib' if sys.platform == 'darwin' else '.so.6'\n",
+ "dll = 'dylib' if sys.platform == 'darwin' else 'so.6'\n",
"libc = CDLL(\"libc.%s\" % dll) \n",
"libc.time(-1) # BOOM!!"
],
@@ -707,8 +707,9 @@
"collapsed": false,
"input": [
"from IPython.display import HTML\n",
+ "from base64 import b64encode\n",
"video = open(\"animation.m4v\", \"rb\").read()\n",
- "video_encoded = video.encode(\"base64\")\n",
+ "video_encoded = b64encode(video)\n",
"video_tag = '<video controls alt=\"test\" src=\"data:video/x-m4v;base64,{0}\">'.format(video_encoded)\n",
"HTML(data=video_tag)"
],
View
3  docs/examples/notebooks/01_notebook_introduction.ipynb
@@ -111,13 +111,14 @@
"cell_type": "code",
"collapsed": false,
"input": [
+ "from __future__ import print_function\n",
"def f(x):\n",
" \"\"\"My function\n",
" x : parameter\"\"\"\n",
" \n",
" return x+1\n",
"\n",
- "print \"f(3) = \", f(3)"
+ "print(\"f(3) = \", f(3))"
],
"language": "python",
"metadata": {},
View
5 docs/examples/notebooks/Animations_and_Progress.ipynb
@@ -54,7 +54,7 @@
"for i in range(10):\n",
" time.sleep(0.25)\n",
" clear_output()\n",
- " print i\n",
+ " print(i)\n",
" sys.stdout.flush()"
],
"language": "python",
@@ -203,6 +203,7 @@
"cell_type": "code",
"collapsed": true,
"input": [
+ "from __future__ import print_function\n",
"import sys, time\n",
"\n",
"class ProgressBar:\n",
@@ -214,7 +215,7 @@
" self.__update_amount(0)\n",
"\n",
" def animate(self, iter):\n",
- " print '\\r', self,\n",
+ " print('\\r', self, end='')\n",
" sys.stdout.flush()\n",
" self.update_iteration(iter + 1)\n",
"\n",
View
21 docs/examples/notebooks/Capturing Output.ipynb
@@ -27,6 +27,7 @@
"cell_type": "code",
"collapsed": false,
"input": [
+ "from __future__ import print_function\n",
"import sys"
],
"language": "python",
@@ -45,8 +46,8 @@
"collapsed": false,
"input": [
"%%capture\n",
- "print 'hi, stdout'\n",
- "print >> sys.stderr, 'hi, stderr'"
+ "print('hi, stdout')\n",
+ "print('hi, stderr', file=sys.stderr)"
],
"language": "python",
"metadata": {},
@@ -64,8 +65,8 @@
"collapsed": false,
"input": [
"%%capture captured\n",
- "print 'hi, stdout'\n",
- "print >> sys.stderr, 'hi, stderr'"
+ "print('hi, stdout')\n",
+ "print('hi, stderr', file=sys.stderr)"
],
"language": "python",
"metadata": {},
@@ -141,13 +142,13 @@
"input": [
"%%capture wontshutup\n",
"\n",
- "print \"setting up X\"\n",
+ "print(\"setting up X\")\n",
"x = np.linspace(0,5,1000)\n",
- "print \"step 2: constructing y-data\"\n",
+ "print(\"step 2: constructing y-data\")\n",
"y = np.sin(x)\n",
- "print \"step 3: display info about y\"\n",
+ "print(\"step 3: display info about y\")\n",
"plt.plot(x,y)\n",
- "print \"okay, I'm done now\""
+ "print(\"okay, I'm done now\")"
],
"language": "python",
"metadata": {},
@@ -175,8 +176,8 @@
"collapsed": false,
"input": [
"%%capture cap --no-stderr\n",
- "print 'hi, stdout'\n",
- "print >> sys.stderr, \"hello, stderr\""
+ "print('hi, stdout')\n",
+ "print(\"hello, stderr\", file=sys.stderr)"
],
"language": "python",
"metadata": {},
View
4 docs/examples/notebooks/Script Magics.ipynb
@@ -197,8 +197,8 @@
"cell_type": "code",
"collapsed": false,
"input": [
- "print error\n",
- "print output"
+ "print(error)\n",
+ "print(output)"
],
"language": "python",
"metadata": {},
View
4 docs/examples/notebooks/display_protocol.ipynb
@@ -113,7 +113,7 @@
"\n",
" def _repr_svg_(self):\n",
" if self._svg_data is None:\n",
- " self._svg_data = self._figure_data('svg')\n",
+ " self._svg_data = self._figure_data('svg').decode('utf-8')\n",
" return self._svg_data\n",
" \n",
" def _repr_latex_(self):\n",
@@ -132,7 +132,7 @@
" \n",
" @property\n",
" def latex(self):\n",
- " return Math(self._repr_svg_())\n",
+ " return Math(self._repr_latex_())\n",
" \n",
" # An example of using a property to display rich information, in this case\n",
" # the histogram of the distribution. We've hardcoded the format to be png\n",
View
20 docs/examples/notebooks/rmagic_extension.ipynb
@@ -189,7 +189,7 @@
"input": [
"b = %R a=resid(lm(Y~X))\n",
"%Rpull a\n",
- "print a\n",
+ "print(a)\n",
"assert id(b.data) == id(a.data)\n",
"%R -o a"
],
@@ -220,8 +220,8 @@
"%R d=resid(lm(Y~X)); e=coef(lm(Y~X))\n",
"%R -o d -o e\n",
"%Rpull e\n",
- "print d\n",
- "print e\n",
+ "print(d)\n",
+ "print(e)\n",
"import numpy as np\n",
"np.testing.assert_almost_equal(d, a)"
],
@@ -313,10 +313,11 @@
"cell_type": "code",
"collapsed": false,
"input": [
+ "from __future__ import print_function\n",
"v1 = %R plot(X,Y); print(summary(lm(Y~X))); vv=mean(X)*mean(Y)\n",
- "print 'v1 is:', v1\n",
+ "print('v1 is:', v1)\n",
"v2 = %R mean(X)*mean(Y)\n",
- "print 'v2 is:', v2"
+ "print('v2 is:', v2)"
],
"language": "python",
"metadata": {},
@@ -429,8 +430,9 @@
"cell_type": "code",
"collapsed": false,
"input": [
+ "from __future__ import print_function\n",
"v = %R print(summary(X)); X\n",
- "print 'v:', v"
+ "print('v:', v)"
],
"language": "python",
"metadata": {},
@@ -675,9 +677,9 @@
"cell_type": "code",
"collapsed": false,
"input": [
- "print seq1\n",
+ "print(seq1)\n",
"%R -i seq1 -o seq1\n",
- "print seq1\n",
+ "print(seq1)\n",
"seq1[0] = 200\n",
"%R print(seq1)\n",
"seq1_view = %R seq1\n",
@@ -725,7 +727,7 @@
"try:\n",
" %R -n nosuchvar\n",
"except Exception as e:\n",
- " print e.message\n",
+ " print(e)\n",
" pass"
],
"language": "python",
View
5 docs/examples/notebooks/trapezoid_rule.ipynb
@@ -116,10 +116,11 @@
"cell_type": "code",
"collapsed": false,
"input": [
+ "from __future__ import print_function\n",
"from scipy.integrate import quad, trapz\n",
"integral, error = quad(f, 1, 9)\n",
- "print \"The integral is:\", integral, \"+/-\", error\n",
- "print \"The trapezoid approximation with\", len(xint), \"points is:\", trapz(yint, xint)"
+ "print(\"The integral is:\", integral, \"+/-\", error)\n",
+ "print(\"The trapezoid approximation with\", len(xint), \"points is:\", trapz(yint, xint))"
],
"language": "python",
"metadata": {},
Something went wrong with that request. Please try again.