Skip to content

Commit 84598f9

Browse files
committed
[WIP]: use pkgutil
1 parent 206519a commit 84598f9

File tree

1 file changed

+38
-23
lines changed

1 file changed

+38
-23
lines changed

support/walk-modules.py

Lines changed: 38 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,43 @@
11
#!/usr/bin/env python
22

33
import inspect
4+
import pkgutil
45
import sys
56

67
SEEN_MODS = set()
78

89

10+
def walk_pkgutil(mod_name, mod):
11+
for pkg in pkgutil.walk_packages(mod.__path__, mod_name + "."):
12+
walk(pkg.name)
13+
14+
15+
def walk_naive(mod_name, mod):
16+
for attr in dir(mod):
17+
attr_obj = getattr(mod, attr, None)
18+
# Shouldn't happen, but who knows.
19+
if attr_obj is None:
20+
continue
21+
22+
# If this member isn't a module, skip it.
23+
if not inspect.ismodule(attr_obj):
24+
continue
25+
26+
# To filter "real" submodules from re-exports, we try
27+
# and import the submodule by its qualified name.
28+
# If the import fails, we know it's a re-exported module.
29+
try:
30+
submod_name = mod_name + "." + attr
31+
__import__(submod_name)
32+
walk(submod_name)
33+
except ImportError:
34+
# ...but sometimes we do want to include re-exports, since
35+
# they might be things like "accelerator" modules that don't
36+
# appear anywhere else.
37+
# For example, `_bz2` might appear as a re-export.
38+
walk(attr)
39+
40+
941
def walk(mod_name):
1042
if mod_name in SEEN_MODS:
1143
return
@@ -16,29 +48,12 @@ def walk(mod_name):
1648
# Try and import it.
1749
try:
1850
mod = __import__(mod_name)
19-
for attr in dir(mod):
20-
attr_obj = getattr(mod, attr, None)
21-
# Shouldn't happen, but who knows.
22-
if attr_obj is None:
23-
continue
24-
25-
# If this member isn't a module, skip it.
26-
if not inspect.ismodule(attr_obj):
27-
continue
28-
29-
# To filter "real" submodules from re-exports, we try
30-
# and import the submodule by its qualified name.
31-
# If the import fails, we know it's a re-exported module.
32-
try:
33-
submod_name = mod_name + "." + attr
34-
__import__(submod_name)
35-
walk(submod_name)
36-
except ImportError:
37-
# ...but sometimes we do want to include re-exports, since
38-
# they might be things like "accelerator" modules that don't
39-
# appear anywhere else.
40-
# For example, `_bz2` might appear as a re-export.
41-
walk(attr)
51+
52+
if hasattr(mod, "__path__"):
53+
walk_pkgutil(mod_name, mod)
54+
else:
55+
walk_naive(mod_name, mod)
56+
4257
except ImportError:
4358
pass
4459

0 commit comments

Comments
 (0)