[Tutor] Basic question about docstrings

Steven D'Aprano steve at pearwood.info
Thu Jul 30 18:26:11 CEST 2015


On Thu, Jul 30, 2015 at 08:24:27AM +0000, David Aldrich wrote:

> I understand that 'help' works with modules that I have imported. But 
> if I've just written a script called main.py (which contains 
> get_value()) I don't think I can 'import' that. So how would I see the 
> docstrings in main.py?

import main
help(main)


Of course, you have to write main.py so it is intended to be imported. 
If you write main.py as a regular script, then importing it the first 
time will run the script, which you don't want.

The trick is to put the script functionality in a function, say:

# File script.py

def do_this():
   """This is a helper function"""
   ...

def main():
   """Main function."""
   print("Processing...")
   do_this()
   do_that()
   do_something_else()
   print("Done!")

if __name__ == "__main__":
    # Run the main script.
    main()


By using that pattern, the file "script.py" can be imported at the 
interactive interpreter:

import script
help(script.main)
help(script.do_this)  # etc.

but of you run it directly, outside the interactive intepreter, the 
main() function will run and it will behave as a script as expected.

The reason this works is that when you run a script, Python sets the 
magic variable __name__ to "__main__". But when you import it, the 
variable is set to the actual name of the file (minus the .py 
extension).


-- 
Steve


More information about the Tutor mailing list