Module 11 - Python Modules Header

Module 11 - Python Modules

Introducing Modules

In Python, a module is a file containing Python code that defines functions, classes, and variables, which can be imported and used in other Python programs. Modules allow you to organize code into logical units and facilitate code reuse, modularity, and maintainability.

Creating and Importing Modules:

To create a module, you simply write Python code in a file with a .py extension. You can define functions, classes, and variables in the module file. Here's an example of a simple module named my_module.py:

# my_module.py

def greet(name):
print(f"Hello, {name}!")

def add_numbers(a, b):
return a + b

PI = 3.14159

To use the functions and variables defined in a module, you need to import it into your Python program. There are several ways to import a module:

Importing the Whole Module:

When you are planning to access most or a significant part of the functionality of a module, you will probably chooce to import the entire module.  This gives access to all of the functions, classes, and variables within it.  The only downside of this method is that you will be required to use the module name then the function, variable or class to refer to those members of the module.  You will see this in the example below (my_module.greet, and so on).

import my_module

my_module.greet("Alice")
print(my_module.add_numbers(5, 7))
print(my_module.PI)

Importing Specific Functions or Variables:

When you only want a small part of a module's functionality, or memory conservation is a concern, you may want to only import the things that you need from a module.  This is done using the from keyword.  Notice also that in this method, you don't need to use dot notation.  Be careful, though - If you have the same name used somewhere else in your code, this will create a conflict called a namespace conflict.

from my_module import greet, PI

greet("Bob")
print(PI)

Variable Scope in Modules:

Variables defined within a module have a module-level scope. This means they are accessible throughout the module. Functions and classes defined in the module can access these variables.

__name__

In Python, there is a special variable called __name__ that represents the current module's name. When a module is imported, the __name__ variable is set to the module's name. However, when the module is executed as the main program, the __name__ variable is set to "__main__".

This distinction allows you to have code in a module that runs only when the module is executed as the main program, but not when it is imported as a module.

Example:

from my_module import greet, PI

greet("Bob")
print(PI)# my_module.py

def greet(name):
print(f"Hello, {name}!")

if __name__ == "__main__":
# This code will only run when the module is executed as the main program
greet("Alice")

Limitations and Common Mistakes:

  • Namespace Conflicts: Be cautious of naming conflicts when importing multiple modules. If two modules have functions or variables with the same name, you may encounter conflicts or unexpected behavior.
  • Forgetting to Import Modules: If you forget to import a required module, you'll encounter a NameError when trying to use functions or variables from that module.
  • Overusing Wildcard Imports: Avoid using wildcard imports (from module import *) as they can pollute the namespace and make it unclear which functions or variables come from which modules.
  • Circular Dependencies: Be mindful of circular dependencies, where two or more modules depend on each other. This can lead to import errors or unexpected behaviors. Try to design your modules with a clear hierarchy to avoid circular dependencies.

Variations in Usage:

  • Using Third-Party Modules: In addition to Python's built-in modules, you can also use third-party modules developed by the Python community. These modules provide additional functionalities that are not available in the standard library. They can be installed using package managers like pip and imported into your program.
  • Creating and Using Packages: Packages are directories that contain multiple modules and sub-packages. They allow you to organize related modules into a hierarchical structure. To create a package, you need to include an __init__.py file in the package directory. Packages are imported similarly to modules using the import statement.
# Importing a module from a package
import my_package.my_module

my_package.my_module.my_function()

Modules in Python provide a powerful way to organize and reuse code. By understanding their abilities, limitations, variable scope, and common mistakes, you can effectively use and create modules to enhance your Python programs.



The Python Standard Library

The Python Standard Library is a collection of modules that come bundled with Python. It provides a wide range of functionalities to help you perform various tasks without requiring additional installations or dependencies. The Standard Library covers diverse areas such as file handling, network programming, mathematics, string manipulation, and more.

Overview of Commonly Used Modules:

Let's explore some commonly used modules from the Python Standard Library, along with examples of their usage:

math: Provides mathematical functions and constants.

import math

print(math.sqrt(25)) # Output: 5.0
print(math.pi) # Output: 3.141592653589793
print(math.sin(math.pi/2)) # Output: 1.0

random: Offers functions for generating random numbers and selecting random elements.

import random

print(random.randint(1, 10)) # Output: Random integer between 1 and 10
print(random.choice(['apple', 'banana', 'cherry'])) # Output: Random choice from the list

os: Provides operating system-related functions for file and directory manipulation.

import os

print(os.getcwd()) # Output: Current working directory
print(os.listdir('/path')) # Output: List of files and directories in the given path

datetime: Allows working with dates, times, and timedeltas.

import datetime

now = datetime.datetime.now()
print(now) # Output: Current date and time
print(now.year) # Output: Current year
print(now.strftime('%Y-%m-%d %H:%M:%S')) # Output: Formatted date and time

json: Provides functions for working with JSON (JavaScript Object Notation) data.

import json

data = '{"name": "John", "age": 30}'
parsed_data = json.loads(data)
print(parsed_data['name']) # Output: John

person = {'name': 'Alice', 'age': 25}
json_data = json.dumps(person)
print(json_data) # Output: {"name": "Alice", "age": 25}

urllib: Offers modules for working with URLs and making HTTP requests.

import urllib.request

response = urllib.request.urlopen('https://www.example.com')
html = response.read()
print(html) # Output: HTML content of the webpage

