Friday, July 5, 2019

Stack Abuse: The Python Help System

When writing and running your Python programs, you may get stuck and need to get help. You may need to know the meaning of certain modules, classes, functions, keywords, etc. The good news is that Python comes with an built-in help system. This means that you don't have to seek help outside of Python itself.

In this article, you will learn how to use the built-in Python help system.

Python help() function

This function helps us to get the documentation of a certain class, function, variable, module, etc. The function should be used on the Python console to get details of various Python objects.

Passing an Object to help() Function

The Python help() function has the following syntax:

>>> help(object)

In the above syntax, the object parameter is the name of the object that you need to get help about.

For example, to know more about the Python's print function, type the following command on the Python console:

>>> help(print)

Output:

Help on built-in function print in module builtins:

print(...)  
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

To get help for the dict class, type the following on the Python console:

>>> help(dict)

Output:

Help on class dict in module builtins:

class dict(object)  
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      True if D has a key k, else False.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  

...

You can also pass an actual list object to the help() function:

>>> help(['a', 'b', 'c'])

Output:

Help on list object:

class list(object)  
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).

...

We can see that when you pass an object to the help() function, it's documentation or help page is printed. In the next section, you will learn about passing string arguments to the help() function.

Passing a String Argument to help()

If you pass a string as an argument, the string will be treated as the name of a function, module, keyword, method, class, or a documentation topic and the corresponding help page will be printed. To mark it as a string argument, enclose it within either single or double quotes.

For example:

>>> help('print')

Output:

Help on built-in function print in module builtins:

print(...)  
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

Although we passed 'print' as a string argument, we still got the documentation for the Python's print function. Here is another example:

>>> help('def')

Output:

Function definitions  
********************

A function definition defines a user-defined function object (see  
section *The standard type hierarchy*):

   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
   decorators     ::= decorator+
   decorator      ::= "@" dotted_name ["(" [parameter_list [","]] ")"] NEWLINE
   dotted_name    ::= identifier ("." identifier)*
   parameter_list ::= (defparameter ",")*
                      | "*" [parameter] ("," defparameter)* ["," "**" parameter]
                      | "**" parameter
                      | defparameter [","] )
   parameter      ::= identifier [":" expression]
   defparameter   ::= parameter ["=" expression]
   funcname       ::= identifier

A function definition is an executable statement.  Its execution binds  
the function name in the current local namespace to a function object  
(a wrapper around the executable code for the function).  This

...

Here we passed "def" as a string argument to the help() function and it returned the documentation for defining functions.

If no matching object, method, function, class or module is found, you will be notified. For example:

>>> help('qwerty')

Output:

No Python documentation found for 'qwerty'.  
Use help() to get the interactive help utility.  
Use help(str) for help on the str class.  

We are notified that no documentation was found for our string.

Sometimes, we may need to get help about a certain function that is defined in a certain Python library. This requires us to first import the library. A good example is when we need to get the documentation for the log function defined in Python's math library. In this case, we first need to import the math library then we call the help() function as demonstrated below:

>>> from math import log
>>> help(log)

Output:

Help on built-in function log in module math:

log(...)  
    log(x[, base])

    Return the logarithm of x to the given base.
    If the base not specified, returns the natural logarithm (base e) of x.

Using help() with no Argument

The help() function can be used without an argument. If you run the function without an argument, the interactive Python's help utility will be started on the interpreter console. You just have to type the following command on the Python console:

>>> help()

This will return the Python's help utility on which you can type the name of the object you need to get help about. For example:

help> print  

Output:

Help on built-in function print in module builtins:

print(...)  
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

To return to the previous prompt, just press "q".

Here is another example:

help> return  

Output:

The "return" statement  
**********************

   return_stmt ::= "return" [expression_list]

"return" may only occur syntactically nested in a function definition,
not within a nested class definition.

If an expression list is present, it is evaluated, else "None" is  
substituted.

"return" leaves the current function call with the expression list (or
"None") as return value.

When "return" passes control out of a "try" statement with a "finally"  
clause, that "finally" clause is executed before really leaving the  
function.

In a generator function, the "return" statement indicates that the  
generator is done and will cause "StopIteration" to be raised. The  
returned value (if any) is used as an argument to construct  
"StopIteration" and becomes the "StopIteration.value" attribute.

Related help topics: FUNCTIONS  

To leave the help utility and return to the Python console, just type "quit" and hit the enter key:

help> quit  

Output:

You are now leaving help and returning to the Python interpreter.  
If you want to ask for help on a particular object directly from the  
interpreter, you can type "help(object)".  Executing "help('string')"  
has the same effect as typing a particular string at the help> prompt.  
>>>

In the next section, we will be discussing how to define help() for our custom objects.

Defining Help Docs for Custom Functions and Classes

It is possible for us to define the output of help() function for our custom functions and classes by defining a docstring (document string). In Python, the first comment string added to the body of a method is treated as its docstring. The comment has to be surrounded with three double quotes. For example:

def product(a, b):  
    """
    This function multiplies two given integers, a and b
    :param x: integer
    :param y: integer
    :returns: integer
    """
    return a * b

In the above example, we have defined a function named product. This function multiplies two integer values, a and b passed to it as arguments/parameters. See the comment enclosed within three double quotes:

    """
    This function multiplies two given integers, a and b
    :param x: integer
    :param y: integer
    :returns: integer
    """

This will be treated as the docstring for the function product.

Now, create a new file and give it the name "myfile.py". Add the following code to the file:

def product(a, b):  
    """
    This function multiplies two given integers, a and b
    :param x: integer
    :param y: integer
    :returns: integer
    """
    return a * b

class Student:  
    """
    Student class in Python. It will store student details
    """
    admission = 0
    name = ''

    def __init__(self, adm, n):
        """
        A constructor of the student object
        :param adm: a positive integer,
        :param n: a string
        """
        self.admission = adm
        self.name = n

In the above example, a docstring has been defined for a function, class, and methods.

We now need to demonstrate how we can get the above docstring as the help documentation on our Python console.

First, we need to execute the script on the console in order to load both the function and class definition to the Python environment. We can use the Python's exec() method for this. Run the following command on the Python console:

>>> exec(open("myfile.py").read())

Alternatively, if you have written the code within the Python IDLE, you simply have to run it.

We can now confirm whether the function and class modules have been detected by running the globals() command on the Python console:

>>> globals()

In my case, I get the following output:

{'__doc__': None, 'log': <built-in function log>, '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__file__': 'C:/Users/admin/myfile.py', 'Student': <class '__main__.Student', 'product': <function product at 0x0000000003569B70>}

As shown in the above output, both Student and product are in the global scope dictionary. We can now use the help() function to get the help for the Student class and product function. Just run the following command on the Python console:

>>> help('myfile')

Output:

Help on module myfile:

NAME  
    myfile

CLASSES  
    builtins.object
        Student

    class Student(builtins.object)
     |  Student class in Python. It will store student details
     |  
     |  Methods defined here:
     |  
     |  __init__(self, adm, n)
     |      A constructor of the student object
     |      :param adm: a positive integer,
     |      :param n: a string
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__
     |      list of weak references to the object (if defined)
     |  
     |  ----------------------------------------------------------------------
     |  Data and other attributes defined here:
     |  
     |  admission = 0
     |  
     |  name = ''

FUNCTIONS  
    product(a, b)
        This function multiplies two given integers, a and b
        :param x: integer
        :param y: integer
        :returns: integer

FILE  
    c:\users\admin\myfile.py

Let us check the help documentation for the product function:

>>> help('myfile.product')

Output:

Help on function product in myfile:

myfile.product = product(a, b)  
    This function multiplies two given integers, a and b
    :param x: integer
    :param y: integer
    :returns: integer

Now, let us access the help documentation for the Student class:

>>> help('myfile.Student')

Output:

Help on class Student in myfile:

myfile.Student = class Student(builtins.object)  
 |  Student class in Python. It will store student details
 |  
 |  Methods defined here:
 |  
 |  __init__(self, adm, n)
 |      A constructor of the student object
 |      :param adm: a positive integer,
 |      :param n: a string
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  admission = 0
 |  
 |  name = ''

In the output, we can see the documentation that we wrote for the Student class.

Conclusion

Python comes with an built-in system from which we can get help in regards to modules, classes, functions, and keywords. This help utility can be accessed by the use of Python's help() function in the REPL. When we call this function and pass an object to it, it returns the help page or the documentation for the object. When we run the function without an argument, the help utility is opened where we can get help about objects in an interactive way. Finally, to get help regarding our custom classes and functions, we can define docstrings.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...