When and how to refactor your code into generators

May 26, 2023 from 11:45 am to 12:15 pm

Speaker: Jan-Hein Bührman

May 26, 2023 from 10:15 am to 10:45 am

  • Camera 1 (64 people)

Have you ever found yourself coding variations of a loop construct where fragments of the loop code were exactly the same between the variations? Or, in an attempt to factor out these common parts, you ended up with a loop construct containing a lot of conditional code for varying start, stop, or selection criteria?

You might have felt that the end result just didn’t look right. Because of the duplicated parts in your code, you noticed that the code didn’t conform to the DRY (Don’t Repeat Yourself) principle. Or, after an attempt to combine the variations into a single loop, with consequently a lot of conditional code, your inner voice told you that the resulting code had become too complex and difficult to maintain.

This talk will show you a way out of this situation. It demonstrates how you can create a generator function that implements only the common parts of your loop construct. Subsequently you will learn how you can combine this generator function with distinct hand-crafted functions or building blocks from the standard library itertools module or the more-itertools package.

As an example, imagine you’d need to implement some varying functionality based on the Fibonacci sequence. This talk shows you how it would look like before and after you’ve refactored it into a pipeline of generators.

After having seen this pattern, you will recognize more quickly when this kind of refactoring helps you to create more maintainable and more Pythonic code.

About Jan-Hein Bührman

Jan-Hein is a software engineer who witnessed Python’s first baby steps up very close, and loves programming in Python since then. While he worked in different software development roles, he always kept an eye on its development.

After he has founded a dedicated Python practice within Ordina, the company he works for, he’s now back at the work that leaves him with a positive energy balance at the end of the day: programming in Python!