##// END OF EJS Templates
Function to refactor print statements in doctests to print() function calls for Python 3.
Thomas Kluyver -
Show More
@@ -1,6 +1,7 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 import sys
3 import sys
4 import re
4 import types
5 import types
5
6
6 orig_open = open
7 orig_open = open
@@ -50,6 +51,30 b' if sys.version_info[0] >= 3:'
50 def execfile(fname, glob, loc=None):
51 def execfile(fname, glob, loc=None):
51 loc = loc if (loc is not None) else glob
52 loc = loc if (loc is not None) else glob
52 exec compile(open(fname).read(), fname, 'exec') in glob, loc
53 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
53
78
54 else:
79 else:
55 PY3 = False
80 PY3 = False
@@ -96,4 +121,7 b' else:'
96
121
97 # don't override system execfile on 2.x:
122 # don't override system execfile on 2.x:
98 execfile = execfile
123 execfile = execfile
124
125 def doctest_refactor_print(func_or_str):
126 return func_or_str
99
127
General Comments 0
You need to be logged in to leave comments. Login now