Skip to content

Instantly share code, notes, and snippets.

Last active Apr 10, 2019
What would you like to do?
import pathlib
import ast
def _packages(path):
return _include_parents(path.with_suffix('').parts)
def _include_parents(parts):
p = list(parts)
while p:
mod = tuple(p)
yield mod
if mod and not mod[-1] == '__init__':
yield mod + ('__init__', )
def _split(mod):
return tuple(mod.split('.')) if mod else ()
def parse_imports(path):
t = path.read_text('utf8', 'surrogateescape')
packages = _packages(path)
package = next(packages)
yield package
yield from packages
for stmt in ast.parse(t).body:
if isinstance(stmt, ast.Import):
for alias in stmt.names:
yield from _include_parents(_split(
if isinstance(stmt, ast.ImportFrom):
root = package[:-stmt.level] + _split(stmt.module)
for alias in stmt.names:
yield from _include_parents(root + _split(
def main():
seen = set()
roots = set()
for p in pathlib.Path('odc').glob('**/*.py'):
imports = list(parse_imports(p))
package = imports[0]
roots -= set(imports)
if package not in seen:
seen |= set(imports)
print(sorted('.'.join(m) for m in roots))
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment