Python Context Managers
In this page:
with expression as variable:
# use resource; cleanup is automatic
class ContextClass:
def __enter__(self):
return resource
def __exit__(self, exc_type, exc_value, traceback):
# cleanup
with Statement
एक context manager गारंटी देता है कि किसी block के चारों ओर setup और teardown code भरोसे के साथ चलता है -- with statement ही Python को block से पहले वह setup और उसके बाद teardown call करने देता है, भले ही block के अंदर का code बीच में कोई exception raise कर दे।
उदाहरण: The with Statement
with open("data.txt", "w") as f:
f.write("hello")
print("File automatically closed after the block") # teardown ran even without an explicit close()
Class-Based Context Managers
अपना context manager एक class के रूप में लिखने का मतलब है __enter__ (जो with block शुरू होने पर चलता है, अक्सर इस्तेमाल के लिए कोई resource लौटाता है) और __exit__ (जो block खत्म होने पर चलता है, उस resource को release करने का ज़िम्मेदार) implement करना -- यह इसे बनाने का पारंपरिक, explicit तरीका है।
उदाहरण: Class-Based Context Managers
class Resource:
def __enter__(self): # runs when the with block starts
print("Acquiring resource")
return self
def __exit__(self, exc_type, exc_val, exc_tb): # runs when the with block ends
print("Releasing resource")
with Resource():
print("Using resource")
Generator-Based Context Managers
contextlib का @contextmanager decorator आपको पूरी class की बजाय एक single generator function के रूप में context manager लिखने देता है -- yield से पहले का code __enter__ का काम करता है, yield किया गया value वह है जो 'as x' capture करता है, और yield के बाद का code __exit__ का काम करता है।
उदाहरण: Generator-Based Context Managers
from contextlib import contextmanager
@contextmanager
def resource():
print("Acquiring") # code before yield acts like __enter__
yield "resource" # this value is what "as r" captures
print("Releasing") # code after yield acts like __exit__
with resource() as r:
print("Using", r)
Context के अंदर Exceptions Handle करना
अगर with block ने कोई exception raise किया हो, तो __exit__ को उसका type, value, और traceback arguments के रूप में मिलता है -- __exit__ से True लौटाना Python को बताता है कि exception handle हो गया और उसे दबा देना चाहिए, जबकि False (या कुछ नहीं) लौटाना cleanup चलने के बाद उसे सामान्य रूप से propagate होने देता है।
उदाहरण: Handling Exceptions inside context
class Suppressor:
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Suppressing:", exc_val)
return True # tells Python the exception was handled
with Suppressor():
raise ValueError("boom") # caught and suppressed by __exit__
print("Execution continues")
Context Managers के व्यावहारिक उपयोग
Context managers उन हर चीज़ के लिए standard tool हैं जिन्हें सफलता या विफलता के बावजूद guaranteed cleanup चाहिए -- file handles, network sockets, database connections, और locks आमतौर पर इसी तरह लपेटे जाते हैं ताकि resources कभी गलती से खुले न रह जाएँ।
उदाहरण: Practical Uses of Context Managers
with open("data.txt", "w") as f:
f.write("saved")
with open("data.txt") as f:
print(f.read()) # file is guaranteed to be closed after each block
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: