Post

Modules in Python - How Using Modules Simplifies Code

Modules can be described as being a file containing a set of code or functions that are then imported to your application for use. It's like separating all the functions to be in one organised file so that you can use those function through the main base of your code. Here is what I have learnt on day 12 about what we can achieve with them.

Modules in Python - How Using Modules Simplifies Code

We’ve already practised building functions and now know the basics of writing code. Here is where it begins to get complicated. Modules aren’t just specific files that we create to place functions in. We use modules to import functions that we don’t otherwise have access to in the standard library of functions.

I’ve recently also learnt that there is a slight distinction between packages and modules as you can have built-in modules than you can import and also packages that contain different modules that you first would download and install.

Link: This is a link to the official PyPi. You can explore all the packages they have.

Let’s say we wanted to build an application for advanced mathematics; the built-in functions alone wouldn’t be enough. That’s where we would take to the python packages available online and built by python programmers around the world to help make coding easier.

To simplify, downloading and installing a package with multiple modules is known as using a python package manager, and importing and using a specific module and its feature/functions is known as importing a module.

This is information that I would have liked to be described early on in my learning journey, as I would often get the two muddled up.


Creating a Module and Using it

To recap, when we want to use a module, we import its functions.

In order to create our own module, we would create a separate file that will house all the functions, and then our main application file will use the import tag to begin helping us write code.

1
2
3
4
5
6
7
8
import math

def circle_area(radius):
    # Calculate the area of a circle using math.pi
    return math.pi * radius ** 2

# Call the function and print the result
print(circle_area(5))

In this example, we used math.pi to get the true value of pi, 3.14…, instead of hard coding it ourselves.

Now that we know how to use the built-in modules of Python, we can better understand how we can create our own.

To begin, we would first have a file and can name it anything, but for this tutorial, we can call it mymodule.py. We would then go on to write our functions inside that would take arguments as values.

1
2
3
4
# mymodule.py

def add(*nums):
  return sum(num)

Now, in our main file, main.py, we’ll import this function we have made as a module.

1
2
3
4
5
6
7
8
9
10
11
12
13
# main.py

import mymodule
import mymodule * # This ensures that all functions are important, not always necessary

print(mymodule.add(1,2,3,4,5)) #  15

# OR


from mymodule import add

print(add(1,2,3,4,5)) # 15

Tip: We can also have several functions imported by using the comma to separate each function, from mymodule import func1, func2, func3.

If we import an entire module, we call a function from it by writing the module name first, followed by a period, and then the function name with any arguments, like this: mymodule.function(args).

If we import the exact function we want by using from, then we can just refer to the function from it alone, as we did when we created functions from day 111.

Important: Ensure that both the files are in the same directory/folder.

Renaming a Module After Import

Some programmers prefer to use abbreviations or shorter terms to refer to functions within a module to help make their code more concise. We can do this by including an as clause after the function we want to import.

1
2
3
4
5
6
from math import pi as p

print(p)
# 3.14...
print(f"{p:.2f}") # We can use string formatter here
# 3.14

Python Built-In Modules

While this is relevant, it’s not vital to know by this point. It’s just a good idea to get a feel of all the modules you would have access to with a default install of Python.

NameDescriptionExample Use (Code)
OS ModuleProvides functions to interact with the operating system, such as creating directories, changing the current directory, listing contents, and removing directories.python\nimport os\nos.mkdir('my_folder') # Create a folder\nos.chdir('my_folder') # Change to that folder\nprint(os.getcwd()) # Show current folder\nos.rmdir('my_folder') # Remove the folder\n
Sys ModuleAllows you to interact with the Python runtime environment. You can read command-line arguments, exit scripts, check Python version, environment paths, and maximum integer size.python\nimport sys\nprint(sys.version) # Python version\nprint(sys.maxsize) # Largest integer\nsys.exit() # Exit the program\n
Statistics ModuleProvides functions for statistical calculations on numeric data, such as mean, median, mode, and standard deviation.python\nfrom statistics import mean, median, mode, stdev\ndata = [10, 15, 10, 20, 15]\nprint(mean(data))\nprint(median(data))\nprint(mode(data))\nprint(stdev(data))\n
Math ModuleContains many mathematical constants and functions like pi, sqrt, pow, floor, ceil, and log10.python\nimport math\nprint(math.pi) # Pi value\nprint(math.sqrt(16)) # Square root\nprint(math.pow(2, 4)) # Power function\nprint(math.floor(7.8)) # Round down\nprint(math.ceil(7.2)) # Round up\nprint(math.log10(1000)) # Logarithm base 10\n
String ModuleProvides useful constants and functions for string manipulation, such as letters, digits, and punctuation.python\nimport string\nprint(string.ascii_letters) # abc...XYZ\nprint(string.digits) # 0123456789\nprint(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\\]^_`{ | }~\n
Random ModuleUsed to generate random numbers or select random items. Includes functions like random() and randint().python\nfrom random import random, randint\nprint(random()) # Random float between 0 and 1\nprint(randint(1, 10)) # Random integer between 1 and 10\n

Update: While going through the course again I revisited a concept that is useful to use here to discover the different attributes or functions that are placed in a module that you import. If you use print(dir(module)) syntax, you are able to extract all the available functions inside it.

Summary

I have been able to go over the concept of modules that I needed a refresher on, which helped build on the existing knowledge I had on them. I now know how to create my own modules and import them into my application file for development. This helps create code that looks cleaner, professional, and well-thought-out.

Refactoring code isn’t easiest to do and can take some time to learn as we first have to, I think, get used to debugging. Whereby we learn how to rearrange code in a manner that uses the same input to get the same output, but with more efficient and effective code.

Footnote

This post is licensed under CC BY 4.0 by the author.