joeF
joeF

Reputation: 3

Print the docString of the currently running python script from an imported module

I desire the following behaviour

# module.py
""" module's docString """

def foo():
   print(??something??)
   do other stuff`
# script.py
""" Scripts docString """

from module import foo

foo()

do otherstuff

Now when I run python script.py I would like the call to foo() to print the docString of script.py

I have tried

# module.py
""" module's docString """

def foo():
   print(__doc__)
   do other stuff`

But this prints the docString of module.py

Upvotes: 0

Views: 52

Answers (2)

Saurabh Sangwan
Saurabh Sangwan

Reputation: 427

The docstring is stored in the module's __doc__ global.

def foo():
   print("something")
   import script
   print(script.__doc__)

Upvotes: 0

chepner
chepner

Reputation: 531075

You can use sys.modules to get a reference to the __main__ module, whatever module that might be. With that, you can access its __doc__ attribute.

# module.py
""" module's docString """

import sys


def foo():
   print(sys.modules['__main__'].__doc__)

Upvotes: 2

Related Questions