Understanding Python Generator Functions: Syntax, Usage, and Practical Examples
Python generator functions, using the yield keyword, enable lazy evaluation and memory-efficient data processing, with examples covering basic syntax, differences from regular functions, Fibonacci sequence generation, large file reading, two-way communication via send(), and control methods like throw() and close(), highlighting their advantages.
Generator functions are a special type of function in Python that produce data on demand instead of loading all data into memory at once. They return values using the yield keyword and resume execution from the last paused point on each call. This mechanism makes generators well suited for handling large datasets, lazy evaluation, or infinite sequences.
✅ 1. Basic Syntax
def my_generator():
yield 1
yield 2
yield 3Usage:
gen = my_generator()
print(next(gen)) # 输出: 1
print(next(gen)) # 输出: 2
print(next(gen)) # 输出: 3Or iterate with a loop:
for value in my_generator():
print(value)✅ 2. Difference from Regular Functions
(Illustrative diagram omitted for brevity.)
✅ 3. Example: Fibonacci Sequence Generator
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# Usage
for num in fibonacci(10):
print(num)
# Output:
0
1
1
2
3
5
8
13
21
34✅ 4. Example: Reading Large Files
Generators are ideal for reading large files line‑by‑line without loading the entire file into memory:
def read_large_file(file_path):
with open(file_path, 'r') as f:
for line in f:
yield line.strip()
# Usage
for line in read_large_file("large.txt"):
print(line)✅ 5. send() Method and Two‑Way Communication
def echo():
while True:
received = yield
print(f"收到: {received}")
gen = echo()
next(gen) # start generator
gen.send("你好")
# Output:
收到: 你好✅ 6. throw() and close()
def demo_gen():
try:
yield "正常"
yield "继续"
except GeneratorExit:
print("生成器正在关闭")
gen = demo_gen()
print(next(gen)) # 正常
gen.close() # 生成器正在关闭✅ 7. Summary of Advantages
Memory saving: does not generate all data at once.
Lazy computation: generates data on demand.
Simplifies code structure: replaces complex state‑machine logic.
Suitable for large data‑stream processing such as logs, network requests, sensor data, etc.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.