(f)
| 21 | |
| 22 | def export_nonlocals(*vars): |
| 23 | def func(f): |
| 24 | code = map(ord, f.func_code.co_code) |
| 25 | varnames = list(f.func_code.co_varnames) |
| 26 | names = list(f.func_code.co_names) |
| 27 | cf=lambda c,i:c[i] in (LOAD_FAST,STORE_FAST) and varnames[c[i+1]] in vars |
| 28 | while True: |
| 29 | idx = find_code(code, cf) |
| 30 | if idx is None: |
| 31 | break |
| 32 | code[idx] = LOAD_NAME if code[idx] == LOAD_FAST else STORE_NAME |
| 33 | var = varnames[code[idx+1]] |
| 34 | code[idx+1] = len(names) |
| 35 | try: |
| 36 | code[idx+1] = names.index(var) |
| 37 | except ValueError: |
| 38 | names.append(var) |
| 39 | for i, var in enumerate(filter(varnames.__contains__, names)): |
| 40 | varnames[varnames.index(var)] = '__anon_var_%d' % i |
| 41 | rescode = types.CodeType(f.func_code.co_argcount, f.func_code.co_nlocals, |
| 42 | f.func_code.co_stacksize, |
| 43 | f.func_code.co_flags^0x01, |
| 44 | ''.join(map(chr, code)), f.func_code.co_consts, |
| 45 | tuple(names), tuple(varnames), |
| 46 | f.func_code.co_filename, f.func_code.co_name, |
| 47 | f.func_code.co_firstlineno, |
| 48 | f.func_code.co_lnotab, f.func_code.co_freevars, |
| 49 | f.func_code.co_cellvars) |
| 50 | return types.FunctionType(rescode, dict(f.func_globals, __ns=True), |
| 51 | f.func_name, f.func_defaults, f.func_closure) |
| 52 | return func |
| 53 | |
| 54 | def nonlocals(*vars): |
no test coverage detected