Created
May 12, 2024 21:35
-
-
Save kirillzhosul/c9d6ebfdaf2c26cd4ccc5d295276eb89 to your computer and use it in GitHub Desktop.
Get (detect) imports from raw python source
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
exprs = [ | |
""" | |
import flask | |
import django | |
a = 'hello world!' | |
b = __import__ | |
b("io") | |
""" | |
] | |
import_names = [] | |
[ | |
[import_names.extend(expr.names) for expr in _exprs] | |
for _exprs in [ | |
list( | |
filter(lambda a: type(a) in (ast.Import, ast.ImportFrom), ast.parse(e).body) | |
) | |
for e in exprs | |
] | |
] | |
[ | |
[ | |
import_names.extend( | |
[ | |
[ | |
str(arg.value) | |
if type(arg) == ast.Constant | |
else (arg.id if type(arg) == ast.Name else None) | |
][0] | |
for arg in expr.value.args | |
] | |
) | |
for expr in _exprs | |
] | |
for _exprs in [ | |
list( | |
filter( | |
lambda a: type(a) == ast.Expr and a.value.func.id == "__import__", | |
ast.parse(e).body, | |
) | |
) | |
for e in exprs | |
] | |
] | |
[ | |
print(m) | |
for m in set( | |
list( | |
map( | |
lambda e: e.name if type(e) == ast.alias else e, | |
list(filter(lambda a: a is not None, import_names)), | |
) | |
) | |
) | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment