Skip to content

Instantly share code, notes, and snippets.

@tdudziak
Created February 1, 2012 13:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tdudziak/1716961 to your computer and use it in GitHub Desktop.
Save tdudziak/1716961 to your computer and use it in GitHub Desktop.
A proof-of-concept function that extract import statements from Python bytecode
import dis
import inspect
def extract_imports(code):
"""Returns list of pairs (module_name, from_list) representing imports
from a given code object."""
i = 0
n = len(code.co_code)
IMPORT_NAME = dis.opmap['IMPORT_NAME']
LOAD_CONST = dis.opmap['LOAD_CONST']
result = []
last_const = None
while i < n:
op = ord(code.co_code[i])
# handle arguments if present
arg = None
if op >= dis.HAVE_ARGUMENT:
# FIXME: this doesn't support EXTENDED_ARG
arg = ord(code.co_code[i+1]) + ord(code.co_code[i+2])*256
i = i+3
else:
i = i+1
if op == IMPORT_NAME:
result.append((code.co_names[arg], last_const))
elif op == LOAD_CONST:
last_const = code.co_consts[arg]
return result
code = inspect.stack()[1][0].f_code
print extract_imports(code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment