Advertisement
Guest User

Untitled

a guest
Apr 24th, 2015
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. import linecache
  2. import traceback
  3. import sys
  4. import ast
  5.  
  6. def do_evil(*args):
  7.     # find the line that ends the function invocation
  8.     srcfile, num, _, _ = traceback.extract_stack()[-2]
  9.     # find the name of the function
  10.     funcname = sys._getframe().f_code.co_name
  11.  
  12.     # seek backwards until we have the whole call
  13.     line = ""
  14.     while funcname not in line:
  15.         line = linecache.getline(srcfile, num) + line
  16.         num -= 1
  17.  
  18.     # trim off before the call
  19.     invocation = line.rfind(funcname)
  20.     line = line[invocation:]
  21.  
  22.     # find the paren that closes the call
  23.     i = line.find('(') + 1
  24.     stack = 1
  25.     while stack > 0:
  26.         if line[i] == ')': stack -= 1
  27.         if line[i] == '(': stack += 1
  28.         i += 1
  29.     line = line[:i]
  30.  
  31.     # parse what's left into an ast
  32.     argnames = []
  33.     for arg in ast.parse(line).body[0].value.args:
  34.         argnames.append(arg.id)
  35.  
  36.     # show off
  37.     return zip(argnames, args)
  38.  
  39. x = 1
  40. y = 2
  41. print do_evil(x, y)
  42. # prints [('x', 1), ('y', 2)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement