Get __doc__ from main module in imported module.

D

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))
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?
 
A

Alf P. Steinbach

* 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
 
D

David

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

Problem solved!
Thanks for the other tips too.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top