Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Install Python Modules without Root Access
Next article icon

How to Import Local Modules with Python

Last Updated : 28 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, modules are self-contained files with reusable code units like functions, classes, and variables. Importing local modules allows for organizing the codebase effectively, enhance maintainability, and enhances code reuse. In this article, we will understand how to import local modules with Python.

Understanding Modules and Packages

  • Python Modules: Think of them as individual Python files (e.g., mymodule.py) containing code to reuse.
  • Python Packages: These are directories (with an __init__.py file) that group related modules together, creating a hierarchical structure.

Basic Import Techniques:

Using the import Statement

The import syntax imports an entire module.

import module_name

Or, to import a specific attribute or function from a module:

from module_name import attribute_name

Setting Up the Environment

Directory Structure for Local Modules

Create a clear project structure with dedicated folders for modules and packages. A well-organized project might look like this:

my_project/
├── modules/
│ ├── module1.py
│ └── module2.py
└── main.py

The __init__.py file in the modules directory makes it a package, allowing us to import modules using dot notation.

Creating Sample Modules

Craft Python files (e.g., module1.py, module2.py) containing the code to reuse.

Importing Modules in the Same Directory

If main.py and module1.py are in the same directory:

Python
# In main.py import module1  module1.my_function()  # Call a function from module1 

Importing Modules from a Subdirectory

Using __init__.py Files

The __init__.py file in a package signals to Python that the directory should be treated as a package, enabling imports from its subdirectories.promotes

from modules import module2

module2.my_class() # Instantiate a class from module2

Adjustments might be needed for relative imports if running our script as the main program versus importing it as a module.

Example:

Suppose the project structure looks like this:

my_project/
├── modules/
│ ├── core/
│ │ ├── utils.py
│ │ └── helpers.py
│ └── extensions/
│ ├── data_processing.py
│ └── visualizations.py
└── main.py

1. Importing an Entire Module:

Python
from modules.core import utils  # Use a function from utils.py result = utils.calculate_sum(10, 20) print(result) 

2. Importing a Specific Function:

Python
from modules.extensions.data_processing import preprocess_data  # Directly use the imported function processed_data = preprocess_data(raw_data) 

3. Importing Multiple Items:

Python
from modules.core.utils import calculate_sum, another_function from modules.extensions.visualizations import create_chart  # Use the imported functions result1 = calculate_sum(5, 8) result2 = another_function(result1) create_chart(processed_data) 

4. Using as to Rename:

Python
from modules.extensions.visualizations import create_chart as plot_chart  # Use the renamed function plot_chart(processed_data) 

Handling Circular Imports

Circular imports occur when two modules depend on each other, leading to errors. Refactor the code to break these dependencies or use local imports within functions to avoid issues.

Modifying the Python Path

Using sys.path to Add Directories: The sys.path list determines where Python searches for modules. You can append custom paths using sys.path.append().

Python
import sys sys.path.append("/path/to/custom/modules")  import custom_module  # Now importable 

Using Relative Imports: Relative imports use dot notation (e.g., ., ..) to specify the location of a module relative to the current module.

from . import module1  # Import from the current package
from ..modules import module2 # Import from the parent package

Example:

Python
# In modules/core/utils.py from . import helpers  # Import from the current package (core) from ..extensions import visualizations  # Import from the parent package (modules) 

Relative imports are concise but can be sensitive to the current working directory.

Common Import Errors and Troubleshooting:

  • ModuleNotFoundError: Check file paths, names, and typos.
  • ImportError: Verify module contents and circular import issues.

Use clear and consistent naming conventions.

Best Practices

  • Structure project logically.
  • Use meaningful module and function names.
  • Employ clear and consistent import statements.
  • Consider using tools like virtual environments for dependency management.

Conclusion

In conclusion, mastering local module imports is essential for writing well-organized and maintainable Python code. By organizing code into reusable modules and packages, we create a well-structured, maintainable, and scalable codebase.


Next Article
Install Python Modules without Root Access
author
susobhanakhuli19
Improve
Article Tags :
  • Python
  • python-modules
Practice Tags :
  • python

Similar Reads

  • How to Install a Python Module?
    A module is simply a file containing Python code. Functions, groups, and variables can all be described in a module. Runnable code can also be used in a module. What is a Python Module?A module can be imported by multiple programs for their application, hence a single code can be used by multiple pr
    4 min read
  • Where Does Python Look for Modules?
    Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module in that file and then we can use them. Modules can exist in various directories. In this article, we will discuss where do
    3 min read
  • Import module in Python
    In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Python’s import st
    3 min read
  • How to Install Python Six Module on Windows?
    The Six Library in python is used to wrap differences between Python 2 and Python 3 for systems that operate both on Python 2 and python 3. In this, article, we will look into the process of installing Python Six Library on Windows. Pre-requisites: The only thing that you need for installing the Scr
    2 min read
  • Install Python Modules without Root Access
    Python is a popular programming language that gives users access to numerous modules. However, for the usage of those modules, the user needs to install those modules. The most common way of installing the Python modules is using the root access. While the most common way is using the root access, t
    3 min read
  • How to import a module in Typescript ?
    Before starting with importing modules, first of all, we need to know the basics of modules in TypeScript. We know that JavaScript has come with the concept of modules from the ES6 version in 2015 and by 2020 had broad support in most web browsers and JavaScript runtimes. TypeScript also shares the
    5 min read
  • How to locate a particular module in Python?
    In this article, we will see how to locate a particular module in Python. Locating a module means finding the directory from which the module is imported. When we import a module the Python interpreter searches for the module in the following manner: First, it searches for the module in the current
    3 min read
  • How to Install Python py-asn module on Windows?
    Py-asn is a Python module that is said to be an extension module. It provides\Enables a fast IP address to Autonomous System Numbers Lookups. It can perform both Current state and Historical state lookups with help from its contained packages. Input can be given as MRT/RIB BGP archive. The module is
    2 min read
  • How to install Python on Windows?
    Python is a high-level programming language that has become increasingly popular due to its simplicity, versatility, and extensive range of applications. The process of How to install Python in Windows, operating system is relatively easy and involves a few uncomplicated steps. This article aims to
    5 min read
  • How to import a Python module given the full path?
    The Python module is a file consisting of Python code with a set of functions, classes, and variable definitions. The module makes the code reusable and easy to understand. The program that needs to use the module should import that particular module. In this article, we will discuss how to import a
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences