Sammy’s Generators in Python

Skyler Lewis
Development at Canopy Tax
3 min readAug 20, 2018

Python generators are versatile tools that offer unique capabilities for managing data flow and optimizing code efficiency.

Imagine it’s lunchtime, and Sammy Sandwiches’ food truck pulls into the parking lot next to your office. A line quickly forms as people eagerly await their favorite sandwiches.

import time

# Function to get customers and their orders
def get_customers():
return [('Bob', 'Ham Sandwich'), ('Paul', 'Grilled Cheese'), ('Sally', 'Chicken Croissant')]

customers = get_customers()

# Function to make sandwiches for each customer and deliver them
def make_sandwiches():
completed_sandwiches = []
for customer in customers:
time.sleep(1) # Time taken to make the sandwich
completed_sandwiches.append((customer[0], customer[1]))
return completed_sandwiches

sandwiches = make_sandwiches()

# Deliver the sandwiches
for sandwich in sandwiches:
print('Delivering sandwich:', sandwich[1], 'for', sandwich[0])

Initially, Sammy’s workflow involved taking all the orders first, preparing the sandwiches, and then delivering them. However, as his food truck gained popularity, the long wait times left customers hungry.

To improve efficiency, Sammy decides to alter his approach. He starts taking orders and delivering sandwiches as soon as they are ready, reducing wait times significantly.

import time

# Function to make sandwiches for each customer and deliver them immediately
def make_sandwiches():
for customer in customers:
time.sleep(1) # Time taken to make the sandwich
# Now we will "hand off" the sandwhich
# to the next customer before starting to make the next one.
yield (customer[0], customer[1])

sandwiches = make_sandwiches()

# Deliver the sandwiches
for sandwich in sandwiches:
print('Delivering sandwich:', sandwich[1], 'for', sandwich[0])

While this method improves efficiency, it still doesn’t address the issue of customers having to wait for others to order before receiving their food.

Sammy’s final solution is to take one order, prepare the sandwich, and deliver it before moving on to the next customer.

import time

# Function to make sandwiches for each customer and deliver them immediately
def make_sandwiches():
for customer in get_next_customer():
time.sleep(1) # Time taken to make the sandwich
yield (customer[0], customer[1])

# Function to yield the next customer in the queue
def get_next_customer():
list_of_customers = [('Bob', 'Ham Sandwich'), ('Paul', 'Grilled Cheese'), ('Sally', 'Chicken Croissant')]
for an_order in list_of_customers:
yield an_order

sandwiches = make_sandwiches()

# Deliver the sandwiches
for sandwich in sandwiches:
print('Delivering sandwich:', sandwich[1], 'for', sandwich[0])

By understanding and optimizing his operation, Sammy achieves success. Generators, like the ones used in Sammy’s sandwich-making process, help streamline workflows and remove bottlenecks.

Generators not only pause execution to extract values but also allow sending values to the yielding function. This can be demonstrated with the following example:

def make_sandwich():
customer = yield 'No Customer'
print(customer)

action = make_sandwich()
print(next(action))
print(action.send(13))

Running the above example produces ‘No Customer’ followed by 13, showcasing the communication between the generator and the caller.

Another useful feature of generators is pipelining, which allows for cleaner, more readable code. Instead of manually iterating over multiple generators, the yield from statement can be used:

def retrieve_all_users():
yield from employees()
yield from customers()

for user in retrieve_all_users():
print(user)

Generators form the basis of many optimizations, including Asyncio, making them essential tools in Python development.

These adjustments aim to enhance clarity and readability while maintaining the informative content of your article. Let me know if you need further clarification or have any specific questions!

Skyler Lewis makes no claims to expertise or exactness of the information presented and may not reflect the opinions of the owners or advertisers. Parental guidance isn’t recommended. Any rebroadcast, retransmission, or account of this article, without the express written consent of Major League Baseball, is not prohibited. Use as directed. May cause sleepiness, headaches, backaches, or thoughts of bacon wrapped shrimp.

--

--