Search code examples
pythondocstring

Custom Docstrings in Python


How would create a custom docstring in python? Would you just say __nameofdocstring__ or is there something else you should do?

Is it possible to create a new docstring for a certain .py file? I want to write __notes__ = "blah blah blah", but just saying that statement won't work.


Solution

  • Docstring Example

    Let's show how an example of a multi-line docstring:

    def my_function():
    """Do nothing, but document it.
    
    No, really, it doesn't do anything.
    """
    pass
    

    Let's see how this would look like when we print it

    print my_function.__doc__
    
    Do nothing, but document it.
    
        No, really, it doesn't do anything.
    

    Declaration of docstrings

    The following Python file shows the declaration of docstrings within a python source file:

    """
    Assuming this is file mymodule.py, then this string, being the
    first statement in the file, will become the "mymodule" module's
    docstring when the file is imported.
    """
    
    class MyClass(object):
        """The class's docstring"""
    
        def my_method(self):
            """The method's docstring"""
    
    def my_function():
        """The function's docstring"""
    

    How to access the Docstring

    The following is an interactive session showing how the docstrings may be accessed

    >>> import mymodule
    >>> help(mymodule)
    

    Assuming this is file mymodule.py then this string, being the first statement in the file will become the mymodule modules docstring when the file is imported.

    >>> help(mymodule.MyClass)
    The class's docstring
    
    >>> help(mymodule.MyClass.my_method)
    The method's docstring
    
    >>> help(mymodule.my_function)
    The function's docstring