Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 055cc6c

Browse files
committed
Function to refactor print statements in doctests to print() function calls for Python 3.
1 parent 8ffab04 commit 055cc6c

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

IPython/utils/py3compat.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# coding: utf-8
22
"""Compatibility tricks for Python 3. Mainly to do with unicode."""
33
import sys
4+
import re
45
import types
56

67
orig_open = open
@@ -50,6 +51,30 @@ def isidentifier(s, dotted=False):
5051
def execfile(fname, glob, loc=None):
5152
loc = loc if (loc is not None) else glob
5253
exec compile(open(fname).read(), fname, 'exec') in glob, loc
54+
55+
# Refactor print statements in doctests.
56+
_print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
57+
def _print_statement_sub(match):
58+
expr = match.groups('expr')
59+
return "print(%s)" % expr
60+
def doctest_refactor_print(func_or_str):
61+
"""Refactor 'print x' statements in a doctest to print(x) style. 2to3
62+
unfortunately doesn't pick up on our doctests.
63+
64+
Can accept a string or a function, so it can be used as a decorator."""
65+
if isinstance(func_or_str, str):
66+
func = None
67+
doc = func_or_str
68+
else:
69+
func = func_or_str
70+
doc = func.__doc__
71+
doc = _print_statement_re.sub(_print_statement_sub, doc)
72+
73+
if func:
74+
func.__doc__ = doc
75+
return func
76+
return doc
77+
5378

5479
else:
5580
PY3 = False
@@ -96,4 +121,7 @@ def MethodType(func, instance):
96121

97122
# don't override system execfile on 2.x:
98123
execfile = execfile
124+
125+
def doctest_refactor_print(func_or_str):
126+
return func_or_str
99127

0 commit comments

Comments
 (0)