Skip to content

Commit 221f636

Browse files
Add the generators tutorial's scripts and README (#916)
Co-authored-by: realpython-bot <12371494+realpython-bot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 539b1fa commit 221f636

6 files changed

Lines changed: 153 additions & 0 deletions

File tree

‎generators/README.md‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# How to Use Generators and yield in Python
2+
3+
This folder provides the code examples for the Real Python tutorial [How to Use Generators and yield in Python](https://realpython.com/introduction-to-python-generators/).
4+
5+
The scripts only use Python's standard library. They read `techcrunch.csv` from the current working directory, so run them from inside this folder:
6+
7+
```shell
8+
$ python data_pipeline.py
9+
Total series A fundraising: $4380015000
10+
```
11+
12+
Each script holds the code from one section of the tutorial:
13+
14+
| File | Tutorial section |
15+
| --- | --- |
16+
| `csv_reader.py` | Example 1: Reading Large Files |
17+
| `infinite_sequence.py` | Example 2: Generating an Infinite Sequence |
18+
| `palindromes.py` | Example 3: Detecting Palindromes |
19+
| `advanced_gen.py` | Using Advanced Generator Methods |
20+
| `data_pipeline.py` | Creating Data Pipelines With Generators |
21+
| `techcrunch.csv` | The data set for Example 1 and the data pipeline |
22+
23+
`infinite_sequence.py` and `palindromes.py` run forever, so press <kbd>Ctrl</kbd>+<kbd>C</kbd> to stop them. `advanced_gen.py` takes the generator method to demonstrate as an argument:
24+
25+
```shell
26+
$ python advanced_gen.py send # Runs until you press Ctrl+C
27+
$ python advanced_gen.py throw # Stops with a ValueError
28+
$ python advanced_gen.py close # Stops with StopIteration
29+
```

‎generators/advanced_gen.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import sys
2+
3+
4+
def is_palindrome(num):
5+
# Skip single-digit inputs
6+
if num // 10 == 0:
7+
return False
8+
temp = num
9+
reversed_num = 0
10+
while temp != 0:
11+
reversed_num = (reversed_num * 10) + (temp % 10)
12+
temp = temp // 10
13+
if num == reversed_num:
14+
return True
15+
else:
16+
return False
17+
18+
19+
def infinite_palindromes():
20+
num = 0
21+
while True:
22+
if is_palindrome(num):
23+
i = yield num
24+
if i is not None:
25+
num = i
26+
num += 1
27+
28+
29+
def use_send():
30+
# Press Ctrl+C to stop the loop
31+
pal_gen = infinite_palindromes()
32+
for i in pal_gen:
33+
print(i)
34+
digits = len(str(i))
35+
pal_gen.send(10 ** (digits))
36+
37+
38+
def use_throw():
39+
pal_gen = infinite_palindromes()
40+
for i in pal_gen:
41+
print(i)
42+
digits = len(str(i))
43+
if digits == 5:
44+
pal_gen.throw(ValueError("We don't like large palindromes"))
45+
pal_gen.send(10 ** (digits))
46+
47+
48+
def use_close():
49+
pal_gen = infinite_palindromes()
50+
for i in pal_gen:
51+
print(i)
52+
digits = len(str(i))
53+
if digits == 5:
54+
pal_gen.close()
55+
pal_gen.send(10 ** (digits))
56+
57+
58+
def main():
59+
demos = {"send": use_send, "throw": use_throw, "close": use_close}
60+
choice = sys.argv[1] if len(sys.argv) > 1 else "close"
61+
demos[choice]()
62+
63+
64+
if __name__ == "__main__":
65+
main()

‎generators/csv_reader.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def csv_reader(file_name):
2+
for row in open(file_name, "r"):
3+
yield row
4+
5+
6+
csv_gen = csv_reader("techcrunch.csv")
7+
row_count = 0
8+
for row in csv_gen:
9+
row_count += 1
10+
print(f"Row count is {row_count}")

‎generators/data_pipeline.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
file_name = "techcrunch.csv"
2+
lines = (line for line in open(file_name))
3+
list_line = (s.rstrip().split(",") for s in lines)
4+
cols = next(list_line)
5+
company_dicts = (dict(zip(cols, data)) for data in list_line)
6+
funding = (
7+
int(company_dict["raisedAmt"])
8+
for company_dict in company_dicts
9+
if company_dict["round"] == "a"
10+
)
11+
total_series_a = sum(funding)
12+
print(f"Total series A fundraising: ${total_series_a}")

‎generators/infinite_sequence.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
def infinite_sequence():
2+
num = 0
3+
while True:
4+
yield num
5+
num += 1
6+
7+
8+
# Press Ctrl+C to stop the loop
9+
for i in infinite_sequence():
10+
print(i, end=" ")

‎generators/palindromes.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
def infinite_sequence():
2+
num = 0
3+
while True:
4+
yield num
5+
num += 1
6+
7+
8+
def is_palindrome(num):
9+
# Skip single-digit inputs
10+
if num // 10 == 0:
11+
return False
12+
temp = num
13+
reversed_num = 0
14+
while temp != 0:
15+
reversed_num = (reversed_num * 10) + (temp % 10)
16+
temp = temp // 10
17+
if num == reversed_num:
18+
return num
19+
else:
20+
return False
21+
22+
23+
# Press Ctrl+C to stop the loop
24+
for i in infinite_sequence():
25+
pal = is_palindrome(i)
26+
if pal:
27+
print(i)

0 commit comments

Comments
 (0)