Get __doc__ from main module in imported module.

Get __doc__ from main module in imported module.

Post by Davi » Fri, 12 Feb 2010 09:48:39


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))
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.

How can I access the top level module's doc string from toolkit?
 
 
 

Get __doc__ from main module in imported module.

Post by Alf P. Ste » Fri, 12 Feb 2010 10:31:37

* David:

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.



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.



Like

import __main__
print_usage( __main__ )

with suitable definition of 'usage'.


Cheers & hth.,

- Alf

 
 
 

Get __doc__ from main module in imported module.

Post by Davi » Fri, 12 Feb 2010 11:32:28

> > How can I access the top level module's doc string from toolkit?
> mport __main__> > rint_usage( __main__>) >>
> with suitable definition of 'usage>. >>
> Cheers & hth>, >>
> - Alf

Problem solved!
Thanks for the other tips too.