Modules in Python
Modules in Python
Importing a module creates a new variable with that name. And that name refers to an
object whose type id module:
type(math)
<class ‘module’>
The built in function help can be used to see what the module contains.
help(math)
• In Python, we may import functions from one module into our program.
• For this, we make use of the import keyword. In the Python window, we
add the next to import keyword, the name of the module we need to
import.
• Example : import example_module
• The functions that we defined in the example_module are not
immediately imported into the present program. Only the name of the
module, i.e., example_ module, is imported here.
• We may use the dot operator to use the functions using the
module name. For instance:
• There are several standard modules for Python. The complete list
of Python standard modules is available. The list can be seen
using the help command.
• Similar to how we imported our module, a user-defined module,
we can use an import statement to import other standard
modules.
• Importing a module can be done in a variety of ways. Below is a
list of them.
Python import Statement
• Using the import Python keyword and the dot operator, we may
import a standard module and can access the defined functions
within it. Here's an illustration.
Importing and also Renaming
• While importing a module, we can change its name too. Here is an example to show.
• The module is initially looked for in the current working directory. Python
then explores every directory in the shell parameter PYTHONPATH if the
module cannot be located in the current directory. A list of folders
makes up the environment variable known as PYTHONPATH. Python
examines the installation-dependent set of folders set up when Python
is downloaded if that also fails.
The dir() Built-in Function
• We may use the dir() method to identify names declared within a
module.
• For instance, we have the following names in the standard
module str. To print the names, we will use the dir() method in
the following way:
Code
# Python program to print the directory of a module
print( "List of functions:\n ", dir( str ), end=", " )
Output: Displays list of functions wrt str
Create a Module:
A module is a file containing Python code, definitions of functions,
statements, or classes.
An example_module.py file is a module we will create and whose name is
example_module.
We employ modules to divide complicated programs into smaller, more understandable
pieces.
Modules also allow for the reuse of code.
To create a module just save the code you want in a file with the file extension .py:
• To import the created module, we make use of import keyword
followed by name of the module which we want to import.
import example_module