Show More
@@ -1,5 +1,6 | |||
|
1 | 1 | # coding: utf-8 |
|
2 | 2 | """Compatibility tricks for Python 3. Mainly to do with unicode.""" |
|
3 | import functools | |
|
3 | 4 | import sys |
|
4 | 5 | import re |
|
5 | 6 | import types |
@@ -27,6 +28,24 def cast_bytes(s, encoding=None): | |||
|
27 | 28 | return encode(s, encoding) |
|
28 | 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 | 49 | if sys.version_info[0] >= 3: |
|
31 | 50 | PY3 = True |
|
32 | 51 | |
@@ -57,24 +76,22 if sys.version_info[0] >= 3: | |||
|
57 | 76 | def _print_statement_sub(match): |
|
58 | 77 | expr = match.groups('expr') |
|
59 | 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 | 82 | """Refactor 'print x' statements in a doctest to print(x) style. 2to3 |
|
62 | 83 | unfortunately doesn't pick up on our doctests. |
|
63 | 84 | |
|
64 | 85 | 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 | |
|
86 | return _print_statement_re.sub(_print_statement_sub, doc) | |
|
87 | ||
|
88 | # Abstract u'abc' syntax: | |
|
89 | @_modify_str_or_docstring | |
|
90 | def u_format(s): | |
|
91 | """"{u}'abc'" --> "'abc'" (Python 3) | |
|
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 | 96 | else: |
|
80 | 97 | PY3 = False |
@@ -125,3 +142,10 else: | |||
|
125 | 142 | def doctest_refactor_print(func_or_str): |
|
126 | 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