• Latest
  • Trending
How to Create, Import, and Reuse Your Own Module in Python

How to Create, Import, and Reuse Your Own Module in Python

March 21, 2022
Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023
Data Leak Hits Thousands of NHS Workers

Data Leak Hits Thousands of NHS Workers

February 20, 2023
EU Cybersecurity Agency Warns Against Chinese APTs

EU Cybersecurity Agency Warns Against Chinese APTs

February 20, 2023
How Your Storage System Will Still Be Viable in 5 Years’ Time?

How Your Storage System Will Still Be Viable in 5 Years’ Time?

February 20, 2023
The Broken Promises From Cybersecurity Vendors

Cloud Infrastructure Used By WIP26 For Espionage Attacks on Telcos

February 20, 2023
Instagram and Facebook to get paid-for verification

Instagram and Facebook to get paid-for verification

February 20, 2023
YouTube CEO Susan Wojcicki steps down after nine years

YouTube CEO Susan Wojcicki steps down after nine years

February 20, 2023
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Friday, 17 July, 2026
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

How to Create, Import, and Reuse Your Own Module in Python

We explain an important fundamental of code reusability in Python: modules.

by ITECHNEWS
March 21, 2022
in Data Science, Leading Stories
0 0
0
How to Create, Import, and Reuse Your Own Module in Python

Whether you’re an expert or beginner at Python programming, you must be familiar with the import modules command. However, as a newcomer, you might not have an idea where those modules come from.

Let’s take a deeper look to understand the origin of those modules, along with how to create and import them for reuse.

YOU MAY ALSO LIKE

French Telco Orange Hit by Cyber-Attack

ATC Ghana supports Girls-In-ICT Program

What Is Code Reusability and Why Should You Do It?

One of the best practices when working with most server-side languages is to modularize your code so that it’s reusable. Because Python is object-oriented, it’s one of those languages that makes code reusability possible.

Code modularization involves writing codes that carry out different instructions in blocks. It’s used to separate tasks from each other.

When you modularize a code, you give it a unique name. That name is its identity and means the next time you need to use that block of code, you only need to call out its name and not the whole code.

This practice makes your job a lot easier and faster during a real-life project. Code modularization also improves execution speed and makes testing easier. In essence, it makes your code more efficient and readable.

While our example here is not based on object-oriented programming (OOP), we must discuss it briefly before moving on to creating a module.

The code you intend to reuse sometimes can stand alone as individual functions. But it can also be in the form of methods in a class. That’s when the concept of OOP comes into play.

Object-Oriented Programming in Python

OOP is the presentation of codes as independent objects in the form of a class. Each object then has its attributes and methods.

Those attributes are the characteristics of the class, while each method defines the behavior of the attributes.

Instead of writing long code that’s less efficient—a convention in procedural programming—your code become more efficient and specific in OOP. The reason is that functions and data are stored in independent classes in OOP, as opposed to the separation of both in procedural programming.

Each class that you create then takes up an identity. So when you need a named module from a class, you call it with reference to that class.

Making Reusable Functions: A Practical Example

Moving on, let’s have a look at how we can reuse the function for a word counter in another Python file. This guide will only focus on creating reusable functions that are not inside an object.

First off, open up a command prompt to any location on your computer to start a new project. In this case, we’ll use a project name of word_count. To do that, type mkdir word_count.

Next, use your preferred virtual environment tool to create a new virtual environment. If you’ve created one already, simply activate it. Make sure that you’re still in your project’s directory.

Creating project directory and making virtual environment

As a good practice, to create the word counter function, we first try to figure out a raw formula for calculating it. Generally, you can find a word count by adding one to the number of spaces in a sentence. Note that while you might not have need for a word count, it’s how the idea relates to code reusability that matters for this explanation.

Next, open up a text editor to your project location and create a new Python file. In this case, the file is named as wordcounter.py; ensure that you use the correct .py extension.

Here’s what the wordcounter file looks like:

# create a variable called word that holds some strings
word = ['how to make a word counter in python']
# Next, loop through the variable to count the words in the created variable
NumberOfWords = [EachWord.count(' ') + 1 for EachWord in word]
print(NumberOfWords)
output: [8]

Now that the raw code is working, we then modularize it by creating a function that makes the code reusable:

def CountWords(words):
	if words is not None:
		NumberOfWords = [Eachword.count(' ') + 1 for Eachword in words]
		return NumberOfWords
mywords = ['making a word counter in python']
print(CountWords(mywords))
output: [6]

That’s it; we’re created a word counter module. Let’s see how to reuse it.

Importing the Created Module

Remember that you earlier created a file named wordcounter.py. That file holds a function called CountWords. If you need that function in a new file and don’t want to rewrite the whole code or function, all you need to do is import that function as a module in your new file.

Note that all your Python files must be in the same directory, in this case. To make sure this is the case, just create a new Python file in the same directory where you have the wordcounter.py file.

Here’s what the new file looks like:

from wordcounter import CountWords
words = ["how to import and reuse your code in Python"]
CountWords(words)
output: [9]

In the snippet above, CountWords is the function inside the wordcounter.py file. To reuse that function in a new Python file, we import it from its parent file (wordcounter.py).

Importing Your Created Module Absolutely

What if the new file isn’t in the same directory as the module file? In these cases, you must reference the module by using an absolute import.

To understand this a bit further, let’s assume that you’ve created a new file within your project’s directory. But the file that you intend to import your function from (which is wordcounter, in this case), is in another folder within your project’s directory—let’s call that folder subword_count.

To import your module from wordcounter (which is now inside the subword_count folder) into a new Python file, you need to call it absolutely. To see how this works, create a new file in your project’s directory, give it your preferred name, and import your module as written in the code snippet below:

from subword_count.wordcounter import CountWords
words = ["how to import and reuse your code in Python for files in different folders."]
CountWords(words)
output: [14]

During an absolute import, Python browses through the parent folder (subword_count in this case) and locates the file or module containing the function of interest (CountWords).

File structure to further explain the absolute import

To break down the meaning of the absolute import above, subword_count is a folder in your project’s directory that holds the wordcounter.py file. That file then contains the CountWordsfunction.

Where Does Code Reusability Work?

Modularizing and reusing your code is a best practice for any project you’re running. If you write OOP, which you’re likely to do often, you can import a class from a module or call a function from a class. If the class is in a folder, import it absolutely into your new file.

The same practice applies to functions that aren’t in an object. Depending on your project’s layout, you can import them explicitly or absolutely, as we’ve done above.

Source: IDOWU OMISOLA
Via: makeuseof
Tags: Your Own Module in Python
ShareTweet

Get real time update about this post categories directly on your device, subscribe now.

Unsubscribe

Search

No Result
View All Result

Recent News

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025

Recent News

  • Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa July 29, 2025
  • French Telco Orange Hit by Cyber-Attack July 29, 2025
  • ATC Ghana supports Girls-In-ICT Program April 25, 2023
  • Vice President Dr. Bawumia inaugurates ICT Hub April 2, 2023
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
Go to mobile version