Allow a module to export a subset of __all__, so a user can do from module.api import *
1 2 3 4 5 6 7 8 9 10 11 12 | class fake_module(object):
def __init__(self, name, *args):
self.name = name
self.__all__ = []
for func in args:
name = func.__name__
self.__dict__[name] = func
self.__all__.append(name)
def register(self):
sys.modules["%s.%s" % (__name__, self.name)] = self
fake_module('api', class1, class2, func3, exception4).register()
|
__all__ is used for at least three things:
- what will be imported by
from ... import *
- declaring the public api
- the help() subsystem in determining what is presented by help(...)
I have a module where I want the user to be able to do a from ... import *
and just get the handful of commonly used classes, exceptions, etc -- the remainder being utility type functions and whatnot.
The above code allows from xxx.api import *
to import the subset that was declared in the fake_module, even though api
is not a separate file and even though xxx
is a single module, not a package.