democritus-project / d8s-python

Democritus functions for working with Python ASTs.
GNU Lesser General Public License v3.0
2 stars 4 forks source link

Write functions to list all imports in a given code string #5

Closed fhightower closed 3 years ago

fhightower commented 3 years ago

I would like a python_imports function to list all packages (and, if present, functions/variables) being imported:

s = '''from democritus_dates import date_parse, date_now
import requests

print(date_parse('2 days from now'))
'''

python_package_imports(s) => # {'democritus_dates': ['date_parse', 'date_now'], 'requests': []}

Function Signature

The function should accept a string argument and return a dict with package names as keys and with a list containing each explicitly imported function/variable name for each package (see the example above).

The annotated signature should look something like:

def python_package_imports(code: str) -> Dict[str, List[str]]:
    ...
fhightower commented 3 years ago

I may be able to use https://docs.python.org/3.7/library/modulefinder.html#modulefinder-example for this (may have to write code to a temp file and then read it out using the modulefinder).

mCallesen commented 3 years ago

Hi there. I'd like to give this a shot. I messed around with modulefinder a bit, but I didn't really like it. Instead, I think I can make a function that uses the ast module. My idea is to parse the given string into an AST and then look for nodes of the type Import or ImportFrom and extracting the names from them.

fhightower commented 3 years ago

Hi @mCallesen! Thanks for being willing to help. That sounds like a plan! There are a number of ast search functions in this library, so feel free to use those as needed. Let me know if you have any questions. Thanks again!

fhightower commented 3 years ago

Looks like this one was done with #33 🎉