0% found this document useful (0 votes)
3 views8 pages

Python Generators and Decorators Guide

The document explains generator functions in Python, highlighting their ability to yield values and resume execution, which allows for efficient value generation over time. It contrasts generators with traditional functions by noting that they do not return a value and exit but instead support an iteration protocol. An example is provided with the range() function, which generates numbers without creating a full list in memory.

Uploaded by

nayanrajani2709
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views8 pages

Python Generators and Decorators Guide

The document explains generator functions in Python, highlighting their ability to yield values and resume execution, which allows for efficient value generation over time. It contrasts generators with traditional functions by noting that they do not return a value and exit but instead support an iteration protocol. An example is provided with the range() function, which generates numbers without creating a full list in memory.

Uploaded by

nayanrajani2709
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Generators

Decorators

● We've learned how to create functions with


def and the return statement.
● Generator functions allow us to write a
function that can send back a value and
then later resume to pick up where it left
off.
Decorators

● This type of function is a generator in


Python, allowing us to generate a
sequence of values over time.
● The main difference in syntax will be the
use of a yield statement.
Decorators

● When a generator function is compiled


they become an object that supports an
iteration protocol.
● That means when they are called in your
code they don't actually return a value and
then exit.
Decorators

● Generator functions will automatically


suspend and resume their execution and
state around the last point of value
generation.
● The advantage is that instead of having to
compute an entire series of values up
front, the generator computes one value
waits until the next value is called for.
Decorators

● For example, the range() function doesn’t


produce an list in memory for all the
values from start to stop.
● Instead it just keeps track of the last
number and the step size, to provide a
flow of numbers.
Decorators

● If a user did need the list, they have to


transform the generator to a list with
list(range(0,10))
● Let’s explore how to create our own
generators!
Iterators and
Generators
Homework
Solutions

You might also like