Python Generators
In this page:
def generator_name():
yield value1
yield value2
for item in generator_name():
# use item
Generator क्या है?
एक generator function दिखने में एक साधारण function जैसा है पर return की बजाय yield इस्तेमाल करता है, और उसे call करना तुरंत function body नहीं चलाता -- यह एक generator object लौटाता है जो मांगे जाने पर ही एक बार में एक value produce करता है।
उदाहरण: What is a Generator?
def my_gen():
yield 1 # yield instead of return makes this a generator function
yield 2
g = my_gen()
print(type(g)) # generator object, body hasn't run yet
print(next(g)) # runs up to the first yield
yield Keyword
हर बार yield execute होता है, function ठीक वहीं रुक जाता है, yield किया गया value लौटा देता है, और अपनी पूरी local state (variables, loops में position) याद रखता है -- next() की अगली call function को शुरू से चलाने की बजाय ठीक उस yield के बाद से resume करती है।
उदाहरण: The yield Keyword
def counter():
n = 1
while True:
yield n # pauses here, remembering n
n += 1
c = counter()
print(next(c)) # first call, prints 1
print(next(c)) # second call, resumes after yield and prints 2
Generator Expressions
एक generator expression -- (x*2 for x in range(10)) -- list comprehension जैसे लगभग एक जैसे syntax से एक generator बनाता है, पर square brackets की बजाय parentheses के साथ, और results की पूरी list कभी memory में बनाए बिना।
उदाहरण: Generator Expressions
squares = (x * x for x in range(5))
print(list(squares))
Generator State और Lifecycle
जब कोई generator function अपने body के अंत तक चलता है या plain return statement पर पहुँचता है, तो Python अपने आप यह संकेत देने के लिए StopIteration raise करता है कि अब produce करने के लिए कुछ बचा नहीं -- यह बिल्कुल वही signal है जिसे for loop किसी भी iterator पर iterate करते समय देखता है।
उदाहरण: Generator State and Lifecycle
def one_value():
yield "only value"
g = one_value()
print(next(g))
try:
next(g) # generator body has finished
except StopIteration:
print("Generator exhausted")
Performance Benefits
चूँकि generator पहले से पूरी list बनाने की बजाय एक बार में एक value compute और yield करता है, यह चाहे कितनी भी values आख़िर में produce करे, हमेशा एक निश्चित, छोटी मात्रा में memory इस्तेमाल करता है -- यह उन datasets को stream करने के लिए आदर्श है जो RAM में आराम से नहीं समातीं।
उदाहरण: Performance Benefits
import sys
list_version = [x for x in range(1000)] # builds the entire list upfront
gen_version = (x for x in range(1000)) # produces values lazily, one at a time
print(sys.getsizeof(list_version) > sys.getsizeof(gen_version))
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: