Chapter 7: Modules and Packages
7.4 Python Packages
In the previous sections, we discussed modules and how to create and use them. In addition to being a powerful tool for code organization, modules also allow for code reuse, simplifying development and maintenance tasks.
In this section, we'll dive into Python packages, which are a way of organizing related modules in a hierarchical structure. Packages provide yet another level of organization within a codebase, making it easy to group and manage a large number of modules. By breaking up code into smaller, more easily manageable pieces, packages help developers maintain order and clarity within their projects.
Furthermore, packages can be shared between projects, making them an ideal tool for promoting code reuse across an entire organization.
A Python package is simply a directory that contains a collection of modules and a special file called __init__.py
. The presence of this file tells Python that the directory should be treated as a package. The __init__.py
file can be empty or contain initialization code for your package.
Let's understand packages with an easy explanation:
7.4.1: Creating a package:
To create a package, first, create a directory with a suitable name. Then, create an __init__.py
file inside the directory.
For example, let's create a package called vehicles
. Create a directory named vehicles
and add an empty __init__.py
file to it.
7.4.2: Adding modules to a package:
You can add modules to the package by simply creating .py
files within the package directory.
For example, let's add two modules to our vehicles
package: cars.py
and trucks.py
.
7.4.3: Importing and using packages:
To use a package, simply use the import
statement followed by the package name and the module name, separated by a dot.
For example, to use the cars
module from the vehicles
package, you would write import vehicles.cars
. You can also use the from ... import ...
statement to import specific functions or classes.
Here's a brief example to demonstrate packages:
vehicles/__init__.py
:
# This can be empty or contain package-level initialization code.
vehicles/cars.py
:
def car_description(make, model):
return f"{make} {model}"
vehicles/trucks.py
:
def truck_description(make, model, bed_size):
return f"{make} {model} with a {bed_size} bed"
main.py
:
from vehicles.cars import car_description
from vehicles.trucks import truck_description
print(car_description("Toyota", "Camry"))
print(truck_description("Ford", "F-150", "6.5 ft"))
Output:
Toyota Camry
Ford F-150 with a 6.5 ft bed
Python packages provide an efficient way of organizing related modules into a hierarchical structure, enabling developers to manage and maintain larger projects with ease. This feature is especially useful when working on complex software projects with a lot of code.
Packages are directories that contain one or more python modules, with an __init__.py
file defining the package. The __init__.py
file is executed when the package is imported, which allows for customization of the package's behavior. This file can contain variables, functions, or classes that are used across the modules in the package.
By grouping related modules together into a package, it becomes easier to manage dependencies between them. This promotes code reuse and makes it easier for others to understand the codebase. Additionally, packages can be distributed as standalone units, making them easy to share and reuse across multiple projects.
Overall, using packages in Python is an excellent way to keep your code organized and maintainable, making it easier to work on larger projects and collaborate with others. Remember, packages are a fundamental feature of the Python language, so it's essential to learn how to use them effectively.
Exercise 7.4.1: Creating and using a simple package
In this exercise, you will create a package named shapes
containing two modules: rectangle.py
and circle.py
. Each module should contain functions to calculate the area and perimeter of the respective shape. Finally, you will import and use these functions in a script called main.py
.
Instructions:
- Create a package named
shapes
with an empty__init__.py
file. - Create a module
rectangle.py
inside theshapes
package containing the following functions:area(width, height)
: Returns the area of a rectangle.perimeter(width, height)
: Returns the perimeter of a rectangle.
- Create a module
circle.py
inside theshapes
package containing the following functions:area(radius)
: Returns the area of a circle.circumference(radius)
: Returns the circumference of a circle.
- In
main.py
, import and use the functions from both modules to calculate the area and perimeter of a rectangle with width 5 and height 7, and the area and circumference of a circle with radius 4.
Solution:
shapes/__init__.py
:
# This can be empty or contain package-level initialization code.
shapes/rectangle.py
:
def area(width, height):
return width * height
def perimeter(width, height):
return 2 * (width + height)
shapes/circle.py
:
import math
def area(radius):
return math.pi * radius ** 2
def circumference(radius):
return 2 * math.pi * radius
main.py
:
from shapes.rectangle import area as rect_area, perimeter as rect_perimeter
from shapes.circle import area as circle_area, circumference as circle_circumference
width = 5
height = 7
radius = 4
print(f"Rectangle area: {rect_area(width, height)}")
print(f"Rectangle perimeter: {rect_perimeter(width, height)}")
print(f"Circle area: {circle_area(radius)}")
print(f"Circle circumference: {circle_circumference(radius)}")
Output:
Rectangle area: 35
Rectangle perimeter: 24
Circle area: 50.26548245743669
Circle circumference: 25.132741228718345
Exercise 7.4.2: Creating a Package
In this exercise, you will create a simple package named my_math
containing two modules, addition
and multiplication
. Each module will have functions to perform basic arithmetic operations.
Instructions:
- Create a folder named
my_math
to serve as your package. - Inside the
my_math
folder, create two Python files namedaddition.py
andmultiplication.py
. - In
addition.py
, define a functionadd(a, b)
that returns the sum of the two input numbers. - In
multiplication.py
, define a functionmultiply(a, b)
that returns the product of the two input numbers. - In the main script, import and use both modules to perform addition and multiplication.
Solution:
# my_math/addition.py
def add(a, b):
return a + b
# my_math/multiplication.py
def multiply(a, b):
return a * b
# main.py
from my_math.addition import add
from my_math.multiplication import multiply
a = 5
b = 3
sum_result = add(a, b)
product_result = multiply(a, b)
print(f"{a} + {b} = {sum_result}")
print(f"{a} * {b} = {product_result}")
Output:
5 + 3 = 8
5 * 3 = 15
Exercise 7.4.3: Using third-party packages
In this exercise, you will install and use a third-party package to generate random names. You will create a script that generates and prints a random name using the names
package.
Instructions:
- Install the
names
package usingpip install names
. - Create a script
random_name.py
that imports thenames
package. - Use the
names.get_full_name()
function to generate a random full name. - Print the random full name.
Solution:
# random_name.py
import names
random_full_name = names.get_full_name()
print(f"Random full name: {random_full_name}")
Output (sample):
Random full name: John Smith
Note: The output will vary each time you run the script since it generates a random name.
Congratulations on completing Chapter 7! In this chapter, you learned about Python modules and packages, essential tools for organizing and structuring your code.
You started by understanding how to import modules and use the functions they provide. Next, you explored some of the standard library modules, such as os
, random
, math
, and urllib
, which provide useful functionalities in different areas.
We then moved on to creating your own modules, allowing you to reuse and share your code more easily. Finally, you learned about packages, which are a way to group related modules together, creating a more structured and organized codebase.
As you continue to work on more complex projects, you'll find that modules and packages are indispensable for managing code, avoiding duplication, and improving maintainability. Keep practicing, and don't be afraid to explore other standard library modules and third-party packages to help you accomplish your tasks more efficiently.
7.4 Python Packages
In the previous sections, we discussed modules and how to create and use them. In addition to being a powerful tool for code organization, modules also allow for code reuse, simplifying development and maintenance tasks.
In this section, we'll dive into Python packages, which are a way of organizing related modules in a hierarchical structure. Packages provide yet another level of organization within a codebase, making it easy to group and manage a large number of modules. By breaking up code into smaller, more easily manageable pieces, packages help developers maintain order and clarity within their projects.
Furthermore, packages can be shared between projects, making them an ideal tool for promoting code reuse across an entire organization.
A Python package is simply a directory that contains a collection of modules and a special file called __init__.py
. The presence of this file tells Python that the directory should be treated as a package. The __init__.py
file can be empty or contain initialization code for your package.
Let's understand packages with an easy explanation:
7.4.1: Creating a package:
To create a package, first, create a directory with a suitable name. Then, create an __init__.py
file inside the directory.
For example, let's create a package called vehicles
. Create a directory named vehicles
and add an empty __init__.py
file to it.
7.4.2: Adding modules to a package:
You can add modules to the package by simply creating .py
files within the package directory.
For example, let's add two modules to our vehicles
package: cars.py
and trucks.py
.
7.4.3: Importing and using packages:
To use a package, simply use the import
statement followed by the package name and the module name, separated by a dot.
For example, to use the cars
module from the vehicles
package, you would write import vehicles.cars
. You can also use the from ... import ...
statement to import specific functions or classes.
Here's a brief example to demonstrate packages:
vehicles/__init__.py
:
# This can be empty or contain package-level initialization code.
vehicles/cars.py
:
def car_description(make, model):
return f"{make} {model}"
vehicles/trucks.py
:
def truck_description(make, model, bed_size):
return f"{make} {model} with a {bed_size} bed"
main.py
:
from vehicles.cars import car_description
from vehicles.trucks import truck_description
print(car_description("Toyota", "Camry"))
print(truck_description("Ford", "F-150", "6.5 ft"))
Output:
Toyota Camry
Ford F-150 with a 6.5 ft bed
Python packages provide an efficient way of organizing related modules into a hierarchical structure, enabling developers to manage and maintain larger projects with ease. This feature is especially useful when working on complex software projects with a lot of code.
Packages are directories that contain one or more python modules, with an __init__.py
file defining the package. The __init__.py
file is executed when the package is imported, which allows for customization of the package's behavior. This file can contain variables, functions, or classes that are used across the modules in the package.
By grouping related modules together into a package, it becomes easier to manage dependencies between them. This promotes code reuse and makes it easier for others to understand the codebase. Additionally, packages can be distributed as standalone units, making them easy to share and reuse across multiple projects.
Overall, using packages in Python is an excellent way to keep your code organized and maintainable, making it easier to work on larger projects and collaborate with others. Remember, packages are a fundamental feature of the Python language, so it's essential to learn how to use them effectively.
Exercise 7.4.1: Creating and using a simple package
In this exercise, you will create a package named shapes
containing two modules: rectangle.py
and circle.py
. Each module should contain functions to calculate the area and perimeter of the respective shape. Finally, you will import and use these functions in a script called main.py
.
Instructions:
- Create a package named
shapes
with an empty__init__.py
file. - Create a module
rectangle.py
inside theshapes
package containing the following functions:area(width, height)
: Returns the area of a rectangle.perimeter(width, height)
: Returns the perimeter of a rectangle.
- Create a module
circle.py
inside theshapes
package containing the following functions:area(radius)
: Returns the area of a circle.circumference(radius)
: Returns the circumference of a circle.
- In
main.py
, import and use the functions from both modules to calculate the area and perimeter of a rectangle with width 5 and height 7, and the area and circumference of a circle with radius 4.
Solution:
shapes/__init__.py
:
# This can be empty or contain package-level initialization code.
shapes/rectangle.py
:
def area(width, height):
return width * height
def perimeter(width, height):
return 2 * (width + height)
shapes/circle.py
:
import math
def area(radius):
return math.pi * radius ** 2
def circumference(radius):
return 2 * math.pi * radius
main.py
:
from shapes.rectangle import area as rect_area, perimeter as rect_perimeter
from shapes.circle import area as circle_area, circumference as circle_circumference
width = 5
height = 7
radius = 4
print(f"Rectangle area: {rect_area(width, height)}")
print(f"Rectangle perimeter: {rect_perimeter(width, height)}")
print(f"Circle area: {circle_area(radius)}")
print(f"Circle circumference: {circle_circumference(radius)}")
Output:
Rectangle area: 35
Rectangle perimeter: 24
Circle area: 50.26548245743669
Circle circumference: 25.132741228718345
Exercise 7.4.2: Creating a Package
In this exercise, you will create a simple package named my_math
containing two modules, addition
and multiplication
. Each module will have functions to perform basic arithmetic operations.
Instructions:
- Create a folder named
my_math
to serve as your package. - Inside the
my_math
folder, create two Python files namedaddition.py
andmultiplication.py
. - In
addition.py
, define a functionadd(a, b)
that returns the sum of the two input numbers. - In
multiplication.py
, define a functionmultiply(a, b)
that returns the product of the two input numbers. - In the main script, import and use both modules to perform addition and multiplication.
Solution:
# my_math/addition.py
def add(a, b):
return a + b
# my_math/multiplication.py
def multiply(a, b):
return a * b
# main.py
from my_math.addition import add
from my_math.multiplication import multiply
a = 5
b = 3
sum_result = add(a, b)
product_result = multiply(a, b)
print(f"{a} + {b} = {sum_result}")
print(f"{a} * {b} = {product_result}")
Output:
5 + 3 = 8
5 * 3 = 15
Exercise 7.4.3: Using third-party packages
In this exercise, you will install and use a third-party package to generate random names. You will create a script that generates and prints a random name using the names
package.
Instructions:
- Install the
names
package usingpip install names
. - Create a script
random_name.py
that imports thenames
package. - Use the
names.get_full_name()
function to generate a random full name. - Print the random full name.
Solution:
# random_name.py
import names
random_full_name = names.get_full_name()
print(f"Random full name: {random_full_name}")
Output (sample):
Random full name: John Smith
Note: The output will vary each time you run the script since it generates a random name.
Congratulations on completing Chapter 7! In this chapter, you learned about Python modules and packages, essential tools for organizing and structuring your code.
You started by understanding how to import modules and use the functions they provide. Next, you explored some of the standard library modules, such as os
, random
, math
, and urllib
, which provide useful functionalities in different areas.
We then moved on to creating your own modules, allowing you to reuse and share your code more easily. Finally, you learned about packages, which are a way to group related modules together, creating a more structured and organized codebase.
As you continue to work on more complex projects, you'll find that modules and packages are indispensable for managing code, avoiding duplication, and improving maintainability. Keep practicing, and don't be afraid to explore other standard library modules and third-party packages to help you accomplish your tasks more efficiently.
7.4 Python Packages
In the previous sections, we discussed modules and how to create and use them. In addition to being a powerful tool for code organization, modules also allow for code reuse, simplifying development and maintenance tasks.
In this section, we'll dive into Python packages, which are a way of organizing related modules in a hierarchical structure. Packages provide yet another level of organization within a codebase, making it easy to group and manage a large number of modules. By breaking up code into smaller, more easily manageable pieces, packages help developers maintain order and clarity within their projects.
Furthermore, packages can be shared between projects, making them an ideal tool for promoting code reuse across an entire organization.
A Python package is simply a directory that contains a collection of modules and a special file called __init__.py
. The presence of this file tells Python that the directory should be treated as a package. The __init__.py
file can be empty or contain initialization code for your package.
Let's understand packages with an easy explanation:
7.4.1: Creating a package:
To create a package, first, create a directory with a suitable name. Then, create an __init__.py
file inside the directory.
For example, let's create a package called vehicles
. Create a directory named vehicles
and add an empty __init__.py
file to it.
7.4.2: Adding modules to a package:
You can add modules to the package by simply creating .py
files within the package directory.
For example, let's add two modules to our vehicles
package: cars.py
and trucks.py
.
7.4.3: Importing and using packages:
To use a package, simply use the import
statement followed by the package name and the module name, separated by a dot.
For example, to use the cars
module from the vehicles
package, you would write import vehicles.cars
. You can also use the from ... import ...
statement to import specific functions or classes.
Here's a brief example to demonstrate packages:
vehicles/__init__.py
:
# This can be empty or contain package-level initialization code.
vehicles/cars.py
:
def car_description(make, model):
return f"{make} {model}"
vehicles/trucks.py
:
def truck_description(make, model, bed_size):
return f"{make} {model} with a {bed_size} bed"
main.py
:
from vehicles.cars import car_description
from vehicles.trucks import truck_description
print(car_description("Toyota", "Camry"))
print(truck_description("Ford", "F-150", "6.5 ft"))
Output:
Toyota Camry
Ford F-150 with a 6.5 ft bed
Python packages provide an efficient way of organizing related modules into a hierarchical structure, enabling developers to manage and maintain larger projects with ease. This feature is especially useful when working on complex software projects with a lot of code.
Packages are directories that contain one or more python modules, with an __init__.py
file defining the package. The __init__.py
file is executed when the package is imported, which allows for customization of the package's behavior. This file can contain variables, functions, or classes that are used across the modules in the package.
By grouping related modules together into a package, it becomes easier to manage dependencies between them. This promotes code reuse and makes it easier for others to understand the codebase. Additionally, packages can be distributed as standalone units, making them easy to share and reuse across multiple projects.
Overall, using packages in Python is an excellent way to keep your code organized and maintainable, making it easier to work on larger projects and collaborate with others. Remember, packages are a fundamental feature of the Python language, so it's essential to learn how to use them effectively.
Exercise 7.4.1: Creating and using a simple package
In this exercise, you will create a package named shapes
containing two modules: rectangle.py
and circle.py
. Each module should contain functions to calculate the area and perimeter of the respective shape. Finally, you will import and use these functions in a script called main.py
.
Instructions:
- Create a package named
shapes
with an empty__init__.py
file. - Create a module
rectangle.py
inside theshapes
package containing the following functions:area(width, height)
: Returns the area of a rectangle.perimeter(width, height)
: Returns the perimeter of a rectangle.
- Create a module
circle.py
inside theshapes
package containing the following functions:area(radius)
: Returns the area of a circle.circumference(radius)
: Returns the circumference of a circle.
- In
main.py
, import and use the functions from both modules to calculate the area and perimeter of a rectangle with width 5 and height 7, and the area and circumference of a circle with radius 4.
Solution:
shapes/__init__.py
:
# This can be empty or contain package-level initialization code.
shapes/rectangle.py
:
def area(width, height):
return width * height
def perimeter(width, height):
return 2 * (width + height)
shapes/circle.py
:
import math
def area(radius):
return math.pi * radius ** 2
def circumference(radius):
return 2 * math.pi * radius
main.py
:
from shapes.rectangle import area as rect_area, perimeter as rect_perimeter
from shapes.circle import area as circle_area, circumference as circle_circumference
width = 5
height = 7
radius = 4
print(f"Rectangle area: {rect_area(width, height)}")
print(f"Rectangle perimeter: {rect_perimeter(width, height)}")
print(f"Circle area: {circle_area(radius)}")
print(f"Circle circumference: {circle_circumference(radius)}")
Output:
Rectangle area: 35
Rectangle perimeter: 24
Circle area: 50.26548245743669
Circle circumference: 25.132741228718345
Exercise 7.4.2: Creating a Package
In this exercise, you will create a simple package named my_math
containing two modules, addition
and multiplication
. Each module will have functions to perform basic arithmetic operations.
Instructions:
- Create a folder named
my_math
to serve as your package. - Inside the
my_math
folder, create two Python files namedaddition.py
andmultiplication.py
. - In
addition.py
, define a functionadd(a, b)
that returns the sum of the two input numbers. - In
multiplication.py
, define a functionmultiply(a, b)
that returns the product of the two input numbers. - In the main script, import and use both modules to perform addition and multiplication.
Solution:
# my_math/addition.py
def add(a, b):
return a + b
# my_math/multiplication.py
def multiply(a, b):
return a * b
# main.py
from my_math.addition import add
from my_math.multiplication import multiply
a = 5
b = 3
sum_result = add(a, b)
product_result = multiply(a, b)
print(f"{a} + {b} = {sum_result}")
print(f"{a} * {b} = {product_result}")
Output:
5 + 3 = 8
5 * 3 = 15
Exercise 7.4.3: Using third-party packages
In this exercise, you will install and use a third-party package to generate random names. You will create a script that generates and prints a random name using the names
package.
Instructions:
- Install the
names
package usingpip install names
. - Create a script
random_name.py
that imports thenames
package. - Use the
names.get_full_name()
function to generate a random full name. - Print the random full name.
Solution:
# random_name.py
import names
random_full_name = names.get_full_name()
print(f"Random full name: {random_full_name}")
Output (sample):
Random full name: John Smith
Note: The output will vary each time you run the script since it generates a random name.
Congratulations on completing Chapter 7! In this chapter, you learned about Python modules and packages, essential tools for organizing and structuring your code.
You started by understanding how to import modules and use the functions they provide. Next, you explored some of the standard library modules, such as os
, random
, math
, and urllib
, which provide useful functionalities in different areas.
We then moved on to creating your own modules, allowing you to reuse and share your code more easily. Finally, you learned about packages, which are a way to group related modules together, creating a more structured and organized codebase.
As you continue to work on more complex projects, you'll find that modules and packages are indispensable for managing code, avoiding duplication, and improving maintainability. Keep practicing, and don't be afraid to explore other standard library modules and third-party packages to help you accomplish your tasks more efficiently.
7.4 Python Packages
In the previous sections, we discussed modules and how to create and use them. In addition to being a powerful tool for code organization, modules also allow for code reuse, simplifying development and maintenance tasks.
In this section, we'll dive into Python packages, which are a way of organizing related modules in a hierarchical structure. Packages provide yet another level of organization within a codebase, making it easy to group and manage a large number of modules. By breaking up code into smaller, more easily manageable pieces, packages help developers maintain order and clarity within their projects.
Furthermore, packages can be shared between projects, making them an ideal tool for promoting code reuse across an entire organization.
A Python package is simply a directory that contains a collection of modules and a special file called __init__.py
. The presence of this file tells Python that the directory should be treated as a package. The __init__.py
file can be empty or contain initialization code for your package.
Let's understand packages with an easy explanation:
7.4.1: Creating a package:
To create a package, first, create a directory with a suitable name. Then, create an __init__.py
file inside the directory.
For example, let's create a package called vehicles
. Create a directory named vehicles
and add an empty __init__.py
file to it.
7.4.2: Adding modules to a package:
You can add modules to the package by simply creating .py
files within the package directory.
For example, let's add two modules to our vehicles
package: cars.py
and trucks.py
.
7.4.3: Importing and using packages:
To use a package, simply use the import
statement followed by the package name and the module name, separated by a dot.
For example, to use the cars
module from the vehicles
package, you would write import vehicles.cars
. You can also use the from ... import ...
statement to import specific functions or classes.
Here's a brief example to demonstrate packages:
vehicles/__init__.py
:
# This can be empty or contain package-level initialization code.
vehicles/cars.py
:
def car_description(make, model):
return f"{make} {model}"
vehicles/trucks.py
:
def truck_description(make, model, bed_size):
return f"{make} {model} with a {bed_size} bed"
main.py
:
from vehicles.cars import car_description
from vehicles.trucks import truck_description
print(car_description("Toyota", "Camry"))
print(truck_description("Ford", "F-150", "6.5 ft"))
Output:
Toyota Camry
Ford F-150 with a 6.5 ft bed
Python packages provide an efficient way of organizing related modules into a hierarchical structure, enabling developers to manage and maintain larger projects with ease. This feature is especially useful when working on complex software projects with a lot of code.
Packages are directories that contain one or more python modules, with an __init__.py
file defining the package. The __init__.py
file is executed when the package is imported, which allows for customization of the package's behavior. This file can contain variables, functions, or classes that are used across the modules in the package.
By grouping related modules together into a package, it becomes easier to manage dependencies between them. This promotes code reuse and makes it easier for others to understand the codebase. Additionally, packages can be distributed as standalone units, making them easy to share and reuse across multiple projects.
Overall, using packages in Python is an excellent way to keep your code organized and maintainable, making it easier to work on larger projects and collaborate with others. Remember, packages are a fundamental feature of the Python language, so it's essential to learn how to use them effectively.
Exercise 7.4.1: Creating and using a simple package
In this exercise, you will create a package named shapes
containing two modules: rectangle.py
and circle.py
. Each module should contain functions to calculate the area and perimeter of the respective shape. Finally, you will import and use these functions in a script called main.py
.
Instructions:
- Create a package named
shapes
with an empty__init__.py
file. - Create a module
rectangle.py
inside theshapes
package containing the following functions:area(width, height)
: Returns the area of a rectangle.perimeter(width, height)
: Returns the perimeter of a rectangle.
- Create a module
circle.py
inside theshapes
package containing the following functions:area(radius)
: Returns the area of a circle.circumference(radius)
: Returns the circumference of a circle.
- In
main.py
, import and use the functions from both modules to calculate the area and perimeter of a rectangle with width 5 and height 7, and the area and circumference of a circle with radius 4.
Solution:
shapes/__init__.py
:
# This can be empty or contain package-level initialization code.
shapes/rectangle.py
:
def area(width, height):
return width * height
def perimeter(width, height):
return 2 * (width + height)
shapes/circle.py
:
import math
def area(radius):
return math.pi * radius ** 2
def circumference(radius):
return 2 * math.pi * radius
main.py
:
from shapes.rectangle import area as rect_area, perimeter as rect_perimeter
from shapes.circle import area as circle_area, circumference as circle_circumference
width = 5
height = 7
radius = 4
print(f"Rectangle area: {rect_area(width, height)}")
print(f"Rectangle perimeter: {rect_perimeter(width, height)}")
print(f"Circle area: {circle_area(radius)}")
print(f"Circle circumference: {circle_circumference(radius)}")
Output:
Rectangle area: 35
Rectangle perimeter: 24
Circle area: 50.26548245743669
Circle circumference: 25.132741228718345
Exercise 7.4.2: Creating a Package
In this exercise, you will create a simple package named my_math
containing two modules, addition
and multiplication
. Each module will have functions to perform basic arithmetic operations.
Instructions:
- Create a folder named
my_math
to serve as your package. - Inside the
my_math
folder, create two Python files namedaddition.py
andmultiplication.py
. - In
addition.py
, define a functionadd(a, b)
that returns the sum of the two input numbers. - In
multiplication.py
, define a functionmultiply(a, b)
that returns the product of the two input numbers. - In the main script, import and use both modules to perform addition and multiplication.
Solution:
# my_math/addition.py
def add(a, b):
return a + b
# my_math/multiplication.py
def multiply(a, b):
return a * b
# main.py
from my_math.addition import add
from my_math.multiplication import multiply
a = 5
b = 3
sum_result = add(a, b)
product_result = multiply(a, b)
print(f"{a} + {b} = {sum_result}")
print(f"{a} * {b} = {product_result}")
Output:
5 + 3 = 8
5 * 3 = 15
Exercise 7.4.3: Using third-party packages
In this exercise, you will install and use a third-party package to generate random names. You will create a script that generates and prints a random name using the names
package.
Instructions:
- Install the
names
package usingpip install names
. - Create a script
random_name.py
that imports thenames
package. - Use the
names.get_full_name()
function to generate a random full name. - Print the random full name.
Solution:
# random_name.py
import names
random_full_name = names.get_full_name()
print(f"Random full name: {random_full_name}")
Output (sample):
Random full name: John Smith
Note: The output will vary each time you run the script since it generates a random name.
Congratulations on completing Chapter 7! In this chapter, you learned about Python modules and packages, essential tools for organizing and structuring your code.
You started by understanding how to import modules and use the functions they provide. Next, you explored some of the standard library modules, such as os
, random
, math
, and urllib
, which provide useful functionalities in different areas.
We then moved on to creating your own modules, allowing you to reuse and share your code more easily. Finally, you learned about packages, which are a way to group related modules together, creating a more structured and organized codebase.
As you continue to work on more complex projects, you'll find that modules and packages are indispensable for managing code, avoiding duplication, and improving maintainability. Keep practicing, and don't be afraid to explore other standard library modules and third-party packages to help you accomplish your tasks more efficiently.