Skip to content

Chapter 7 of 7

Modules, Exceptions, and Advanced Features

Python's modular system allows you to organize and reuse code across files and projects. You can import a module with import module and access its functions as module.func, or bring specific names into scope with from module import func. The standard library provides many built-in modules such as math for mathematical functions, os for operating system interactions, and sys for system-specific parameters. A package is a directory containing an __init__.py file along with modules, and you can import from it using from pkg.module import func.

Exception handling in Python uses the try/except construct. You place code that might raise an error inside a try block, follow it with except clauses that catch specific exception types like ValueError, and optionally add an else block for code that runs only if no exception occurred, plus a finally block for cleanup that always runs. To signal an error condition yourself, you can use the raise statement, such as raise ValueError('message').

Python also offers several advanced features for concise and expressive code. Lambda functions are anonymous functions defined with a single expression, like lambda x: x*2, and they are commonly used with map(), filter(), and sorted(). List comprehensions provide a compact way to build lists; for example, [x*2 for x in range(5) if x%2==0] generates doubled values of even numbers from 0 to 4. Generators are functions that use yield to produce values lazily, one at a time, which saves memory when working with large sequences. Decorators are functions that wrap other functions to modify their behavior, applied with the @decorator syntax above the function definition; common examples include @staticmethod and @classmethod. Context managers handle resource setup and cleanup automatically, as seen in with open('file.txt', 'r') as f:, and you can create custom context managers using classes with __enter__ and __exit__ methods or with the @contextmanager decorator. Finally, async and await enable concurrent programming through the asyncio module, allowing non-blocking I/O operations; an async def coroutine can pause with await asyncio.sleep(1) while other tasks run.

All chapters
  1. 1Introduction to Python
  2. 2Variables, Types, and Operators
  3. 3Control Flow
  4. 4Functions
  5. 5Data Structures
  6. 6Object-Oriented Programming
  7. 7Modules, Exceptions, and Advanced Features

Drill it

Reading is not remembering. These come from the Python Programming deck:

Q

What is Python?

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple paradigms including procedural, object-o...

Q

Who created Python and when?

Guido van Rossum created Python, with the first version released in 1991. It was named after the British comedy series Monty Python.

Q

What are the key features of Python?

Python features dynamic typing, automatic memory management, extensive standard library, and cross-platform compatibility. It emphasizes code readability with s...

Q

How do you run a Python script from the command line?

Save the code in a file with .py extension, then run python filename.py in the terminal. Use python3 if Python 2 is also installed.