How to import custom module in Python (2024)

Python is a high-level programming language that supports various programming paradigms. It has a large ecosystem of libraries and third-party packages to support various functionalities. We can import modules to include external libraries and modules in our program and use their functionalities.

What is a custom module?

A custom module is a facility provided by Python to create a Python file containing reusable functions and classes that can be imported and used in different code files. It provides a more readable code interface and consequently improves maintainability.

How to import custom module in Python (1)How to import custom module in Python (2)

Import validate.py in main.py to access its functions.

Simple steps to import custom module

  1. Create a Python file for the module we need to import. Keep a relevant name and define all the required functionalities in it. For example, a validate.py file that contains validation functions.

def validate_num(num):

if len(num) == 11:

return True

def validate_pass(password):

if len(password) < 7:

return False

  1. Create a Python file for the program where the created module will be imported and used. For example, a main.py file that checks for the validity of a number and a password.

#need to import custom module here

print("Let's check for validity :\n")

number = '03001234567'

#need to add code here

paasword = 'key123'

#need to add code here

  1. Import the created module to the code file and use its functionalities according to the requirement. We can import the whole module or a single function from the module.

Import the whole custom module

The whole module is imported to the main.py file, which means that we can access all the functions and classes available inside the module and use them in our code. We can access the functions inside the module using the dot operator i.e. moduleName.functionName to specify from where the function is accessed.

Syntax

We can import the custom module by using the import keyword and specifying the module's name.

import validate

Example code

In this example, we import the validate module and use its validate_num() and validate_pass() functions to check the validities in our code.

main.py

validate.py

#import the whole custom module

import validate

print("Let's check for validity :\n")

number = '03001234567'

#access the function insdie the imported module

if validate.validate_num(number):

print('num is valid')

else:

print('num is invalid')

password = 'key123'

#access the function insdie the imported module

if validate.validate_pass(password):

print('password is valid')

else:

print('password is invalid')

Import a function from a custom module

A specific function is imported from the whole module to the main.py file, which means that we can access the specified function in our code. We can import more than one function from a single module i.e. import function1 , function2 , function3 when there is a specified need for functions.

Syntax

We can import a function from the custom module by using the from keyword to specify the destination module of the function and import keyword followed by the function's name.

from validate import validate_num

Example code

In this example, we import the validate_num() function from the validate module and use it to check the validity of numbers in our code.

main.py

validate.py

#import function from a custom module

from validate import validate_num

print("Let's check for validity :\n")

number = '03001234567'

#use the imported function

if validate_num(number):

print('number is valid')

else:

print('number is invalid')

Summary

Custom modules improve reusability and code accessibility by allowing users to store necessary functions in one place and use them according to their requirements. If the module is large and needs specified functions only, it is preferred to import functions. However, importing the whole module also works equally well.

Common query

Question

Why must we access a function using the dot operator if the whole module is already imported?

Show Answer

Copyright ©2024 Educative, Inc. All rights reserved

How to import custom module in Python (2024)
Top Articles
Measles vaccination recommendations | Department of Public Health & Environment
Wise Vs Revolut
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
Things To Do In Atlanta Tomorrow Night
Non Sequitur
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Cvs Sport Physicals
Mercedes W204 Belt Diagram
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Reed Wilderman

Last Updated:

Views: 6214

Rating: 4.1 / 5 (52 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.