##// END OF EJS Templates
Add function to handle u'abc' (Python 2) vs. 'abc' (Python 3) in doctests and similar.
Thomas Kluyver -
Show More
@@ -1,5 +1,6 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 functools
3 import sys
4 import sys
4 import re
5 import re
5 import types
6 import types
@@ -27,6 +28,24 b' def cast_bytes(s, encoding=None):'
27 return encode(s, encoding)
28 return encode(s, encoding)
28 return s
29 return s
29
30
31 def _modify_str_or_docstring(str_change_func):
32 @functools.wraps(str_change_func)
33 def wrapper(func_or_str):
34 if isinstance(func_or_str, str):
35 func = None
36 doc = func_or_str
37 else:
38 func = func_or_str
39 doc = func.__doc__
40
41 doc = str_change_func(doc)
42
43 if func:
44 func.__doc__ = doc
45 return func
46 return doc
47 return wrapper
48
30 if sys.version_info[0] >= 3:
49 if sys.version_info[0] >= 3:
31 PY3 = True
50 PY3 = True
32
51
@@ -57,24 +76,22 b' if sys.version_info[0] >= 3:'
57 def _print_statement_sub(match):
76 def _print_statement_sub(match):
58 expr = match.groups('expr')
77 expr = match.groups('expr')
59 return "print(%s)" % expr
78 return "print(%s)" % expr
60 def doctest_refactor_print(func_or_str):
79
80 @_modify_str_or_docstring
81 def doctest_refactor_print(doc):
61 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
82 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
62 unfortunately doesn't pick up on our doctests.
83 unfortunately doesn't pick up on our doctests.
63
84
64 Can accept a string or a function, so it can be used as a decorator."""
85 Can accept a string or a function, so it can be used as a decorator."""
65 if isinstance(func_or_str, str):
86 return _print_statement_re.sub(_print_statement_sub, doc)
66 func = None
87
67 doc = func_or_str
88 # Abstract u'abc' syntax:
68 else:
89 @_modify_str_or_docstring
69 func = func_or_str
90 def u_format(s):
70 doc = func.__doc__
91 """"{u}'abc'" --> "'abc'" (Python 3)
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
92
93 Accepts a string or a function, so it can be used as a decorator."""
94 return s.format(u='')
78
95
79 else:
96 else:
80 PY3 = False
97 PY3 = False
@@ -125,3 +142,10 b' else:'
125 def doctest_refactor_print(func_or_str):
142 def doctest_refactor_print(func_or_str):
126 return func_or_str
143 return func_or_str
127
144
145 # Abstract u'abc' syntax:
146 @_modify_str_or_docstring
147 def u_format(s):
148 """"{u}'abc'" --> "u'abc'" (Python 2)
149
150 Accepts a string or a function, so it can be used as a decorator."""
151 return s.format(u='u')
General Comments 0
You need to be logged in to leave comments. Login now