How to import other Python files? (2024)

How to import other Python files? (1)

  • Trending Categories
  • Data Structure
  • Networking
  • RDBMS
  • Operating System
  • Java
  • MS Excel
  • iOS
  • HTML
  • CSS
  • Android
  • Python
  • C Programming
  • C++
  • C#
  • MongoDB
  • MySQL
  • Javascript
  • PHP
  • Physics
  • Chemistry
  • Biology
  • Mathematics
  • English
  • Economics
  • Psychology
  • Social Studies
  • Fashion Studies
  • Legal Studies
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

PythonServer Side ProgrammingProgramming

';

The task or process of importing other files in Python allows you to use functions, classes, or variables defined in those files within your current Python script. In this article, we will explore different ways to import other Python files, including built-in modules, user-defined modules, and importing specific functions or variables. By the end of this article, you will have a solid understanding of how to import and use code from other Python files in your current projects. Along the way, we will use code examples followed by lucid explanations to help you understand the above task.

Importing a User-Defined Module

Let us say we have a file called math_operations.py that contains several math-related functions. To import this module into another Python script, you need to follow these steps

  • You create a new Python script in the same directory as math_operations.py.

  • Then you use the import keyword followed by the name of the module without the .py extension. In this case, it would be import math_operations.

  • Now, you can access the functions from the math_operations module by using the module name followed by the function name, like math_operations.subtract(6, 1).

Let us consider the code for importing the math_operations module and using its functions:

Example

In this example, we import the math_operations module and used its subtract function to compute the difference of 6 and 1.

# main.pyimport math_operationsresult = math_operations.subtract(6, 1)print(result) 

Output

5

Importing Specific Functions or Variables

Sometimes, it is required that you only need to import specific functions or variables from a module rather than importing the complete module. This strategy can help reduce memory usage and improve code readability. This is how you can import specific functions or variables from a module:

  • A new Python script is created in the same directory as the module you want to import from.

  • The 'from' keyword is used, followed by the module name, import, and the specific function or variable names you want to import.

  • Then the imported functions or variables are made use of directly without referencing the module name.

Here, let us consider an example of importing specific functions from the math_operations module:

Example

In this code, we begin by importing only the add and subtract functions from the math_operations module. We now use these functions directly without referencing the module name.

# main.pyfrom math_operations import add, subtractresult1 = add(2, 3)result2 = subtract(5, 2)print(result1) print(result2) 

Output

53

Importing a Built-in Module

You must know that Python provides a broad range of built-in modules that offer various functionalities. In order to import a built-in module, you can follow these steps −

  • You first create a new Python script in the desired directory.

  • Then you use the 'import' keyword followed by the name of the module you want to import. For instance, to import the random module, you use import random.

  • Now, you gain access to the functions and classes from the imported module by using the module name followed by the function or class name.

Here, let us see an example of importing and using the random module to generate a random number:

Example

In this code snippet, the random module was imported and the randint() function was utilized to generate a random number between 1 and 10. By making use of built-in modules, you can take advantage of existing functionalities and save time and effort in implementing common tasks.

# main.pyimport randomrandom_number = random.randint(1, 10)print(random_number) # Output: Random number between 1 and 10

Output

One possible output is the following

4

Importing with an Alias

In some other scenarios, you may wish to use an alias for a module to simplify its application or prevent naming conflicts. To import such a module with an alias, you follow these steps:

  • A new Python script is created in the desired directory.

  • The 'import' keyword is used followed by the module name and the 'as' keyword, and then the desired alias is specified.

  • Now the alias is used instead of the original module name when accessing its functions or classes.

Here is an example of how we import the math module with an alias and use its sqrt() function.

Example

In the code given here, we proceed to import the math module with the alias m. We then use the m.sqrt notation to gain access to the sqrt function and compute the square root of 49. Using aliases can help make your code more compact and readable, especially when you have to deal with long module names.

# main.pyimport math as mresult = m.sqrt(49)print(result) 

Output

7

Importing a User-defined Module

In Python, it is possible that you can create your own modules to efficiently organize and reuse your code. In order to import a user-defined module, you need to follow these steps:

  • You create a new Python script in the same folder as the module you wish to import.

  • You then use the 'import' keyword followed by the name of the module file (without mentioning the file extension). For instance, if your module file is named my_module.py, you only use import my_module.

  • Now, you access the functions, classes, or variables defined in the imported module by making use of the module name along with the function, class, or variable name.

This is how we use the example of importing a user-defined module called my_module.py and use a function defined within it.

