Get __doc__ from main module in imported module.
Alf P. Steinbach
alfps at start.no
Wed Feb 10 20:31:37 EST 2010
* David:
> I have a module toolkit.py with some functions I use often. One of
> these functions displays a usage message (__doc__).
>
> def usage(messages=[], exit=-1):
> """Print the doc string as wells as any useful messages."""
> print(__doc__)
> for message in messages:
> print("\033[91m{}\033[0m".format(message))
Consider using a terminal control library such as 'curses' instead of embedding
escape sequences directly in the text, since escape sequences vary from terminal
to terminal.
> if exit >= 0:
> sys.exit(exit)
>
> I import this module into another module, with the doc string I want
> to display. However, calling usage prints toolkit's doc string
> (None), not the current module's doc string.
The function doesn't know where it's called from.
You have to tell it, or dynamically create a module-specific function.
One way to tell it is to pass the current module as an argument.
> How can I access the top level module's doc string from toolkit?
Like
import __main__
print_usage( __main__ )
with suitable definition of 'usage'.
Cheers & hth.,
- Alf
More information about the Python-list
mailing list