1ALG
ALGORITHMS WITH
PYTHON
Chapter 7: Working with modules
Summary
- What are modules.
- Why use modules.
- Creating our own modules.
- Adding external modules.
- Using virtual environments.
Extending our
code with modules
3
Current context
We know how to use functions and do complex things with them.
How can we reuse code in different projects ?
How can we use functions that someone else has already written ?
4
Python modules
Python files which contains useful functions, classes, variables, …
Can be used to avoid reinventing the wheel.
Promotes reusability and makes code easier to maintain.
5
Included in your distribution
Built-ins Cover your basics needs
modules
Part of the standard library
6
Using modules
- To use a module, you need to import it.
- There are many ways to use imports.
- We will see these two statements :
- import <module_name>
- from <module_name> import <content>
7
Different ways to import
Consider that we have a module called demo that contains many functions and
constants.
example explication
import demo Imports demo, use demo.content to use of its content.
import demo as my_demo Import tools as my_demo, use my_demo.content.
from demo import * Import everything from demo in the current context.
from demo import a, b, c Only imports a, b and c from demo.
from demo import a as a_demo Imports a from the module demo as a_demo.
8
import <module>
import math # import the math module
# using import <module> we can access its content using
# <module>.<function_name> like math.<content>
x = 9
# compute the squared root of x
root = math.sqrt(x)
# compute the factorial of x
fact = math.factorial(x)
9
from <module> import <content>
# we only import the functions that we need
from math import sqrt, factorial
from sys import platform as current_os
x = 9
# compute the squared root of x
root = sqrt(x) # function was imported from math
# compute the factorial of x
fact = factorial(x) # function was imported from math
print(f"{x=} {root=} {fact=}")
print(f"This machine is running on {current_os}")
10
Modules examples – mixed imports
import os
from math import sqrt, factorial
from sys import platform as current_os
n = 9
n_sqrt = sqrt(n)
n_fact = factorial(n)
print(f"Current working directory = {os.getcwd()}")
print(f"This machine is running on {current_os}.")
11
Built-in modules
- There are a lot of built-ins modules.
- If there's a task you want to accomplish in Python, chances are there's already a module
available to help you get it done.
- Do not hesitate to search on the internet for a module that matches your needs.
- Curious about modules ? Try this in the REPL : import antigravity
12
Built-ins modules : os
- Used to interact with the OS :
- File and directory manipulation
- Managing environment variables
- Operating System Information
- Process Management
- …
- Python doc : https://docs.python.org/3/library/os.html
13
Built-ins modules : os - example
import os
# Read the current working directory
cwd = os.getcwd()
# List the content of a specific folder
dir_content = os.listdir("C://Documents/Python/1ALG")
# Rename a specific file (also does file move)
os.rename("./build/script.js", "./release/script.js")
Python doc : https://docs.python.org/3/library/os.html
14
Built-ins modules : sys
- Interact with the python runtime :
- Command line arguments
- Python version information
- Configure runtime parameters
- Read runtime constants
- …
- Python doc : https://docs.python.org/3/library/sys.html
15
Built-ins modules : sys - examples
import sys
# show the version of the current python runtime
print(sys.version_info)
# change recursion limit
sys.setrecursionlimit(2000)
# Read the maximum possible int value
biggest_value = sys.maxsize
Python doc : https://docs.python.org/3/library/sys.html
16
Built-ins modules : math
- Useful math functions :
- Basic math functions
- Trigonometric functions
- Hyperbolic functions
- Statistics and probabilities
- …
- Python doc : https://docs.python.org/3/library/math.html
17
Built-ins modules : math - example
import math
x, y = 3, 16
# Logarithm, Square Root & Power
log_x = math.log(x)
sqrt_x = math.sqrt(x)
power_xy = math.pow(x, y)
# Trigonometric functions
angle = math.pi / 6 # 30 degrees
sin_angle = math.sin(angle)
cos_angle = math.cos(angle)
tan_angle = math.tan(angle)
18
Built-ins modules : random
- Functions to generate random values :
- Generate random numbers
- Generate random sequences
- Randomly select values
- …
- Python doc : https://docs.python.org/3/library/random.html
19
Built-in modules : random - example
import random
# Generate random floating-point numbers
random_float = random.random()
# Generate a random integer within a range
random_integer = random.randint(1, 10)
# Generate a random floating-point number within a range
random_float_range = random.uniform(1.0, 5.0)
# Shuffle a list randomly
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
20
How does python find the modules ?
sys.modules sys.path
21
sys.path content
Current working directory
Python installation
Third party packages (venv)
22
Creating our
own modules
23
Currently
All our code is in a single file.
Maintainability will become harder as it grows.
We need to find a way to make it easier to manage.
24
Creating modules
Files containing our code.
Makes the code cleaner and easier to understand.
Gives the ability to use namespaces.
25
Using other python files
- Create the file demo.py in the same folder as main.py
.
├── main.py
└── demo.py
26
Importing modules : demo.py
- Add this in the file demo.py :
print("This is demo.py")
def say_hello(name: str):
print(f"Hello, {name} !")
27
Importing files : main.py
- Add this in the content of main.py :
import demo
print("This is main.py")
demo.say_hello("Python")
28
Importing files
- Run the file main.py : "python main.py"
>>> "This is demo.py"
>>> "This is main.py"
>>> "Hello, Python !"
- demo.py is loaded before the code in main.py has finished being run.
29
If __name__ == "__main__"
- When you import a module, all its code is loaded top down.
- This check only executes code if the current file is the one being run.
import utils
def main():
utils.say_hello("Python")
if __name__ == "__main__":
print("This is the main file")
main()
30
Installing new
modules
31
External modules / Extends features of the
standard library.
Allows to use code written by
someone else.
packages
Easiest way to install is with
a package manager.
32
What is PIP ?
Official package manager of python.
Usually comes bundled with python.
Uses the pypi registry.
33
Using pip
- Installing a package :
python -m pip install <package_name>
- Uninstall a package :
python -m pip uninstall <package_name>
34
Package installation example
- Installation of requests, a very useful package for HTTP requests.
> python -m pip install requests
Collecting requests
Downloading requests-xxx-py3-none-any.whl (62 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.8/62.8 kB 1.3 MB/s eta
0:00:00
Installing collected packages: urllib3, certifi, requests
Successfully installed certifi-xxxx.x.xx requests-x.xx.x urllib3-x.xx.xx
35
Where to find packages
https://pypi.org/
36
Packages conflicts.
Packages are installed globally for python.
How can we manage different dependencies versions ?
What about projects with incompatible dependencies ?
37
Virtual environments
- Avoid polluting your python installation.
- Provides per project environment isolation.
- Lightweight solution.
- Native solution : venv.
38
Using venv
- Creation : python -m venv <path_to_venv>
- Activation :
- Windows Powershell : <path_to_venv>\Scripts\activate
- Linux / Mac : source <path_to_venv>/bin/activate
39
Using venv
- Once the venv is active, you will be able to use its python binary.
- Installed packages with pip will be inside the venv.
- Packages are separated from the ones in the global python installation.
40
The requirements.txt file
- Used to track the dependencies of an application.
- Creation :
pip freeze > requirements.txt
- Installing packages using it :
pip install -r requirements.txt
41
Example requirements.txt
certifi==2022.9.24
charset-normalizer==2.1.1
click==8.1.3
idna==3.4
pathspec==0.10.1
platformdirs==2.5.2
requests==2.28.1
tomli==2.0.1
urllib3==1.26.12
42
Poetry
Pipenv
Other tools
Virtualenv
Conda
43
Conclusion
- Modules are a way to extend our
code.
- Provide many useful features
- You can install external modules
using pip.
- Use a virtual env to avoid polluting
your installation.
44
Let’s practice !
45