Go ahead and do your usual from W import X, Y, Z
and then use the __all__
special symbol to define what actual symbols you intend people to import from your module:
__all__ = ('MyClass1', 'MyClass2', 'myvar1', …)
This defines the symbols that will be imported into a user’s module if they import *
from your module.
In general, Python programmers should not be using dir()
to figure out how to use your module, and if they are doing so it might indicate a problem somewhere else. They should be reading your documentation or typing help(yourmodule)
to figure out how to use your library. Or they could browse the source code yourself, in which case (a) the difference between things you import and things you define is quite clear, and (b) they will see the __all__
declaration and know which toys they should be playing with.
If you try to support dir()
in a situation like this for a task for which it was not designed, you will have to place annoying limitations on your own code, as I hope is clear from the other answers here. My advice: don’t do it! Take a look at the Standard Library for guidance: it does from … import …
whenever code clarity and conciseness require it, and provides (1) informative docstrings, (2) full documentation, and (3) readable code, so that no one ever has to run dir()
on a module and try to tell the imports apart from the stuff actually defined in the module.