Reference Python module docstring from within a class

Question:

Consider the following code:

"""Module documentation."""
import argparse

class HandleArgs()
    """Class documentation"""
    def __call__()
        """Method documentation"""
        parser = argparse.ArgumentParser(description= __doc__)

This code will try to use the docstring for the method, not the module. How do I access the module docstring from within a method within the class?

Asked By: Jonathan

||

Answers:

Your statement is not correct. Your code will use the module docstring. If you want to use the class docstring, then self.__doc__

See below for completed example.

"""Module documentation."""
import argparse

class HandleArgs:
    """Class documentation"""
    def __call__(self):
        """Method documentation"""
        parser = argparse.ArgumentParser(description=__doc__)
        print(parser)

ha = HandleArgs()
ha()

Output

ArgumentParser(prog=’docs.py’, usage=None, description=’Module documentation.’, formatter_class=<class ‘argparse.HelpFormatter’>, conflict_handler=’error’, add_help=True)

While

"""Module documentation."""
import argparse

class HandleArgs:
    """Class documentation"""
    def __call__(self):
        """Method documentation"""
        parser = argparse.ArgumentParser(description=__doc__)
        print(parser)

ha = HandleArgs()
ha()

Output:

ArgumentParser(prog=’docs.py’, usage=None, description=’Class documentation’, formatter_class=<class ‘argparse.HelpFormatter’>, conflict_handler=’error’, add_help=True)
pc@dev:~/projects/stackoverflow$

Answered By: drum
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.