
Modules and Libraries
Module
A module is a .py
file containing Python code, typically including functions, classes, and variables designed for a specific purpose.
Modules allow you to logically organize your Python code into reusable components.
You can import and use modules in other Python scripts or interactive sessions to access the functionality defined within them.
Create a Module
To create a module, simply save your code in a file with the .py
extension.
Example
Save the code below in a file named samplemodule.py
:
def greeting(name): print(f"Hello, {name}!")
Use a Module
To use the module we just created, we use the import
statement to import the module into current session.
Example
Import the samplemodule
module and call the greeting function:
import samplemodule
samplemodule.greeting("Mike")
Output:
Hello, Mike!
Add Variables to Modules
A module can include functions, as mentioned, and variables of all types (arrays, dictionaries, objects, etc.).
Example
Add this code to the file samplemodule.py
.
person = { "name": "Mike", "age": 24, "country": "US"}
Import the module named samplemodule
, and access the person
dictionary:
import samplemodule
print(samplemodule.person['name'])print(samplemodule.person['age'])print(samplemodule.person['country'])
Output:
Mike
24
US
Add Classes to Modules
A module can also contain classes.
Example
Add this class to the samplemodule.py
file.
class Athlete(): def __init__(self, name, age, country): self.name = name self.age = age self.country = country def report(self): print(f"{self.name}-{self.age}-{self.country}")
Instead of importing the entire module, you can also import only specific classes, variables, or functions into the current session by using syntax:
from module_name import class_name
Example
Import the Athlete
class to the current session, instantiate an object, and call the report
method.
# Import the Athlete classfrom samplemodule import Athlete
# Instantiate an objectathlete1 = Athlete("Mike", "20", "US")# Invoke the instance functionathlete1.report()
Output:
Mike-20-US
Library
A library, also known as a package, is a collection of related modules that offer specific functionalities for performing a variety of tasks.
Python offers numerous third-party libraries created by programmers and extensively used by the Python community, including numpy
, pandas
, matplotlib
, and more.
Install and Import Third-party Libraries
Example
If it's your first time using the numpy library, install it using the following command in the terminal or Jupyter notebook cell:
pip install numpy
Next, import the numpy library and print the version of the library:
import numpy
print(numpy.__version__)
Output:
1.21.5
To utilize numpy's methods, apply the syntax: numpy.function()
.
For instance, numpy offers a sum()
function to calculate the sum of lists or arrays.
# Create a listsample_list = [1, 2, 3, 4, 5]
# Use numpy.sum() to calculate the sum of the listlist_sum = numpy.sum(sample_list)
print(list_sum)
Output:
15
Use Alias for Libraries
Conventionally, Python developers use a shorthand alias for libraries, such as np
for numpy
, to simplify code.
To achieve that, you just import the library with the shorthand alias using the as
keyword. For example:
import numpy as np
sample_list = [1, 2, 3, 4, 5]
# Use np.sum() instead of numpy.sum()list_sum = np.sum(sample_list)
print(list_sum)
Output:
15