Python Generators - Talk at PySthlm meetup #15

Post on 10-May-2015

394 views 1 download

Tags:

description

Describing how you can use python generator functions to process a file without loading it all in memory before starting

Transcript of Python Generators - Talk at PySthlm meetup #15

Python Generators

PySthlm Meetup #15 – Python Best Practices – Oct 31, 2013

Samuel Lampatwitter.com/smllmp

The “normal” (bad) way

The “normal” (bad) way

New temporary data structures created and kept in memory

== BAD!!!

Using Generator function

Using Generator function

A yield (“return”) for every iteration, so it can

be used immediately without temp data structure

== GOOD!

Using Generator function

A yield (“return”) for every iteration, so it can

be used immediately without temp data structure

== GOOD!

So, this is the generator function

Using Generator function

A yield (“return”) for every iteration, so it can

be used immediately without temp data structure

== GOOD!

So, this is the generator function … which can be

iterated over, like this ...

Using list-comprehension syntax

Using list-comprehension syntax

Here, the generator functionIs defined in one row

Chaining generator functions

Chaining generator functions

Creds and more info:

● David Beazleys Python Generator intro:

→dabeaz.com/generatorsDavid Beazley on twitter: @dabeaz

Thank you!

Samuel LampaG+: gplus.to/samltwitter: @smllmp

Blog: saml.rilspace.org

Developer @ www.uppmax.uu.sewww.farmbio.uu.sewww.rilpartner.se