Python Zero to Heros

Online Absolute Beginner Python Tutorials 

Every Sunday 2pm (UK time/ BST)

Get this slide deck:

slides.com/cheukting_ho/python-generators

Recap

Beginner topics:

Python objects - int, float, str, list, dict, bool

Control flows - if-else, for loop, while loop

Functions, modeuls, classes and decorators

strings operations and regex with re

Testing:

pytest with fixtures and mock

property-based testing

python linters & auto-formatters

TDD

Intermedite topics:

Iterators

What is Generator?

 

Generator functions allow you to declare a function that behaves like an iterator, i.e. it can be used in a for loop.

 

Python generators are a simple way of creating iterators.

Compare to implement a class with __iter__() and __next__() method.

 

 

def firstn(n):
	num = 0
	while num < n:
		yield num
		num += 1

Differences between Generator function and Normal function

https://www.programiz.com/python-programming/generator

  • Generator function contains one or more yield statements.
  • When called, it returns an object (iterator) but does not start execution immediately.
  • Methods like __iter__() and __next__() are implemented automatically. So we can iterate through the items using next().
  • Once the function yields, the function is paused and the control is transferred to the caller.
  • Local variables and their states are remembered between successive calls.
  • Finally, when the function terminates, StopIteration is raised automatically on further calls.

Sending to generator

 

The send() method resumes the generator and sends a value that will be used to continue with the next yield. The method returns the new value yielded by the generator.

- https://stackabuse.com/python-generators/

def numberGenerator(n):
     number = yield
     while number < n:
         number = yield number 
         number += 1

g = numberGenerator(10)    # Create our generator
next(g)                    # 
print(g.send(5))

Python 3.3+ : yield from

def generator1():
    for item in generator2():
        yield item
def generator1():
    yield from generator2()

Next week:
Async

Sunday 2pm (UK time/ BST)

This week no Mid Meet Py because:

Python Generators

By Cheuk Ting Ho

Python Generators

  • 277
Loading comments...

More from Cheuk Ting Ho