How to Import Other Python Files?
Last Updated :
19 Mar, 2024
We have a task of how to import other Python Files. In this article, we will see how to import other Python Files. Python's modular and reusable nature is one of its strengths, allowing developers to organize their code into separate files and modules. Importing files in Python enables you to reuse code, maintain a clean codebase, and enhance collaboration among team members. In this guide, we'll explore how to import other Python files with three practical code examples.
How to Import Other Python Files?
Below are some examples of how to import other Python Files in Python:
Example 1: Basic Import
The most straightforward way to import a Python file is by using the import
statement. Consider the following example, where we have two files: main.py
and module.py
.
module.py: In the below code, a greet function that prints a personalized greeting. If executed independently, it also prints a message indicating that it is the module.py file.
Python3
# module.py
def greet(name):
print(f"Hello, {name}!")
if __name__ == "__main__":
print("This is the module.py file.")
main.py: In main.py, the module file is imported, and the greet function from module.py is called within the main function, greeting "Alice" when the script is executed.
Python3
# main.py
import module
def main():
module.greet("Alice")
if __name__ == "__main__":
main()
Output
Hello, Alice!
Example 2: Importing Specific Functions
Sometimes, you may only need specific functions or variables from a module rather than importing the entire module. You can achieve this using the from ... import ...
syntax. Let's modify the previous example to demonstrate this.
module.py: In module.py, the file defines a welcome function printing a personalized welcome message. When executed independently, it also outputs a statement indicating that it is a different version of the module.py file.
Python3
# module.py
def welcome(name):
print(f"Welcome, {name}!")
if __name__ == "__main__":
print("This is a different version of the module.py file.")
main.py : In main.py, the module file is imported with the alias mod, and the welcome function from module.py is invoked, welcoming "Charlie" when the script is executed. The use of an alias (mod) provides a shorter reference to the imported module.
Python3
# main.py
import module as mod
def main():
mod.welcome("Charlie")
if __name__ == "__main__":
main()
Output
Welcome, Charlie!
Example 3: Imports Alias
In some cases, you might want to rename a module or function for clarity or to avoid naming conflicts. The as
keyword allows you to create an alias for the imported module or function. Let's illustrate this with an example:
module.py: In the below code, a greet function that prints a personalized greeting. If executed independently, it also prints a message indicating that it is the module.py file.
Python3
# module.py
def greet(name):
print(f"Hello, {name}!")
if __name__ == "__main__":
print("This is the module.py file.")
main.py:
In main.py, the module file is imported with the alias mod, and the greet function (assuming it's present in the module) is called, greeting "Charlie" when the script is executed. The use of an alias (mod) provides a shorter reference to the imported module.
Python3
# main.py
import module as mod
def main():
mod.greet("Charlie")
if __name__ == "__main__":
main()
Output
Hello, Charlie
Similar Reads
How to Fix ImportError: Cannot Import name X in Python
We are given an error "Importerror: Cannot Import Name âXâ From âCollectionsâ " in Python and our task is to find the solution for this error. In this article we will see the reasons for occurring and also the solution for the Importerror: Cannot Import Name âXâ From âCollectionsâ " error in Python.
3 min read
How to Load a File into the Python Console
Loading files into the Python console is a fundamental skill for any Python programmer, enabling the manipulation and analysis of diverse data formats. In this article, we'll explore how to load four common file typesâtext, JSON, CSV, and HTMLâinto the Python console. Whether you're dealing with raw
4 min read
What is __Init__.Py File in Python?
One of the features of Python is that it allows users to organize their code into modules and packages, which are collections of modules. The __init__.py file is a Python file that is executed when a package is imported. In this article, we will see what is __init__.py file in Python and how it is u
5 min read
How To Create And Use .env Files In Python
In Python, a .env file is commonly used to store configuration settings, API keys, and other sensitive information. It is a plain text file with key-value pairs, and the python-dotenv library is often used to load these variables into the environment. In this article, we will explore the detailed pr
3 min read
How Can I Make One Python File Run Another File?
In Python programming, there often arises the need to execute one Python file from within another. This could be for modularity, reusability, or simply for the sake of organization. In this article, we will explore different approaches to achieve this task, each with its advantages and use cases. Ma
2 min read
How to Call the main() Function of an Imported Module in Python
We are given an imported module and our task is to call the main() function of that module after importing it in Python. In this article, we will see how to call the main() of an imported module in Python. Call the main() Function of an Imported Module in PythonBelow, are the code methods of how to
3 min read
Install Poetry to Manage Python Dependencies
Poetry is a modern and user-friendly dependency management tool for Python. It simplifies the process of managing project dependencies, packaging, and publishing. In this article, we will see how to install poetry in Python in Windows. What is Python Poetry?Python Poetry is a modern and comprehensiv
2 min read
Importerror: "Unknown Location" in Python
Encountering the ImportError: "Unknown location" in Python is a situation where the interpreter is unable to locate the module or package you are trying to import. This article addresses the causes behind this error, provides examples of its occurrence, and offers effective solutions to resolve it.
3 min read
Pipx : Python CLI package tool
In this article, we will explore the basics of pipx python CLI package tool. Pipx is a tool in Python that allows us to run python packages that have a CLI interface in the global context of your system. It uses its own environment for managing the packages. Here, we will cover its installations, se
4 min read
How to run Python code on Google Colaboratory
Prerequisite: How to use Google Colab Google provides Jupyter Notebook like interface to run Python code on online Virtual Machines. In this article, we will see how to run simple Python code on Google Colab. Step #1: Open https://colab.research.google.com/ Step #2: Select New Python3 Notebook Step
2 min read