← Back to Python Course | Chapter 11: Advanced Python | Lesson 4 of 12

Python Context Managers

Context manager आपके लिए कुछ set up करता है और साफ़ करता है, जैसे कोई helper जो दरवाज़ा खोलता है और आपके पीछे बंद कर देता है। with statement इसे इस्तेमाल करता है ताकि कुछ भी खुला न रह जाए।
Syntax
python
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

python
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

python
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

python
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

python
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

python
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.