Example

In this code, here, we begin by importing the my_module module and use the add_numbers function to add two numbers. The add_numbers function has been defined within the my_module.py file. By the process of creating and importing your own modules, you help organize your code into smaller blocks and promote code reusability.

# main.pyimport my_moduleresult = my_module.add_numbers(10, 20)print(result)

Output

30

In this article, by now, you have seen that we explored different methods to import other Python files, and similar tasks like importing user-defined modules and importing specific functions or variables. By leveraging these techniques, you can definitely enhance the modularity and reusability of your Python code. It must be remembered, however, that the appropriate and proper import statement is used based on your specific needs and project requirements. Armed with this knowledge, you are well-equipped to incorporate external Python files into your projects and fully exploit their functionality to build more robust and efficient applications.

In this article, we also explored additional methods for importing Python files, like importing built-in modules and importing with aliases. By deploying these techniques, you can effectively integrate built-in modules into your code and simplify the import statements with aliases. Making efficient use of built-in modules and utilizing aliases can increase the functionality and readability of your Python projects, permitting you to write efficient and maintainable code.

Rajendra Dharmkar

Updated on: 31-May-2024

83K+ Views

  • Related Articles
  • How to Import Multiple Text Files to Multiple Sheets in Excel?
  • Import Files and Images in ReactJS
  • How to import Matplotlib in Python?
  • How to Import Multiple Text Files from a Folder into One Worksheet?
  • How To Import Text Files To Excel As Separate Sheets With Original Names In Excel?
  • How to convert PDF files to Excel files using Python?
  • How to use multiple modules with Python import Statement?
  • How to install and import Python modules at runtime?
  • How to import everything from a python namespace / package?
  • How to compare files in Python
  • How I can dynamically import Python module?
  • Lazy import in Python
  • How to import a single function from a Python module?
  • How to import a Python module given the full path?
  • How we can import Python modules in Jython?
Kickstart Your Career

Get certified by completing the course

Get Started

How to import other Python files? (31)

Advertisem*nts

';

How to import other Python files? (2024)
Top Articles
15 Money making apps that generate passive income. - The Wise Half
The Complete Guide to Making Money with Affiliate Marketing
Boggle Brain Busters Bonus Answers
Computer Repair Tryon North Carolina
Atrium Shift Select
Xm Tennis Channel
Belle Delphine Boobs
735 Reeds Avenue 737 & 739 Reeds Ave., Red Bluff, CA 96080 - MLS# 20240686 | CENTURY 21
Foodland Weekly Ad Waxahachie Tx
Velocity. The Revolutionary Way to Measure in Scrum
The Menu Showtimes Near Regal Edwards Ontario Mountain Village
Labby Memorial Funeral Homes Leesville Obituaries
Account Suspended
Epguides Strange New Worlds
2024 INFINITI Q50 Specs, Trims, Dimensions & Prices
Lakers Game Summary
Keci News
Project Reeducation Gamcore
Reser Funeral Home Obituaries
Kentuky Fried Chicken Near Me
Craigslist List Albuquerque: Your Ultimate Guide to Buying, Selling, and Finding Everything - First Republic Craigslist
Random Bibleizer
Garden Grove Classlink
Temu Seat Covers
Taylored Services Hardeeville Sc
Purdue Timeforge
Ofw Pinoy Channel Su
Storelink Afs
Kaiserhrconnect
Sf Bay Area Craigslist Com
Play 1v1 LOL 66 EZ → UNBLOCKED on 66games.io
Old Peterbilt For Sale Craigslist
Hair Love Salon Bradley Beach
Autozone Locations Near Me
Radical Red Doc
Restored Republic December 9 2022
Studio 22 Nashville Review
Tokyo Spa Memphis Reviews
Bianca Belair: Age, Husband, Height & More To Know
Top 25 E-Commerce Companies Using FedEx
Second Chance Apartments, 2nd Chance Apartments Locators for Bad Credit
Elven Steel Ore Sun Haven
Ucla Basketball Bruinzone
Large Pawn Shops Near Me
A rough Sunday for some of the NFL's best teams in 2023 led to the three biggest upsets: Analysis
Rocket League Tracker: A useful tool for every player
Www Pig11 Net
Haunted Mansion Showtimes Near Millstone 14
What Time Do Papa John's Pizza Close
Image Mate Orange County
786 Area Code -Get a Local Phone Number For Miami, Florida
Laurel Hubbard’s Olympic dream dies under the world’s gaze
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6612

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.