11. Modules

In this lesson you will learn how to create and use modules. You will also learn how to use other modules made by other people.

Making Your own Modules

To create your own module just write python code in a separate file. To then use your module, open another python file and type import followed by the name of the file your module is in. From here you can call functions defined in the module by using the module’s name followed by a dot and the function. You can also use variables from the module by again using the module’s name followed by a dot and the variable name. Below is an example of using a simple module that imports an adding function and a variable:

# fun.py
big_num = 999999999
def add(num1, num2):
    print(str(num1) + " + " + str(num2) + " = " + str(num1+num2))
# main.py
import fun

fun.add(1, 1)

print(fun.big_num)

Note how the code under the # fun.py and # main.py are in separate files named fun.py and main.py respectively. In each of the examples, the main.py file is the one running.

If you want to rename a module when you import it so you don’t have to type the module’s name dot something use "import module_file as name". Below is an example:

# fun.py
def add(num1, num2):
    print(str(num1) + " + " + str(num2) + " = " + str(num1+num2))
# main.py
import fun as a

a.add(2, 2}

If you want to import some functions from a module but not all the functions use "from module_file import function(s)". If you are importing multiple functions from a module, separate the function names by a comma. Then in the file, you are importing the module, you do not need to say the module’s name dot function name, you can directly call the function. Below is an example of importing one and two functions from a module:

# fun.py
def add(num1, num2):
    print(str(num1) + " + " + str(num2) + " = " + str(num1+num2))

def subtract(num1, num2):
    print(str(num1) + " - " + str(num2) + " = " + str(num1-num2))

def multiply(num1, num2):
    print(str(num1) + " * " + str(num2) + " = " + str(num1*num2))
# main1.py
from fun import add, subtract

add(100, 1)
subtract(10, 5)
# main2.py
from fun import subtract

add(5, 10)

Built-in Modules

In addition to creating your own modules, Python has many modules that are built into Python and can be imported like previously stated. Simply use the keyword import followed by the name of the module. The same ways to import your own modules apply to importing all modules. Below are several popular built-in modules but a list of built-in python modules can be found here.

Math

The built-in math module in python has a lot of useful mathematical functions. Some of these include, sin, cos, pi, sqrt, log, and more. The full list can be found here. Below are some examples:

import math

print(math.sin(math.pi/2)) # 1.0
print(math.cos(0))         # 1.0
print(math.pi)             # 3.141592653589793
print(math.sqrt(64))       # 8.0
print(math.log(100, 10))   # 2.0

Random

The built-in random module in python has a lot of useful functions that revolve around randomness. Some of these include, choice, randint, randrange and more. The full list can be found here. Below are some examples:

import random

print(random.random())           # prints a random float from -1 to 1
print(random.randint(-10, 10))   # prints a random integer from -10 to 10
print(random.choice(["Hello", "Good morning", "Good afternoon"])) # prints a random index in the list

JSON

The built-in JSON module in python has a lot of useful functions that work with JSON. Some of these include, dumps, loads, and more. The full list can be found here. Below are some examples:

import json

json_data = '{ "number":10, "string":"hello", "list":[1, 2, 3] }'

python_data = json.loads(json_data) # converts JSON to python

print(python_data)            # {'number': 10, 'string': 'hello', 'list': [1, 2, 3]}
print(python_data["number"])  # 10
print(python_data["string"])  # hello
print(python_data["list"][0]) # 1


python_data = { "number": 3, "string": "goodbye", "list": [3, 2, 1] }

json_data = json.dumps(python_data) # converts python to JSON

print(json_data) # {"number": 3, "string": "goodbye", "list": [3, 2, 1]}

Datetime

The built-in datetime module in python has a lot of useful functions that are about time. Some of these include, datetime, datetime.now, strftime, and more. The full list can be found here. Below are some examples:

import datetime

date = datetime.datetime.now()

print(date)                # prints the current date
print(date.day)            # prints the current year
print(date.strftime("%c")) # prints the date in a readable string: day, month, day, time, year

Using Other People's Modules

In addition to all the built-in modules Python has pre installed you can also use other modules that people have created. This opens the door to hundreds of thousands of modules or packages for you to install. But before we install modules from other users, it is good practice to set up a virtual environment.

Virtual Environment

A virtual environment is a self-contained directory tree that contains a installation of Python and additional packages. Virtual environments solve the issue of one application requiring a version different version of a module than another application. To get around this you can install each version of that module on its own self-contained virtual environment. To create a virtual environment run the follow command below in the terminal of the directory of your project:

pip install virtualenv
virtualenv venv

Then to activate the virtual environment on MacOS run:

$ source venv/bin/activate

Or run this if on windows in order to activate the virtual environment:

C:\Users\SomeUser\project_folder> venv\Scripts\activate

Pip

Now that we have a virtual environment active we can install packages or modules created by other people. To do this we will use a tool called pip. To simplily install a module run the command "pip install [module name]" in a terminal. Now you might be wondering where you look to find modules. There are many resources but the main one is PyPI or you could always do a google search.

If you are using something like Replit as your IDE, they have their own system for installing modules. Here is more information.

❮ PreviousNext ❯