top of page

Python Practice Set (Part 19): Decorators and Generators

Python practice series
Python practice series

Welcome to Part 19 of our Python practice series! If you're ready to move beyond the fundamentals and start writing truly elegant and efficient code, this session is for you. We'll be exploring two powerful, advanced concepts:

  • Decorators: A way to add new functionality to an existing function without modifying its source code.

  • Generators: A special type of function that allows you to work with large sequences of data without storing them all in memory at once.

Mastering these will not only make you a better programmer but also prepare you for more complex real-world challenges.


1. The Simple Function Wrapper (Your First Decorator)


Write a decorator called log_function_call. This decorator should print a message before the decorated function is called and another message after it completes.

  • Before message: --- Calling function: [function_name] ---

  • After message: --- Function [function_name] finished --- Apply this decorator to a simple say_hellofunction that just prints "Hello, Python!".


2. A Practical Decorator: The Execution Timer


Create a decorator named timing_decorator that measures and prints the execution time of any function it decorates.

  1. It should record the time before the function runs.

  2. It should record the time after the function runs.

  3. It should print the difference in a message like: Function [function_name] took X.XXXX seconds to run.

Hint: Use the time module. The decorator will need to accept args and *kwargs to work with any function.


3. The Countdown (Your First Generator)


Write a generator function called countdown_generator that takes a number n as an argument. When iterated over, it should yield the numbers from n down to 1. Use a for loop to iterate through the generator and print each number.


4. Reading a Large File Efficiently (Generator for Memory)


Generators are perfect for processing large files because they read one line at a time instead of loading the entire file into memory. Write a generator function read_large_file that takes a filename and yields each line from the file.

First, create a sample file my_large_file.txt. Then, use a for loop on your generator to process the file and print each line.


5. Filtering with a Generator Expression


A generator expression has a syntax similar to a list comprehension but uses parentheses (). It creates a generator object without needing a full def function. You have a list of numbers: data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. Create a generator expression that yields the square of only the even numbers in the list. Iterate over the generator and print each resulting value.




Comments


bottom of page