|
1 | 1 | # coding: utf-8 |
2 | 2 | """Compatibility tricks for Python 3. Mainly to do with unicode.""" |
3 | 3 | import sys |
| 4 | +import re |
4 | 5 | import types |
5 | 6 |
|
6 | 7 | orig_open = open |
@@ -50,6 +51,30 @@ def isidentifier(s, dotted=False): |
50 | 51 | def execfile(fname, glob, loc=None): |
51 | 52 | loc = loc if (loc is not None) else glob |
52 | 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 | 79 | else: |
55 | 80 | PY3 = False |
@@ -96,4 +121,7 @@ def MethodType(func, instance): |
96 | 121 |
|
97 | 122 | # don't override system execfile on 2.x: |
98 | 123 | execfile = execfile |
| 124 | + |
| 125 | + def doctest_refactor_print(func_or_str): |
| 126 | + return func_or_str |
99 | 127 |
|
0 commit comments