In Python, the help() function is a built-in function that provides information about modules, classes, functions, and modules. In this article, we will learn about help function in Python.
help() function in Python Syntax
Syntax: help([object])
Parameters (Optional) : Any object for which we want some help or the information.
If the help function is passed without an argument, then the interactive help utility starts up on the console.
What is Help function in Python?
The Python help function is used to display the documentation of modules, functions, classes, keywords, etc. It provides information about modules, classes, functions, and methods. It is a useful tool for getting documentation and assistance on various aspects of Python.
Python help() function Examples
Simple help() Program
In this example, we are using help() without any object to access documentation in Python.
Python
OutputWelcome to Python 3.7's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.
Enter the name ...
Help with Print Function in Python
Let us check the documentation of the print function in the Python console.
Python
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.
Help on User Defined Class in Python
Help function output can also be defined for user-defined functions and classes. The docstring(documentation string) is used for documentation. It is nested inside triple quotes and is the first statement within a class or function or a module. Let us define a class with functions.
Python
class Helper:
def __init__(self):
'''The helper class is initialized'''
def print_help(self):
'''Returns the help description'''
print('helper description')
help(Helper)
help(Helper.print_help)
Output
Help on class Helper in module __main__:
class Helper(builtins.object)
| Methods defined here:
|
| __init__(self)
| The helper class is initialized
|
| print_help(self)
| Returns the help description
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
Help on function print_help in module __main__:
print_help(self)
Returns the help description
If no Help or Info is Present
In this example, we are using help() if no help or info is present and access documentation in Python.
Python
print(help("GeeksforGeeks"))
OutputNo Python documentation found for 'GeeksforGeeks'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
None
If a string is given as an argument
In this example, we are passing a string inside the help function to access documentation in Python.
Python
OutputNo Python documentation found for 'gfg'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.
Python help() function docstring
The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.
Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function.
Python
def my_function():
'''Demonstrates triple double quotes
docstrings and does nothing really.'''
return None
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
help(my_function)
OutputUsing __doc__:
Demonstrates triple double quotes
docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:
my_function()
Demonstrates triple double quot...
Help function in Python – FAQs
How to handle unexpected exception in Python?
To handle unexpected exceptions in Python, you can use a try-except block with a generic Exception class or BaseException as the exception type. This will catch any exception that occurs within the try block.
try:
# Code that might raise an exception
result = 10 / 0 # Example of a division by zero which raises an exception
except Exception as e:
print("An unexpected error occurred:", str(e))
# Handle the exception gracefully, log it, or take appropriate action
How to handle exceptions inside a class in Python?
To handle exceptions inside a class in Python, you can use try-except blocks within methods of the class.
class MyClass:
def method_with_exception(self):
try:
# Code that might raise an exception
result = 10 / 0 # Example of a division by zero which raises an exception
except ZeroDivisionError as e:
print("Division by zero error:", str(e))
# Handle the specific exception
except Exception as e:
print("An unexpected error occurred:", str(e))
# Handle any other exceptions
# Example usage:
obj = MyClass()
obj.method_with_exception()
How to pass an exception in Python?
In Python, you can raise an exception using the raise statement. This allows you to indicate that an exceptional situation has occurred within your code.
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
# Example usage:
try:
validate_age(-5)
except ValueError as e:
print("Invalid age input:", str(e))
# Handle the raised exception
How to catch an unknown exception in Python?
To catch an unknown or unexpected exception in Python, you can use a catch-all except block without specifying a specific exception type. This will handle any exception that occurs within the try block.
try:
# Code that might raise an exception
result = 10 / 0 # Example of a division by zero which raises an exception
except Exception as e:
print("An unknown or unexpected error occurred:", str(e))
# Handle the exception gracefully, log it, or take appropriate action
Is the finally block always executed?
Yes, the finally block in a try-except-finally statement is always executed, regardless of whether an exception was raised or not. It is typically used to perform cleanup actions such as closing files or releasing resources that were opened or acquired in the try block.
try:
# Code that might raise an exception
file = open('example.txt', 'r')
result = 10 / 0 # Example of a division by zero which raises an exception
except ZeroDivisionError as e:
print("Division by zero error:", str(e))
# Handle specific exception
except Exception as e:
print("An unexpected error occurred:", str(e))
# Handle any other exceptions
finally:
print("Closing file")
file.close() # This will always execute, even if an exception was raised
Similar Reads
Iterators in Python
An iterator in Python is an object that holds a sequence of values and provide sequential traversal through a collection of items such as lists, tuples and dictionaries. . The Python iterators object is initialized using the iter() method. It uses the next() method for iteration. __iter__(): __iter_
3 min read
Iterator Functions in Python | Set 1
Perquisite: Iterators in PythonPython in its definition also allows some interesting and useful iterator functions for efficient looping and making execution of the code faster. There are many build-in iterators in the module "itertools". This module implements a number of iterator building blocks.
4 min read
Python __iter__() and __next__() | Converting an object into an iterator
In many cases, we may need to access an object in a way that treats it as if it were an iterator. This means we want to interact with the object in a manner similar to how we would with an iterator, enabling us to iterate over it or perform other iterable operations. For clarity, it's useful to say
6 min read
Python | Difference between iterable and iterator
Iterable is an object, that one can iterate over. It generates an Iterator when passed to iter() method. An iterator is an object, which is used to iterate over an iterable object using the __next__() method. Iterators have the __next__() method, which returns the next item of the object. Note: Ever
3 min read
When to use yield instead of return in Python?
The yield statement suspends a function's execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of v
2 min read
Generators in Python
Python generator functions are a powerful tool for creating iterators. In this article, we will discuss how the generator function works in Python. Generator Function in PythonA generator function is a special type of function that returns an iterator object. Instead of using return to send back a s
5 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
10 min read
Returning Multiple Values in Python
In Python, we can return multiple values from a function. Following are different ways 1) Using Object: This is similar to C/C++ and Java, we can create a class (in C, struct) to hold multiple values and return an object of the class. Python Code # A Python program to return multiple # values from a
4 min read
*args and **kwargs in Python
In Python, *args and **kwargs are used to allow functions to accept an arbitrary number of arguments. These features provide great flexibility when designing functions that need to handle a varying number of inputs. Example: [GFGTABS] Python # *args example def fun(*args): return sum(args) print(fun
4 min read
Packing and Unpacking Arguments in Python
We use two operators * (for tuples) and ** (for dictionaries). Background Consider a situation where we have a function that receives four arguments. We want to make a call to this function and we have a list of size 4 with us that has all arguments for the function. If we simply pass a list to the
5 min read
First Class functions in Python
First-class function is a concept where functions are treated as first-class citizens. By treating functions as first-class citizens, Python allows you to write more abstract, reusable, and modular code. This means that functions in such languages are treated like any other variable. They can be pas
2 min read
Python Closures
In Python, a closure is a powerful concept that allows a function to remember and access variables from its lexical scope, even when the function is executed outside that scope. Closures are closely related to nested functions and are commonly used in functional programming, event handling and callb
3 min read
Decorators in Python
In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
Help function in Python
In Python, the help() function is a built-in function that provides information about modules, classes, functions, and modules. In this article, we will learn about help function in Python. help() function in Python SyntaxSyntax: help([object]) Parameters (Optional) : Any object for which we want so
6 min read
Python | __import__() function
While writing a code, there might be a need for some specific modules. So we import those modules by using a single-line code in Python. But what if the name of the module needed is known to us only during runtime? How can we import that module? One can use Python's inbuilt __import__() function. It
3 min read
Python Classes and Objects
A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
6 min read
Constructors in Python
In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
3 min read
Destructors in Python
Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
7 min read
Inheritance in Python
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
7 min read
Encapsulation in Python
In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
6 min read
Polymorphism in Python
Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave differently based on the type of data they are handling. Derived from Greek, the term literally means "many forms". Python's dynamic typing and duck typing make it inherently pol
7 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated
5 min read
File Handling in Python
File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
7 min read
Reading and Writing to text files in Python
Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character called EOL
8 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
7 min read