Menu
Coddy logo textTech

מנהלי הקשר

חלק מהיחידה תכנות מונחה עצמים במסלול ה-Python של Coddy. שיעור 41 מתוך 64.

מנהלי הקשר מאפשרים לך להקצות ולשחרר משאבים בדיוק כשצריך. הם מבטיחים ניקוי נאות גם אם מתרחשות שגיאות.

הנה הדוגמה הנפוצה ביותר לשימוש במשפט with:

with open('example.txt', 'w') as file:
    file.write('Hello, world!')
# הקובץ נסגר כאן באופן אוטומטי

הקובץ נסגר אוטומטית לאחר הבלוק, גם אם מתרחש חריג.

צרו מנהל הקשר משלכם באמצעות מימוש המתודות __enter__ ו-__exit__:

class MyContext:
    def __enter__(self):
        print("Entering the context")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exiting the context")
        return False  # אל תדכא חריגות

השתמש במנהל ההקשר המותאם אישית שלך:

with MyContext() as ctx:
    print("Inside the context")

פלט:

Entering the context
Inside the context
Exiting the context

צרו מנהל הקשר מעשי יותר לחיבורי מסד נתונים:

class DatabaseConnection:
    def __init__(self, db_name):
        self.db_name = db_name
        self.connection = None
    
    def __enter__(self):
        print(f"Connecting to {self.db_name}")
        self.connection = f"Connection to {self.db_name}"
        return self.connection
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"Closing connection to {self.db_name}")
        self.connection = None

with DatabaseConnection("users_db") as conn:
    print(f"Using {conn}")
    print("Performing database operations...")

טיפול בחריגות במנהלי הקשר:

class SafeContext:
    def __enter__(self):
        print("Setting up resources")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Cleaning up resources")
        if exc_type:
            print(f"An exception occurred: {exc_val}")
        return False  # אל תמנע את העברת החריגה

with SafeContext():
    print("Working with resources")
    # raise ValueError("Something went wrong")  # הסר את סימון ההערה כדי לבדוק

פלט:

Connecting to users_db
Using Connection to users_db
Performing database operations...
Closing connection to users_db
Setting up resources
Working with resources
Cleaning up resources

המתודה __exit__ מקבלת שלושה פרמטרים:

  • exc_type: סוג החריגה (או None)
  • exc_val: ערך החריגה (או None)
  • exc_tb: מעקב המחסנית של החריגה (או None)

נקודה חשובה: מנהלי הקשר משתמשים בשיטות __enter__ ו־__exit__ כדי לנהל משאבים. המשפט with קורא לשיטות האלה באופן אוטומטי, ומבטיח הכנה וניקוי נאותים. הדבר שימושי במיוחד עבור קבצים, חיבורי מסד נתונים ומשאבים אחרים שדורשים ניקוי מובטח.

challenge icon

אתגר

קל

באתגר הזה תממשו מחלקה של מנהל הקשר שמודדת את הזמן שחלף בין הכניסה לבלוק הקשר לבין היציאה ממנו.

  • timer.py - מכיל את המימוש של המחלקה Timer (זה הקובץ שתערכו)
  • driver.py - מכיל מקרי בדיקה מקיפים (אין לשנות)

ממשו את מנהל ההקשר Timer בקובץ timer.py בהתאם להערות TODO. המחלקה צריכה:

  1. לתעד את שעת ההתחלה בעת הכניסה להקשר
  2. לתעד את שעת הסיום בעת היציאה ממנו
  3. לחשב ולהציג את הזמן שחלף

נסו בעצמכם

from timer import Timer
import time

# מטפל במקרי בדיקה
test_case = input()

if test_case == "basic_test":
    # בדיקת תפקוד בסיסי
    with Timer():
        # הדמיית עבודה כלשהי
        time.sleep(2)  # פעולה זו גורמת לתוכנית להמתין 2 שניות

elif test_case == "nested_contexts":
    # בדיקת מנהלי הקשר מקוננים
    with Timer():
        time.sleep(1)
        with Timer():
            time.sleep(1)

elif test_case == "exception_handling":
    # בדיקת טיפול בחריגות בתוך הקשר
    try:
        with Timer():
            time.sleep(1)
            raise ValueError("Test exception")
    except ValueError as e:
        print(f"Caught exception: {e}")

elif test_case == "zero_sleep":
    # בדיקה עם השהיה מזערית
    with Timer():
        time.sleep(0.001)

elif test_case == "multiple_timers":
    # בדיקת כמה טיימרים בזה אחר זה
    with Timer():
        time.sleep(1)
    
    with Timer():
        time.sleep(0.5)
    
    with Timer():
        time.sleep(2)

elif test_case == "as_decorator":
    # בדיקת טיימר בהקשר של פונקציה
    def timed_function():
        with Timer():
            time.sleep(2)
    
    timed_function()

else:
    # בדיקת ברירת מחדל - תפקוד בסיסי
    with Timer():
        # הדמיית עבודה כלשהי
        time.sleep(2)  # פעולה זו גורמת לתוכנית להמתין 2 שניות
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה תכנות מונחה עצמים

תרגלו בעצמכם: קומפיילר Python אונליין