How to Create Your Own Python Modules
In Python, it is possible to create and use custom modules.
In this lesson, we will learn how to create and utilize your own modules.
Creating a Module File
First, you need to create a file that will serve as your module.
For example, let's create a circle.py file that contains a function to calculate the area of a circle and a function to calculate the circumference of a circle.
# Import math module to use the value of pi import math # Function to calculate the area of a circle def get_circle_area(radius): return math.pi * radius ** 2 # Function to calculate the circumference of a circle def get_circle_circumference(radius): return 2 * math.pi * radius
In the circle.py file above, we imported the math module to calculate the area of a circle with the get_circle_area function, and defined the get_circle_circumference function to calculate the circumference of a circle.
Importing the Module
Now, you can use the import keyword to load the circle.py file into another Python file.
# Import the circle.py module located in the same directory import circle # Store the area of a circle with radius 5 in the variable area area = circle.get_circle_area(5) # Store the circumference of a circle with radius 5 in the variable circumference circumference = circle.get_circle_circumference(5) # Print the area of the circle: 78.54 print(area) # Print the circumference of the circle: 31.42 print(circumference)
When using import circle, the module needs to be in the same directory as the Python script that is calling it.
If your module file is located in a subdirectory called modules, you can import it by specifying the relative path, such as import modules.circle.
If the module file is located in a parent directory, you will need to use the sys module to add the module's path.
import sys # Add the modules directory from the parent directory to the system path sys.path.append("../modules") # Import the circle.py module from the modules directory import circle
Lessons in this chapter ยท Concepts of Functions, Modules, and Packages
- 1. Code Blocks Performing Specific Tasks, Functions
- 2. Components of a Function
- 3. What Does It Mean to Call a Function?
- 4. Keyword Arguments and Variable Scope
- 5. Simplifying Functions with Lambda Functions
- 6. Fill-in-the-blank quiz
- 7. Introduction to Files and Basic Input/Output
- 8. How to Read File Contents
- 9. How to Write Data to a File
- 10. Exception Handling for Writing Safe Code
- 11. Enhancing Code Reusability and Efficiency with Modules
- 12. How to Create Your Own Python Modules
- 13. What Are Packages and How to Use Them?
- 14. Multiple-choice quiz
- 15. Coding Quiz - Sum of Even Numbers
What is the keyword used to import modules?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help