tags:

views:

103

answers:

4

Is there a way of knowing which modules are available to import from inside a package?

+2  A: 

Many packages will include a list called __all__, which lists the member modules. This is used when python does from x import *. You can read more about that here.

If the package does not define __all__, you'll have to do something like the answer to a question I asked earlier, here.

DNS
A: 

import fred

print dir(fred)

Phil
That lists all attributes, not just sub-modules, so it doesn't answer the question.
bignose
A: 

You have the source.

Look at the files inside the package directory. Those modules are available for you to import.

S.Lott
There are many ways for there to be files inside the package (a directory) which are *not* modules available for import. The Python import mechanism knows the difference, so it seems reasonable for it to expose that functionality rather than having everyone re-invent it.
bignose
Invent? Invent what? Just read the source.
S.Lott
A: 

dir([object]);

Without arguments, dir() return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

So, in the case of a module, such as 'sys':

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']

That's all there is to it.

That lists all attributes, not just sub-modules, so it doesn't answer the question.
bignose