Trusted answers to developer questions

What are Python modules?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

A Python module is a Python file containing a set of functions and variables to be used in an application. The variables can be of any type (arrays, dictionaries, objects, etc.)

Modules can be either:

1. Built in

2. User-defined.

svg viewer

1) User-defined Modules


Create a Module

To create a module, create a Python file with a .py extension.

Call a Module

Modules created with a .py extension can be used in another Python source file, using the import statement.

svg viewer

Here’s an example of a simple module, myModule.py:

#myModule.py
def myFunction( parameter ): #define a function in myModule.py
print "Course : ", parameter
return

To call this Python module myModule.py, create another Python file callModule.py file and use the import statement.

import myModule.py:
myModule.myFunction(“Python Programming”)

When the Python interpreter encounters an import statement, it imports the module if it is present in the search path.

A search path is a list of directories that the interpreter searches for importing a module.

When the above code is executed, the following output is produced:

callModule.py
myModule.py
#myModule.py
def myFunction( parameter ): #define a function in myModule.py
print ("Course : ", parameter)
return

2) Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Call a built-in Module

To call a built-in Module and use the function of that module write:

import moduleName #call a module
moduleName.function()#use module function
svg viewer
import math
print("The value of cosine is", math.cos(3))
print("The value of sine is", math.sin(3))
print("The value of tangent is", math.tan(3))
print("The value of pi is", math.pi)

Benefits of modules in Python

There are a couple of key benefits of creating and using a module in Python:

Structured Code

  • Code is logically organized by being grouped into one Python file which makes development easier and less error-prone.
  • Code is easier to understand and use.

Reusability

Functionality defined in a single module can be easily reused by other parts of the application. This eliminates the need to recreate duplicate code.

RELATED TAGS

python
python modules
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?