| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
import sys, os, inspect, types |
| 10 |
import py |
| 11 |
|
| 12 |
def render_docstr(func, indent_str='', closing_str=''): |
| 13 |
""" Render a docstring as a string of lines. |
| 14 |
The argument is either a docstring or an object. |
| 15 |
Note that we don't use a sequence, since we want |
| 16 |
the docstring to line up left, regardless of |
| 17 |
indentation. The shorter triple quotes are |
| 18 |
choosen automatically. |
| 19 |
The result is returned as a 1-tuple.""" |
| 20 |
if not isinstance(func, str): |
| 21 |
doc = func.__doc__ |
| 22 |
else: |
| 23 |
doc = func |
| 24 |
if doc is None: |
| 25 |
return None |
| 26 |
doc = doc.replace('\\', r'\\') |
| 27 |
compare = [] |
| 28 |
for q in '"""', "'''": |
| 29 |
txt = indent_str + q + doc.replace(q[0], "\\"+q[0]) + q + closing_str |
| 30 |
compare.append(txt) |
| 31 |
doc, doc2 = compare |
| 32 |
doc = (doc, doc2)[len(doc2) < len(doc)] |
| 33 |
return doc |
| 34 |
|
| 35 |
|
| 36 |
class NiceCompile(object): |
| 37 |
""" Compiling parameterized strings in a way that debuggers |
| 38 |
are happy. We provide correct line numbers and a real |
| 39 |
__file__ attribute. |
| 40 |
""" |
| 41 |
def __init__(self, namespace_or_filename): |
| 42 |
if type(namespace_or_filename) is str: |
| 43 |
srcname = namespace_or_filename |
| 44 |
else: |
| 45 |
srcname = namespace_or_filename.get('__file__') |
| 46 |
if not srcname: |
| 47 |
|
| 48 |
|
| 49 |
srcname = os.path.abspath(sys.argv[-1]) |
| 50 |
self.srcname = srcname |
| 51 |
if srcname.endswith('.pyc') or srcname.endswith('.pyo'): |
| 52 |
srcname = srcname[:-1] |
| 53 |
if os.path.exists(srcname): |
| 54 |
self.srcname = srcname |
| 55 |
self.srctext = file(srcname).read() |
| 56 |
else: |
| 57 |
|
| 58 |
self.srctext = None |
| 59 |
|
| 60 |
def __call__(self, src, args=None): |
| 61 |
""" instance NiceCompile (src, args) -- formats src with args |
| 62 |
and returns a code object ready for exec. Instead of <string>, |
| 63 |
the code object has correct co_filename and line numbers. |
| 64 |
Indentation is automatically corrected. |
| 65 |
""" |
| 66 |
if self.srctext: |
| 67 |
try: |
| 68 |
p = self.srctext.index(src) |
| 69 |
except ValueError: |
| 70 |
msg = "Source text not found in %s - use a raw string" % self.srcname |
| 71 |
raise ValueError(msg) |
| 72 |
prelines = self.srctext[:p].count("\n") + 1 |
| 73 |
else: |
| 74 |
prelines = 0 |
| 75 |
|
| 76 |
for line in src.split('\n'): |
| 77 |
content = line.strip() |
| 78 |
if content and not content.startswith('#'): |
| 79 |
break |
| 80 |
|
| 81 |
if line and line[0].isspace(): |
| 82 |
|
| 83 |
prelines -= 1 |
| 84 |
src = 'if 1:\n' + src |
| 85 |
if args is not None: |
| 86 |
src = '\n' * prelines + src % args |
| 87 |
else: |
| 88 |
src = '\n' * prelines + src |
| 89 |
c = compile(src, self.srcname, "exec") |
| 90 |
|
| 91 |
|
| 92 |
if self.srcname: |
| 93 |
srcname = MyStr(self.srcname) |
| 94 |
if args is not None: |
| 95 |
srcname.__sourceargs__ = args |
| 96 |
c = newcode_withfilename(c, srcname) |
| 97 |
return c |
| 98 |
|
| 99 |
def getsource(object): |
| 100 |
""" similar to inspect.getsource, but trying to |
| 101 |
find the parameters of formatting generated methods and |
| 102 |
functions. |
| 103 |
""" |
| 104 |
name = inspect.getfile(object) |
| 105 |
if hasattr(name, '__source__'): |
| 106 |
src = str(name.__source__) |
| 107 |
else: |
| 108 |
try: |
| 109 |
src = inspect.getsource(object) |
| 110 |
except Exception: |
| 111 |
return None |
| 112 |
if hasattr(name, "__sourceargs__"): |
| 113 |
return src % name.__sourceargs__ |
| 114 |
return src |
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
class MyStr(str): |
| 123 |
""" custom string which allows adding attributes. """ |
| 124 |
|
| 125 |
def newcode(fromcode, **kwargs): |
| 126 |
names = [x for x in dir(fromcode) if x[:3] == 'co_'] |
| 127 |
for name in names: |
| 128 |
if name not in kwargs: |
| 129 |
kwargs[name] = getattr(fromcode, name) |
| 130 |
return types.CodeType( |
| 131 |
kwargs['co_argcount'], |
| 132 |
kwargs['co_nlocals'], |
| 133 |
kwargs['co_stacksize'], |
| 134 |
kwargs['co_flags'], |
| 135 |
kwargs['co_code'], |
| 136 |
kwargs['co_consts'], |
| 137 |
kwargs['co_names'], |
| 138 |
kwargs['co_varnames'], |
| 139 |
kwargs['co_filename'], |
| 140 |
kwargs['co_name'], |
| 141 |
kwargs['co_firstlineno'], |
| 142 |
kwargs['co_lnotab'], |
| 143 |
kwargs['co_freevars'], |
| 144 |
kwargs['co_cellvars'], |
| 145 |
) |
| 146 |
|
| 147 |
def newcode_withfilename(co, co_filename): |
| 148 |
newconstlist = [] |
| 149 |
cotype = type(co) |
| 150 |
for c in co.co_consts: |
| 151 |
if isinstance(c, cotype): |
| 152 |
c = newcode_withfilename(c, co_filename) |
| 153 |
newconstlist.append(c) |
| 154 |
return newcode(co, co_consts = tuple(newconstlist), |
| 155 |
co_filename = co_filename) |
| 156 |
|
| 157 |
|
| 158 |
|
| 159 |
import __future__ |
| 160 |
|
| 161 |
def compile2(source, filename='', mode='exec', flags= |
| 162 |
__future__.generators.compiler_flag, dont_inherit=0): |
| 163 |
""" |
| 164 |
A version of compile() that caches the code objects it returns. |
| 165 |
It uses py.code.compile() to allow the source to be displayed in tracebacks. |
| 166 |
""" |
| 167 |
key = (source, filename, mode, flags) |
| 168 |
try: |
| 169 |
co = compile2_cache[key] |
| 170 |
|
| 171 |
|
| 172 |
except KeyError: |
| 173 |
|
| 174 |
co = py.code.compile(source, filename, mode, flags) |
| 175 |
|
| 176 |
|
| 177 |
compile2_cache[key] = co |
| 178 |
return co |
| 179 |
|
| 180 |
compile2_cache = {} |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
def compile_template(source, resultname): |
| 185 |
"""Compiles the source code (a string or a list/generator of lines) |
| 186 |
which should be a definition for a function named 'resultname'. |
| 187 |
The caller's global dict and local variable bindings are captured. |
| 188 |
""" |
| 189 |
if not isinstance(source, py.code.Source): |
| 190 |
if isinstance(source, str): |
| 191 |
lines = [source] |
| 192 |
else: |
| 193 |
lines = list(source) |
| 194 |
lines.append('') |
| 195 |
source = py.code.Source('\n'.join(lines)) |
| 196 |
|
| 197 |
caller = sys._getframe(1) |
| 198 |
locals = caller.f_locals |
| 199 |
if locals is caller.f_globals: |
| 200 |
localnames = [] |
| 201 |
else: |
| 202 |
localnames = locals.keys() |
| 203 |
localnames.sort() |
| 204 |
values = [locals[key] for key in localnames] |
| 205 |
|
| 206 |
source = source.putaround( |
| 207 |
before = "def container(%s):" % (', '.join(localnames),), |
| 208 |
after = "# no unindent\n return %s" % resultname) |
| 209 |
|
| 210 |
d = {} |
| 211 |
exec(source.compile(), caller.f_globals, d) |
| 212 |
container = d['container'] |
| 213 |
return container(*values) |
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
def func_with_new_name(func, newname, globals=None): |
| 218 |
"""Make a renamed copy of a function.""" |
| 219 |
if globals is None: |
| 220 |
globals = func.__globals__ |
| 221 |
f = types.FunctionType(func.__code__, globals, newname, |
| 222 |
func.__defaults__, func.__closure__) |
| 223 |
if func.__dict__: |
| 224 |
f.__dict__ = {} |
| 225 |
f.__dict__.update(func.__dict__) |
| 226 |
f.__doc__ = func.__doc__ |
| 227 |
return f |
| 228 |
|
| 229 |
def func_renamer(newname): |
| 230 |
"""A function decorator which changes the name of a function.""" |
| 231 |
def decorate(func): |
| 232 |
return func_with_new_name(func, newname) |
| 233 |
return decorate |
| 234 |
|
| 235 |
PY_IDENTIFIER = ''.join([(('0' <= chr(i) <= '9' or |
| 236 |
'a' <= chr(i) <= 'z' or |
| 237 |
'A' <= chr(i) <= 'Z') and chr(i) or '_') |
| 238 |
for i in range(256)]) |
| 239 |
PY_IDENTIFIER_MAX = 120 |
| 240 |
|
| 241 |
def valid_identifier(stuff): |
| 242 |
stuff = str(stuff).translate(PY_IDENTIFIER) |
| 243 |
if not stuff or ('0' <= stuff[0] <= '9'): |
| 244 |
stuff = '_' + stuff |
| 245 |
return stuff[:PY_IDENTIFIER_MAX] |
| 246 |
|
| 247 |
CO_VARARGS = 0x0004 |
| 248 |
CO_VARKEYWORDS = 0x0008 |
| 249 |
|
| 250 |
def has_varargs(func): |
| 251 |
func = getattr(func, 'func_code', func) |
| 252 |
return (func.co_flags & CO_VARARGS) != 0 |
| 253 |
|
| 254 |
def has_varkeywords(func): |
| 255 |
func = getattr(func, 'func_code', func) |
| 256 |
return (func.co_flags & CO_VARKEYWORDS) != 0 |
| 257 |
|
| 258 |
def nice_repr_for_func(fn, name=None): |
| 259 |
mod = getattr(fn, '__module__', None) |
| 260 |
if name is None: |
| 261 |
name = getattr(fn, '__name__', None) |
| 262 |
cls = getattr(fn, 'class_', None) |
| 263 |
if name is not None and cls is not None: |
| 264 |
name = "%s.%s" % (cls.__name__, name) |
| 265 |
try: |
| 266 |
firstlineno = fn.__code__.co_firstlineno |
| 267 |
except AttributeError: |
| 268 |
firstlineno = -1 |
| 269 |
return "(%s:%d)%s" % (mod or '?', firstlineno, name or 'UNKNOWN') |
| 270 |
|
| 271 |
|
| 272 |
def rpython_wrapper(f, template, templateargs=None, **globaldict): |
| 273 |
""" |
| 274 |
We cannot simply wrap the function using *args, **kwds, because it's not |
| 275 |
RPython. Instead, we generate a function from ``template`` with exactly |
| 276 |
the same argument list. |
| 277 |
""" |
| 278 |
if templateargs is None: |
| 279 |
templateargs = {} |
| 280 |
srcargs, srcvarargs, srckeywords, defaults = inspect.getargspec(f) |
| 281 |
assert not srcvarargs, '*args not supported by rpython_wrapper' |
| 282 |
assert not srckeywords, '**kwargs not supported by rpython_wrapper' |
| 283 |
|
| 284 |
arglist = ', '.join(srcargs) |
| 285 |
templateargs.update(name=f.__name__, |
| 286 |
arglist=arglist, |
| 287 |
original=f.__name__+'_original') |
| 288 |
src = template.format(**templateargs) |
| 289 |
src = py.code.Source(src) |
| 290 |
|
| 291 |
globaldict[f.__name__ + '_original'] = f |
| 292 |
exec(src.compile(), globaldict) |
| 293 |
result = globaldict[f.__name__] |
| 294 |
result.__defaults__ = f.__defaults__ |
| 295 |
result.__dict__.update(f.__dict__) |
| 296 |
return result |