Skip to content

Instantly share code, notes, and snippets.

@mikalv
Forked from tdudziak/extract_imports.py
Created August 17, 2019 20:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikalv/68bfcf917f6b5e8b7e8bb5f05cdf3c8f to your computer and use it in GitHub Desktop.
Save mikalv/68bfcf917f6b5e8b7e8bb5f05cdf3c8f 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