If the package author provided an explict index of the package modules, then the convention is to define a list named __all__
that contains this index. So you could do something like the following to see all the submodules / subpackages of an imported package (example prints all json submodules as determined by the package author):
import json
subs = json.__all__
print(subs)
# OUTPUT
# ['dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder']
If the package author did not provide an index of the package modules, then it will be much more difficult to sort it out. One approach would be to use dir
and then sort or filter the attributes by type in an effort to narrow down to a set likely to be submodules / subpackages. Here is an example that might be useful.
import json
def sort_by_type(t):
return t[0].__name__
attrs = [(type(getattr(json, attr)), attr) for attr in dir(json)]
attrs.sort(key=sort_by_type)
for t, n in attrs:
print(t, n)
# OUTPUT
# <class 'json.decoder.JSONDecoder'> _default_decoder
# <class 'json.encoder.JSONEncoder'> _default_encoder
# <class '_frozen_importlib.ModuleSpec'> __spec__
# <class '_frozen_importlib_external.SourceFileLoader'> __loader__
# <class 'dict'> __builtins__
# <class 'function'> detect_encoding
# <class 'function'> dump
# <class 'function'> dumps
# <class 'function'> load
# <class 'function'> loads
# <class 'list'> __all__
# <class 'list'> __path__
# <class 'module'> codecs
# <class 'module'> decoder
# <class 'module'> encoder
# <class 'module'> scanner
# <class 'str'> __author__
# <class 'str'> __cached__
# <class 'str'> __doc__
# <class 'str'> __file__
# <class 'str'> __name__
# <class 'str'> __package__
# <class 'str'> __version__
# <class 'type'> JSONDecodeError
# <class 'type'> JSONDecoder
# <class 'type'> JSONEncoder