Book Image

Expert Python Programming

By : Tarek Ziadé
Book Image

Expert Python Programming

By: Tarek Ziadé

Overview of this book

<p>Python is a dynamic programming language, used in a wide range of domains by programmers who find it simple, yet powerful. From the earliest version 15 years ago to the current one, it has constantly evolved with productivity and code readability in mind.<br /><br />Even if you find writing Python code easy, writing code that is efficient and easy to maintain and reuse is not so straightforward. This book will show you how to do just that:&nbsp; it will show you how Python development should be done. Python expert Tarek Ziadé takes you on a practical tour of Python application development, beginning with setting up the best development environment, and along the way looking at agile methodologies in Python, and applying proven object-oriented principles to your design.</p>
Table of Contents (21 chapters)
Credits
Foreword
About the Author
About the Reviewers
Preface
Index

Iterators and Generators


An iterator is nothing more than a container object that implements the iterator protocol. It is based on two methods:

  • next, which returns the next item of the container

  • __iter__, which returns the iterator itself

Iterators can be created with a sequence using the iter built-in function, for example:

>>> i = iter('abc')
>>> i.next()
'a'
>>> i.next()
'b'
>>> i.next()
'c'
>>> i.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

When the sequence is exhausted, a StopIteration exception is raised. It makes iterators compatible with loops since they catch this exception to stop cycling. To create a custom iterator, a class with a next method can be written, as long as it provides the special method __iter__ that returns an instance of the iterator:

>>> class MyIterator(object):
...     def __init__(self, step):
...         self.step = step
...     def next(self...