TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: How to Import Another Python File
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
HowToPython BasicPython Tutorials

How to Import Another Python File

Last updated: Jan 12, 2024 12:09 pm
By Meenakshi Agarwal
Share
7 Min Read
How to Import Another Python File
SHARE

When working on big Python projects or trying to organize your code better, you need to know how to bring in code from other Python files. This is called “importing,” and it’s a crucial skill for reusing code and keeping things neat. In this guide, we’ll explore different ways to import another Python file into your main project. Use the examples to help you understand how it all works.

Contents
1. Basic Import: Grabbing a Whole Module2. Import Another Python File with Alias: Making Names Shorter3. Import Specific Functions: Only What You NeedMultiple Function Import: Bringing in a Bunch4. Import Everything (Not Recommended): A Quick Mention5. Relative Imports: Keeping Things CloseParent Directory Import: Climbing Up6. Importing Classes: Object-Oriented GoodnessImporting Multiple Classes: Mix and Match7. Importing Modules from Different Directories: Branching OutUsing Pathlib for Cross-Platform Compatibility: Path Magic

Python: Import Code from Another Python File

When you decide or already have multiple Python files in your project, it is important to know how to import another Python file into the main project. In Python, it can be done in many ways. Go through these methods and choose the best suited to your needs.

1. Basic Import: Grabbing a Whole Module

Let’s start with the basics. When you import a Python file, you’re bringing in a whole module. Say you have a file named mod.py with a simple function:

# mod.py
def hello(name):
    print(f"Hello, {name}!")

Now, in another file, like main.py, you can import and use that function:

# main.py
import mod

mod.hello("John")

Here, we’re importing another Python file (mod.py) and using the hello function from it.

2. Import Another Python File with Alias: Making Names Shorter

Sometimes, module names can be long or might clash with other names in your code. To fix this, you can give the module a shorter name, known as an alias:

# main.py
import mod as m

m.hello("Alice")

This way, we can call other files using an alias (m) to make our code cleaner.

3. Import Specific Functions: Only What You Need

If you only want a specific part of a Python file, you can import just that. Let’s say you have a file called math.py:

# math.py
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

In your main.py, you can import just the functions you need:

# main.py
from math import add

result = add(5, 3)

Now, we ‘ll include the above file but only the add function this time.

Multiple Function Import: Bringing in a Bunch

You can import multiple functions at once, like so:

# main.py
from math import add, subtract

result_add = add(5, 3)
result_subtract = subtract(8, 2)

Here, we’re importing another Python file (math.py) and using both the add and subtract functions.

4. Import Everything (Not Recommended): A Quick Mention

You can technically import everything from a file, but it’s generally not a good idea:

# main.py
from math import *

result_add = add(5, 3)

While this does the job, it’s not recommended because it can make your code messy and lead to problems.

5. Relative Imports: Keeping Things Close

When your Python files are in the same project, you can use relative imports. Consider a project structure like this:

project/
|-- main.py
|-- utils/
|   |-- helpers.py

In your main.py, you can use a relative import:

# main.py
from utils import helpers

helpers.hello("Charlie")

This helps import another Python file within your project without making the code confusing.

Parent Directory Import: Climbing Up

You can also go up a level in your project structure:

# utils/helpers.py
from ..other_mod import some_func

This is useful when your files are organized hierarchically.

6. Importing Classes: Object-Oriented Goodness

If your file has classes, you can import and use them:

# shapes.py
# N-Gon: A shape with n number of edges is called an "n-gon."
# For example, a triangle is a 3-gon, and a pentagon is a 5-gon.
class NGon:
    def __init__(self, sides, side_len, apothem_len):
        self.n = sides
        self.s = side_len
        self.a = apothem_len

    def area(self):
        return 0.5 * n * s * a

Now, let’s include the above Python file (shapes.py) into a new file:

# main.py
from shapes import NGon

my_ngon = NGon(5)
print(f"N-Gone Area: {my_ngon.area()}")

This approach is handy when your code revolves around object-oriented programming (OOP) principles.

Importing Multiple Classes: Mix and Match

You can bring in multiple classes from a file:

# main.py
from shapes import Circle, Square

my_circle = Circle(5)
my_square = Square(4)

Here, we’re importing another Python file (shapes.py) and using both the Circle and Square classes.

7. Importing Modules from Different Directories: Branching Out

If your Python files are scattered in different directories, you can add the path dynamically:

# main.py
import sys
sys.path.append("/path/to/mod_directory")

import mod_in_another_dir

mod_in_another_dir.some_func()

This is handy when dealing with external libraries or modules not included in the Python standard library. However, always consider project structure and maintainability before resorting to this approach.

Using Pathlib for Cross-Platform Compatibility: Path Magic

Using the path lib module can make path handling more robust:

# main.py
from pathlib import Path

mod_directory = Path("/path/to/mod_directory")
sys.path.append(str(mod_directory))

import mod_in_another_dir

mod_in_another_dir.some_func()

This ensures that your code works well across different platforms.

Conclusion – Different Ways to Import Another Python File

In this guide, we’ve covered different ways of importing code from other Python files. These methods are crucial for making your code modular and easy to manage. Choose the approach that suits your project’s structure and requirements. As your projects grow, mastering the art of importing becomes key to writing clean, maintainable, and collaborative Python code.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article How to Generate Random Numbers in R How to Generate Random Numbers in R
Next Article Bash Scripting for Beginners Simple Bash Scripting Tutorial for Beginners

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x