- Python help() function
- Python help() function
- Defining help() for custom class and functions
- Summary
- Python Help Function | How to make use of Python Help
- Syntax of Python Help Function
- Parameter of python help function-
- Return Type-
- How to use the Python Help function?
- Using help() on different data types
- To get help on various built-in data-types using python help function
- Help on module
- Using help on print
- Help Function on built-in classes
- Using the interactive shell
- What if we want help on function that doesn’t exist
- Must Read:
- Conclusion
Python help() function
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python help() function is used to get the documentation of specified module, class, function, variables etc. This method is generally used with python interpreter console to get details about python objects.
Python help() function
If no argument is given, the interactive help system starts on the interpreter console. In python help console, we can specify module, class, function names to get their help documentation. Some of them are:
help> True help> collections help> builtins help> modules help> keywords help> symbols help> topics help> LOOPING
If you want to get out of help console, type quit . We can also get the help documentation directly from the python console by passing a parameter to help() function.
>>> help('collections') >>> help(print) >>> help(globals)
>>> help('builtins.globals') Help on built-in function globals in builtins: builtins.globals = globals() Return the dictionary containing the current scope's global variables. NOTE: Updates to this dictionary *will* affect name lookups in the current global scope and vice-versa.
Defining help() for custom class and functions
We can define help() function output for our custom classes and functions by defining docstring (documentation string). By default, the first comment string in the body of a method is used as its docstring. It’s surrounded by three double quotes. Let’s say we have a python file python_help_examples.py with following code.
def add(x, y): """ This function adds the given integer arguments :param x: integer :param y: integer :return: integer """ return x + y class Employee: """ Employee class, mapped to "employee" table in Database """ name = '' def __init__(self, i, n): """ Employee object constructor :param i: integer, must be positive :param n: string """ self.id = i self.name = n
Notice that we have defined docstring for function, class and its methods. You should follow some format for documentation, I have generated some part of them automatically using PyCharm IDE. NumPy docstring guide is a good place to get some idea around proper way of help documentation. Let’s see how to get this docstring as help documentation in python console. First of all, we will have to execute this script in the console to load our function and class definition. We can do this using exec() command.
>>> exec(open("python_help_examples.py").read())
>>> globals() , '__spec__': None, '__annotations__': <>, '__builtins__': , '__warningregistry__': , 'add': , 'Employee': >
Notice that ‘Employee’ and ‘add’ are present in the global scope dictionary. Now we can get the help documentation using help() function. Let’s look at some of the examples.
>>> help('python_help_examples.add') Help on function add in python_help_examples: python_help_examples.add = add(x, y) This function adds the given integer arguments :param x: integer :param y: integer :return: integer (END)
>>> help('python_help_examples.Employee')
>>> help('python_help_examples.Employee.__init__') Help on function __init__ in python_help_examples.Employee: python_help_examples.Employee.__init__ = __init__(self, i, n) Employee object constructor :param i: integer, must be positive :param n: string (END)
Summary
Python help() function is very helpful to get the details about modules, classes, and functions. It’s always best practice to define docstring for the custom classes and functions to explain their usage. You can checkout complete python script and more Python examples from our GitHub Repository. Reference: Official Documentation
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
Python Help Function | How to make use of Python Help
There are so many functions, modules, keywords in python that it is ubiquitous to get confused. And we need to have to look at how these things work quickly. To have a quick look, we can use the help function of python. It is a straightforward, yet beneficial function. We can use it in two ways. Either we can pass the keyword/function in the argument or run the help() function without any dispute, and it will open an interactive shell.
Python Help function is used to determine the composition of certain modules. We can get the methods defined in the module, attributes, classes of the module, function, or datatype. Not only this, but we also get the docstring (documentation) related to that object.
Syntax of Python Help Function
Parameter of python help function-
Object – This can be any keyword, any module, any class, any sub-module, or anything data type we want help. If nothing is passed, it opens an interactive shell that we can take help on any functions.
Return Type-
It returns doc–string containing all the information about the object.
How to use the Python Help function?
Using help() on different data types
Let us see how we can use the help function to know more about basic datatypes such as int, string, float, etc.
# for integer help(int) # for string help(str) # for float help(float)
There are a lot of things that we get as the output, which are impossible to show here. We will truncate the output for you.
Description for int-
class int(object) | int([x]) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal can be preceded by '+' or '-' and be surrounded | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. | Base 0 means to interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4
Static Methods for str
Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | maketrans(x, y=None, z=None, /) | Return a translation table usable for str.translate(). | | If there is only one argument, it must be a dictionary mapping Unicode | ordinals (integers) or characters to Unicode ordinals, strings or None. | Character keys will be then converted to ordinals. | If there are two arguments, they must be strings of equal length, and | in the resulting dictionary, each character in x will be mapped to the | character at the same position in y. If there is a third argument, it | must be a string, whose characters will be mapped to None in the result.
Methods for float
| as_integer_ratio(self, /) | Return integer ratio. | Return a pair of integers, whose ratio is exactly equal to the original float | and with a positive denominator. | Raise OverflowError on infinities and a ValueError on NaNs. | >>> (10.0).as_integer_ratio() | (10, 1) | >>> (0.0).as_integer_ratio() | (0, 1) | >>> (-.25).as_integer_ratio() | (-1, 4) | conjugate(self, /) | Return self, the complex conjugate of any float. | hex(self, /) | Return a hexadecimal representation of a floating-point number. | >>> (-0.1).hex() | '-0x1.999999999999ap-4' | >>> 3.14159.hex() | '0x1.921f9f01b866ep+1' | is_integer(self, /) | Return True if the float is an integer.
To get help on various built-in data-types using python help function
We can also take help on the methods available for various built-in data types like list, tuple, dict, set.
# for list help(list) # for tuple help(tuple) # for dictionary help(dict) # for set help(set)
The output is so long for these built-in collections that, we will again have to show you partial outputs.
class list(object) | list(iterable=(), /) | | Built-in mutable sequence. | | If no argument is given, the constructor creates a new empty list. | The argument must be an iterable if specified.
Help on module
We can take help on any module like math, matplotlib, numpy etc. The only thing to keep in mind is that if the module needs to be imported before use, we have to import it for getting help on it too. Otherwise, we will get an error.
Help on built-in module math: NAME math DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(x, /) Return the arc cosine (measured in radians) of x. DATA e = 2.718281828459045 inf = inf nan = nan pi = 3.141592653589793 tau = 6.283185307179586
Using help on print
To get information on print function, use the below code.
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.
Help Function on built-in classes
Suppose you are working in a team and you colleague has given you a code. Now you want to know the description and the methods that are available in those classes, you can take help on user-defined classes too.
class Car: gear=0 def __init__(self,model,types,company): self.model=model self.types=types self.company=company def horn(self): print("BEEP..BEEP..BEEP!") def gear_up(self): self.gear+=1 def gear_up(self): self.gear-=1 def display_carinfo(self): print(self.model,self.types,self.company)
Suppose this is the class, and you don’t know about the methods and variables available. You can use help() on this class.
Help on class Car in module __main__: class Car(builtins.object) | Car(model, types, company) | | Methods defined here: | | __init__(self, model, types, company) | Initialize self. See help(type(self)) for accurate signature. | | display_carinfo(self) | | gear_up(self) | | horn(self) | | ---------------------------------------------------------------------- | 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: | | gear = 0
Using the interactive shell
We can use the interactive shell by not giving any argument in the python help() function.
To start the interactive shell-
We will get the output like this-
Suppose if we want to know about ‘global’ keyword, we can simply write it in the box near help.
We will get the output like this-
As soon as we got the output, we again get an box where we can know about any other function.
To exit from the shell, we can simply type ‘quit’ in the box and we will get out of it.
What if we want help on function that doesn’t exist
If we write something that doesn’t exist in the argument of help or in the interactive shell in the form of string, we will not get any error, instead we will get the following output. If we just put it as object, we will get an error.
No Python documentation found for 'anything'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
Must Read:
Conclusion
It is quite common for us python programmers to use python help function, because of the variety of functions available in python. It gives a brief overview of the keyword and lists all the functions available in the function. We can also use the interactive shell by not passing any argument in the help().
Try to run the programs on your side and let us know if you have any queries.
Happy Coding!