These are just a few examples of the modules available in the Python Standard Library. The Standard Library contains numerous other modules covering areas such as regular expressions (re), file input/output (io), command-line arguments (argparse), and more.

To explore the Standard Library further, refer to the official Python documentation: https://docs.python.org/3/library/

The Python Standard Library is an invaluable resource that provides ready-to-use functionalities for various programming tasks. Understanding and utilizing the Standard Library will greatly enhance your ability to write efficient and powerful Python programs.



The dir() Function

The dir() function is a powerful built-in function in Python that returns a sorted list of names in the current scope or the attributes of an object. It allows you to explore the available attributes, methods, and variables associated with an object or module, providing insight into its functionality and usage.

Usage of the dir() Function:

The general syntax for using the dir() function is as follows:

dir([object])

When called without any argument (dir()), it returns a list of names in the current local scope.
When called with an object as an argument (dir(object)), it returns a list of names associated with that object.

Examples of Using the dir() Function:

Exploring Names in the Current Local Scope:

x = 5
y = "Hello, World!"

print(dir()) # Output: ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'x', 'y']

In this example, the dir() function is called without any argument. It returns a list of names in the current local scope, including the predefined names (__builtins__, __doc__, __loader__, __name__, __package__, __spec__) and the variables x and y defined by the user.

Exploring Attributes and Methods of an Object:

my_list = [1, 2, 3]

print(dir(my_list))

In this example, the dir() function is called with the my_list object as an argument. It returns a list of attributes and methods associated with the list object, such as append(), clear(), count(), extend(), and more.

Using dir() with Modules:

import math

print(dir(math))

In this example, the dir() function is called with the math module as an argument. It returns a list of names associated with the math module, including mathematical functions like sqrt(), sin(), cos(), constants like pi, and more.

Using dir() with Custom Objects:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
print(f"Hello, my name is {self.name}.")

person = Person("Alice", 25)

print(dir(person))

In this example, the dir() function is called with the person object, which is an instance of the Person class. It returns a list of names associated with the person object, including the name and age attributes and the greet() method.

Common Uses of the dir() Function:

  • Exploring available attributes and methods of an object to understand its functionality.
  • Using it for introspection and debugging purposes.
  • Dynamically accessing and manipulating object attributes or methods based on their names.

It's worth noting that the dir() function returns all the available names, including built-in attributes and methods, which may not always be relevant to your specific use case. Therefore, understanding the purpose and functionality of the object or module is crucial for interpreting the results of dir().

The dir() function is a valuable tool for exploring objects, modules, and the current local scope. By utilizing dir(), you can gain insights into the attributes and methods available, helping you effectively work with Python's built-in functionalities and your custom objects.

Videos for Module 11 - Python Modules

11-1: Introducing Modules in Python (1:29)

11-2: What is a Module? (1:14)

11-3: Benefits of Using Modules in Python (3:33)

11-4: Getting Information about Python Modules (7:53)

11-5: Importing and Using a Module (2:56)

11-6: Creating and Using Custom Modules in Python (6:36)

11-7: A11 Code Walkthrough (4:33)

Key Terms for Module 11 - Python Modules

No terms have been published for this module.

Quiz Yourself - Module 11 - Python Modules

Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.

Skip to the Next Question 

Activities for this Module

S11 - Picasso Module

Note: Sandbox assignments are designed to be formative activities that are somewhat open-ended. To get the most value, spend some time playing around as you code.

Modules are something we’ve already been using throughout this course.  As you know, they allow us to easily expand the basic functionality of Python. For this sandbox, we’re going to channel our inner Picasso using a custom module that I’ve created for you.

First, download and install the following file, and put it in your main project directory in PyCharm.  You should be able to drag it in directly from your desktop or your “downloads” folder.

Picasso Module File

Next, create a new Python file in the same folder, and paste in the following code:

import picasso as p
import turtle

t = turtle.Turtle()
p.draw_nose(t)
p.moveTurtle(t,-50,50)
p.draw_left_eye(t)
p.moveTurtle(t,100,0)
p.draw_right_eye(t)

turtle.done()

If you run the code, it should draw a very simple face.  Each time, you run it, the face should be slightly different.

If you open the picasso.py module, you’ll see that in addition to the functions we’ve used in our little program, there are more functions, for drawing ears and a mouth as well.

The first part of this sandbox challenge is to add code to your main script to complete the face with ears and a mouth.  

The second part of the challenge is a little trickier. See if you can add an additional function to the Picasso module using the existing face parts as a guide.  Your new function should draw some funny hair on top of the face. Once you add your function to the module, add a few lines of code to your main code file to call the function and draw the hair.
Take a screenshot of your finished face, and post it to the forum.

A11 - Rock, Paper, MODULES

The Challenge

for A11, the challenge is to create a custom module that incorporates at least two major pieces of functionality into functions within that module.  The size and complexity of your main program should be SIGNIFICANTLY reduced as a result.  Use the Rock, Paper, Scissors program code for this assignment. 

Constraints / Success Criteria

Your script must conform to the following:

  • The main structure of the program should be in your main script.
  • Your module should have a function that returns the computer's guess.
  • Your module should have a function that takes a user guess and a computer guess and returns the winner.
  • All code must be commented.
  • Use only what we have covered in this class up to this point

Submission Type

Please submit the complete program as two .py files.