Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 6

Using Python's Standard Library Modules

Recommended resources

Hello! Welcome to the final lesson in our "Python Fundamentals Refresher" module.

In our last lesson, we mastered the with statement for safely and cleanly handling files. This technique ensures that resources are managed automatically, which is a pattern you'll see often.

Today, we're going to explore how to expand Python's capabilities far beyond the built-in functions we've used so far. This lesson addresses the learning outcome: Import and use modules from Python's standard library. Think of modules as toolkits for specific jobs. Instead of building every tool from scratch, you can import a pre-built, expertly-crafted toolkit. This is the last core Python skill we'll cover before diving into the Django framework, where using modules is a daily activity.

1. What Are Modules and How Do We Use Them?

At its simplest, a module is a Python file (.py) containing functions, classes, and variables that you can use in other Python files. This allows you to organize your code into logical, reusable components.

Python gives you several ways to bring the code from a module into your current script. The keywords for this are import and from.

To get a clear, practical understanding of how this works, let's watch a video from Corey Schafer. He starts by showing how to import a simple custom module, which is a great way to grasp the core concept, before explaining the different import syntaxes.

Python Tutorial for Beginners 9: Import Modules and Exploring The Standard Library

This video explains what modules are and demonstrates the different ways to import them, including using aliases (as) and importing specific functions (from ... import ...).

Watch from the beginning to 06:20. Pay close attention to the different syntaxes and the discussion on why from module import * is generally discouraged.

To summarize the key import methods you just saw:

  • import module_name: Imports the entire module. You access its contents using dot notation (e.g., module_name.function_name). This is clear and avoids naming conflicts.
    import math
    print(math.sqrt(25)) # Output: 5.0
    
  • import module_name as alias: Imports the entire module but gives it a shorter, more convenient name. This is very common for modules with long names.
    import datetime as dt
    print(dt.datetime.now())
    
  • from module_name import item1, item2: Imports only specific items (functions, classes, etc.) from a module. You can use them directly without the module name prefix.
    from math import sqrt, pi
    print(sqrt(25)) # No 'math.' prefix needed
    print(pi)
    

2. The Python Standard Library: "Batteries Included"

One of Python's greatest strengths is its "batteries-included" philosophy. This means that when you install Python, you also get a huge collection of useful modules called the Python Standard Library. These modules provide tools for a vast range of common tasks, from mathematical calculations to working with dates and interacting with the operating system.

Using the standard library saves you an enormous amount of time and effort. The code is reliable, efficient, and well-tested. Let's explore some of the most useful modules you'll encounter as a web developer.

The video you just watched continues with a great tour of some of these modules.

Python Tutorial for Beginners 9: Import Modules and Exploring The Standard Library

Let's continue with Corey Schafer's tutorial. This segment introduces several key modules from the standard library, demonstrating their practical uses.

Watch from 13:33 to 17:59. Notice how these modules solve common problems that would be complex to code from scratch.

Here are a few of the most important modules for web development, with examples relevant to your goal of building a task manager application:

  • datetime: For handling dates and times. Essential for tracking when tasks are created, when they are due, or when a user last logged in.

    from datetime import datetime
    
    # Get the current time
    now = datetime.now()
    print(f"Task created at: {now}")
    
    # Format the time into a more readable string
    readable_time = now.strftime("%Y-%m-%d %H:%M:%S")
    print(f"Formatted time: {readable_time}")
    
  • random: For generating random numbers, choosing random elements, or shuffling sequences. Useful for creating unique IDs, verification codes, or default avatars.

    import random
    import string # Another useful standard library module!
    
    # Select a random priority for a new task
    priorities = ['Low', 'Medium', 'High']
    random_priority = random.choice(priorities)
    print(f"Randomly assigned priority: {random_priority}")
    
    # Generate a simple random confirmation code
    letters_and_digits = string.ascii_letters + string.digits
    confirmation_code = ''.join(random.choice(letters_and_digits) for i in range(8))
    print(f"Your confirmation code: {confirmation_code}")
    
  • os: For interacting with the operating system. In Django, it's frequently used to build file paths in a way that works across different operating systems (Windows, macOS, Linux).

    import os
    
    # A common pattern in Django's settings.py file
    # This creates a reliable path to a file regardless of the OS
    BASE_DIR = os.getcwd() # Gets the current working directory
    template_path = os.path.join(BASE_DIR, 'templates', 'index.html')
    
    print(f"Path to template file: {template_path}")
    
Test your understanding!

Your task manager application needs to set a default due date for new tasks to be 7 days from the day they are created. How would you use the datetime module to calculate this future date?

Hint: You'll need datetime.now() and another object from the datetime module called timedelta.

Show answer

You would use datetime.timedelta to represent a duration of 7 days and add it to the current date.

from datetime import datetime, timedelta

# Get the current date and time
now = datetime.now()

# Create a timedelta object representing 7 days
duration = timedelta(days=7)

# Calculate the due date
due_date = now + duration

print(f"Task created on: {now.strftime('%Y-%m-%d')}")
print(f"Default due date: {due_date.strftime('%Y-%m-%d')}")

A Deeper Look: How Does Python Find Modules?

Have you wondered how Python just knows where to find math or datetime when you type import?

When you import a module, Python searches for it in a specific list of directories. You can see this list by importing the sys module and printing sys.path. Python checks these locations in order:

  1. The directory of the script you are currently running.
  2. Directories listed in the PYTHONPATH environment variable (an advanced feature you can use to tell Python where else to look for code).
  3. The standard library installation directories.

This is why you can always import standard library modules and any .py files you create in the same folder as your main script. When we start our Django project, you'll see this in action as we import functions between different files within our project structure.


Conclusion

Congratulations on completing the "Python Fundamentals Refresher" module! You've rebuilt your foundation in Python, covering everything from basic data types to the elegant file handling and powerful module system we saw today.

Key Takeaways from this Lesson:

  • A module is a file of Python code that can be imported and reused.
  • You can use import module, import module as alias, or from module import item to bring code into your script.
  • The Python Standard Library is a vast collection of modules included with every Python installation, providing tools for countless common tasks.
  • Modules like datetime, random, and os are particularly important for web development and will be used frequently in our Django project.

Preview of the Next Lesson:

We are now ready to move on to Module 2: Object-Oriented Python Essentials. In our next lesson, we will learn to define classes with attributes and methods. This is the cornerstone of Object-Oriented Programming (OOP), the paradigm that modern frameworks like Django are built upon. Understanding classes will allow you to understand how Django models, views, and forms work, and it's the next critical step on your path to becoming a full-stack developer.