-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06-context-managers-cleanup.py
More file actions
1130 lines (887 loc) · 37.8 KB
/
06-context-managers-cleanup.py
File metadata and controls
1130 lines (887 loc) · 37.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Question: Implement context managers for proper resource cleanup and error handling.
Create context managers that handle file operations, database connections,
and custom resources with proper cleanup in case of exceptions.
Requirements:
1. Create a file manager context manager
2. Create a database connection context manager
3. Create a custom resource manager with cleanup
4. Demonstrate exception handling within context managers
5. Show proper resource cleanup in all scenarios
Example usage:
with FileManager('data.txt') as file:
file.write('Hello World')
with DatabaseManager('db.sqlite') as db:
db.execute('SELECT * FROM users')
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
#
# Tips for success:
# - Read the question carefully
# - Think about what classes and methods you need
# - Start with a simple implementation
# - Test your code step by step
# - Don't worry if it's not perfect - learning is a process!
#
# Remember: The best way to learn programming is by doing, not by reading solutions!
#
# Take your time, experiment, and enjoy the learning process!
# Try to implement your solution here:
# (Write your code below this line)
# HINT SECTION (Only look if you're really stuck!)
#
# Think about:
# - What are the __enter__ and __exit__ methods for?
# - How do you handle exceptions in __exit__?
# - What resources need cleanup?
# - How do you ensure cleanup happens even with exceptions?
#
# Remember: Start simple and build up complexity gradually!
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Import modules and create a basic file context manager
# ===============================================================================
# Explanation:
# Context managers use the __enter__ and __exit__ methods to manage resources.
# The __enter__ method sets up the resource, __exit__ cleans it up.
import os
import sqlite3
import tempfile
from typing import Optional, Any
class FileManager:
"""Context manager for file operations with automatic cleanup."""
def __init__(self, filename: str, mode: str = 'w'):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
"""Enter the context - open the file."""
print(f"Opening file: {self.filename}")
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - close the file."""
if self.file:
print(f"Closing file: {self.filename}")
self.file.close()
# Return False to propagate exceptions
return False
# What we accomplished in this step:
# - Created a basic file context manager
# - Implemented __enter__ and __exit__ methods
# - Added automatic file cleanup
# Step 2: Add database connection context manager
# ===============================================================================
# Explanation:
# Database connections also need proper cleanup. We'll create a context manager
# that handles database connections and ensures they're closed properly.
import os
import sqlite3
import tempfile
from typing import Optional, Any
class FileManager:
"""Context manager for file operations with automatic cleanup."""
def __init__(self, filename: str, mode: str = 'w'):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
"""Enter the context - open the file."""
print(f"Opening file: {self.filename}")
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - close the file."""
if self.file:
print(f"Closing file: {self.filename}")
self.file.close()
# Return False to propagate exceptions
return False
class DatabaseManager:
"""Context manager for database connections with automatic cleanup."""
def __init__(self, database_path: str):
self.database_path = database_path
self.connection = None
self.cursor = None
def __enter__(self):
"""Enter the context - establish database connection."""
print(f"Connecting to database: {self.database_path}")
self.connection = sqlite3.connect(self.database_path)
self.cursor = self.connection.cursor()
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - close database connection."""
if exc_type is None:
# No exception occurred, commit the transaction
print("Committing database transaction")
self.connection.commit()
else:
# Exception occurred, rollback the transaction
print(f"Exception occurred: {exc_value}")
print("Rolling back database transaction")
self.connection.rollback()
if self.cursor:
self.cursor.close()
if self.connection:
print("Closing database connection")
self.connection.close()
# Return False to propagate exceptions
return False
def execute(self, query: str, params: tuple = ()):
"""Execute a database query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.execute(query, params)
def fetchall(self):
"""Fetch all results from the last query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.fetchall()
def fetchone(self):
"""Fetch one result from the last query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.fetchone()
# What we accomplished in this step:
# - Added DatabaseManager context manager
# - Implemented transaction handling (commit/rollback)
# - Added database operation methods
# - Proper cleanup of database resources
# Step 3: Create custom resource manager with advanced cleanup
# ===============================================================================
# Explanation:
# Custom resources might need complex cleanup logic. We'll create a resource
# manager that handles multiple resources and demonstrates advanced cleanup.
import os
import sqlite3
import tempfile
import time
from typing import Optional, Any, List
class FileManager:
"""Context manager for file operations with automatic cleanup."""
def __init__(self, filename: str, mode: str = 'w'):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
"""Enter the context - open the file."""
print(f"Opening file: {self.filename}")
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - close the file."""
if self.file:
print(f"Closing file: {self.filename}")
self.file.close()
# Return False to propagate exceptions
return False
class DatabaseManager:
"""Context manager for database connections with automatic cleanup."""
def __init__(self, database_path: str):
self.database_path = database_path
self.connection = None
self.cursor = None
def __enter__(self):
"""Enter the context - establish database connection."""
print(f"Connecting to database: {self.database_path}")
self.connection = sqlite3.connect(self.database_path)
self.cursor = self.connection.cursor()
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - close database connection."""
if exc_type is None:
# No exception occurred, commit the transaction
print("Committing database transaction")
self.connection.commit()
else:
# Exception occurred, rollback the transaction
print(f"Exception occurred: {exc_value}")
print("Rolling back database transaction")
self.connection.rollback()
if self.cursor:
self.cursor.close()
if self.connection:
print("Closing database connection")
self.connection.close()
# Return False to propagate exceptions
return False
def execute(self, query: str, params: tuple = ()):
"""Execute a database query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.execute(query, params)
def fetchall(self):
"""Fetch all results from the last query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.fetchall()
def fetchone(self):
"""Fetch one result from the last query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.fetchone()
class CustomResourceManager:
"""Context manager for custom resources with complex cleanup logic."""
def __init__(self, resource_name: str, cleanup_delay: float = 0.1):
self.resource_name = resource_name
self.cleanup_delay = cleanup_delay
self.resources: List[str] = []
self.is_active = False
self.start_time = None
def __enter__(self):
"""Enter the context - acquire resources."""
print(f"Acquiring resource: {self.resource_name}")
self.start_time = time.time()
self.is_active = True
# Simulate acquiring multiple sub-resources
self.resources = [
f"{self.resource_name}_connection",
f"{self.resource_name}_buffer",
f"{self.resource_name}_lock"
]
for resource in self.resources:
print(f" - Acquired: {resource}")
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - release resources with proper cleanup."""
duration = time.time() - self.start_time if self.start_time else 0
print(f"Releasing resource: {self.resource_name} (used for {duration:.2f}s)")
if exc_type is not None:
print(f"Exception during resource usage: {exc_type.__name__}: {exc_value}")
print("Performing emergency cleanup...")
# Clean up resources in reverse order (LIFO)
for resource in reversed(self.resources):
try:
print(f" - Releasing: {resource}")
# Simulate cleanup delay
time.sleep(self.cleanup_delay)
except Exception as cleanup_error:
print(f" - Error releasing {resource}: {cleanup_error}")
self.is_active = False
self.resources.clear()
print(f"Resource cleanup completed: {self.resource_name}")
# Return False to propagate exceptions
return False
def use_resource(self, operation: str):
"""Simulate using the resource."""
if not self.is_active:
raise RuntimeError(f"Resource {self.resource_name} is not active")
print(f"Using {self.resource_name} for: {operation}")
return f"Result of {operation} on {self.resource_name}"
def get_status(self):
"""Get the current status of the resource."""
return {
'name': self.resource_name,
'active': self.is_active,
'resources_count': len(self.resources),
'uptime': time.time() - self.start_time if self.start_time else 0
}
# What we accomplished in this step:
# - Created CustomResourceManager with complex cleanup logic
# - Added multiple sub-resource management
# - Implemented proper cleanup order (LIFO)
# - Added resource status tracking and timing
# Step 4: Demonstrate context managers with exception handling
# ===============================================================================
# Explanation:
# Let's create demonstration functions that show how context managers handle
# both normal operations and exception scenarios.
import os
import sqlite3
import tempfile
import time
from typing import Optional, Any, List
class FileManager:
"""Context manager for file operations with automatic cleanup."""
def __init__(self, filename: str, mode: str = 'w'):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
"""Enter the context - open the file."""
print(f"Opening file: {self.filename}")
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - close the file."""
if self.file:
print(f"Closing file: {self.filename}")
self.file.close()
# Return False to propagate exceptions
return False
class DatabaseManager:
"""Context manager for database connections with automatic cleanup."""
def __init__(self, database_path: str):
self.database_path = database_path
self.connection = None
self.cursor = None
def __enter__(self):
"""Enter the context - establish database connection."""
print(f"Connecting to database: {self.database_path}")
self.connection = sqlite3.connect(self.database_path)
self.cursor = self.connection.cursor()
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - close database connection."""
if exc_type is None:
# No exception occurred, commit the transaction
print("Committing database transaction")
self.connection.commit()
else:
# Exception occurred, rollback the transaction
print(f"Exception occurred: {exc_value}")
print("Rolling back database transaction")
self.connection.rollback()
if self.cursor:
self.cursor.close()
if self.connection:
print("Closing database connection")
self.connection.close()
# Return False to propagate exceptions
return False
def execute(self, query: str, params: tuple = ()):
"""Execute a database query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.execute(query, params)
def fetchall(self):
"""Fetch all results from the last query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.fetchall()
def fetchone(self):
"""Fetch one result from the last query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.fetchone()
class CustomResourceManager:
"""Context manager for custom resources with complex cleanup logic."""
def __init__(self, resource_name: str, cleanup_delay: float = 0.1):
self.resource_name = resource_name
self.cleanup_delay = cleanup_delay
self.resources: List[str] = []
self.is_active = False
self.start_time = None
def __enter__(self):
"""Enter the context - acquire resources."""
print(f"Acquiring resource: {self.resource_name}")
self.start_time = time.time()
self.is_active = True
# Simulate acquiring multiple sub-resources
self.resources = [
f"{self.resource_name}_connection",
f"{self.resource_name}_buffer",
f"{self.resource_name}_lock"
]
for resource in self.resources:
print(f" - Acquired: {resource}")
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - release resources with proper cleanup."""
duration = time.time() - self.start_time if self.start_time else 0
print(f"Releasing resource: {self.resource_name} (used for {duration:.2f}s)")
if exc_type is not None:
print(f"Exception during resource usage: {exc_type.__name__}: {exc_value}")
print("Performing emergency cleanup...")
# Clean up resources in reverse order (LIFO)
for resource in reversed(self.resources):
try:
print(f" - Releasing: {resource}")
# Simulate cleanup delay
time.sleep(self.cleanup_delay)
except Exception as cleanup_error:
print(f" - Error releasing {resource}: {cleanup_error}")
self.is_active = False
self.resources.clear()
print(f"Resource cleanup completed: {self.resource_name}")
# Return False to propagate exceptions
return False
def use_resource(self, operation: str):
"""Simulate using the resource."""
if not self.is_active:
raise RuntimeError(f"Resource {self.resource_name} is not active")
print(f"Using {self.resource_name} for: {operation}")
return f"Result of {operation} on {self.resource_name}"
def get_status(self):
"""Get the current status of the resource."""
return {
'name': self.resource_name,
'active': self.is_active,
'resources_count': len(self.resources),
'uptime': time.time() - self.start_time if self.start_time else 0
}
def demonstrate_file_manager():
"""Demonstrate FileManager with normal and exception scenarios."""
print("=" * 60)
print("DEMONSTRATING FILE MANAGER")
print("=" * 60)
# Normal operation
print("\n1. Normal file operation:")
try:
with FileManager("test_file.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a test file.\n")
print("File operation completed successfully")
except Exception as e:
print(f"Error: {e}")
# Exception during file operation
print("\n2. File operation with exception:")
try:
with FileManager("test_file2.txt", "w") as file:
file.write("Starting to write...\n")
# Simulate an error
raise ValueError("Simulated error during file operation")
file.write("This won't be written\n")
except Exception as e:
print(f"Caught exception: {e}")
# Clean up test files
for filename in ["test_file.txt", "test_file2.txt"]:
if os.path.exists(filename):
os.remove(filename)
print(f"Cleaned up: {filename}")
def demonstrate_database_manager():
"""Demonstrate DatabaseManager with normal and exception scenarios."""
print("\n" + "=" * 60)
print("DEMONSTRATING DATABASE MANAGER")
print("=" * 60)
db_path = "test_database.db"
# Normal database operation
print("\n1. Normal database operation:")
try:
with DatabaseManager(db_path) as db:
# Create table
db.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE
)
""")
# Insert data
db.execute("INSERT INTO users (name, email) VALUES (?, ?)",
("Alice", "alice@example.com"))
db.execute("INSERT INTO users (name, email) VALUES (?, ?)",
("Bob", "bob@example.com"))
# Query data
db.execute("SELECT * FROM users")
users = db.fetchall()
print(f"Users in database: {users}")
print("Database operation completed successfully")
except Exception as e:
print(f"Error: {e}")
# Exception during database operation
print("\n2. Database operation with exception:")
try:
with DatabaseManager(db_path) as db:
# Try to insert duplicate email (should cause rollback)
db.execute("INSERT INTO users (name, email) VALUES (?, ?)",
("Charlie", "alice@example.com")) # Duplicate email
except Exception as e:
print(f"Caught exception: {e}")
# Verify rollback worked
print("\n3. Verifying rollback:")
try:
with DatabaseManager(db_path) as db:
db.execute("SELECT COUNT(*) FROM users")
count = db.fetchone()[0]
print(f"Number of users after rollback: {count}")
except Exception as e:
print(f"Error: {e}")
# Clean up
if os.path.exists(db_path):
os.remove(db_path)
print(f"Cleaned up: {db_path}")
def demonstrate_custom_resource_manager():
"""Demonstrate CustomResourceManager with normal and exception scenarios."""
print("\n" + "=" * 60)
print("DEMONSTRATING CUSTOM RESOURCE MANAGER")
print("=" * 60)
# Normal resource operation
print("\n1. Normal resource operation:")
try:
with CustomResourceManager("WebService", cleanup_delay=0.05) as resource:
result1 = resource.use_resource("fetch_data")
print(f"Operation result: {result1}")
status = resource.get_status()
print(f"Resource status: {status}")
result2 = resource.use_resource("process_data")
print(f"Operation result: {result2}")
print("Resource operation completed successfully")
except Exception as e:
print(f"Error: {e}")
# Exception during resource operation
print("\n2. Resource operation with exception:")
try:
with CustomResourceManager("APIClient", cleanup_delay=0.05) as resource:
resource.use_resource("authenticate")
# Simulate an error
raise ConnectionError("Network connection lost")
resource.use_resource("fetch_data") # This won't execute
except Exception as e:
print(f"Caught exception: {e}")
# What we accomplished in this step:
# - Created demonstration functions for all context managers
# - Showed normal operation scenarios
# - Demonstrated exception handling and cleanup
# - Added proper cleanup of test files and databases
# Step 5: Advanced context manager patterns and complete demonstration
# ===============================================================================
# Explanation:
# Let's add advanced patterns like nested context managers, contextlib usage,
# and a complete demonstration that shows all features working together.
import os
import sqlite3
import tempfile
import time
from contextlib import contextmanager, ExitStack
from typing import Optional, Any, List
class FileManager:
"""Context manager for file operations with automatic cleanup."""
def __init__(self, filename: str, mode: str = 'w'):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
"""Enter the context - open the file."""
print(f"Opening file: {self.filename}")
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - close the file."""
if self.file:
print(f"Closing file: {self.filename}")
self.file.close()
# Return False to propagate exceptions
return False
class DatabaseManager:
"""Context manager for database connections with automatic cleanup."""
def __init__(self, database_path: str):
self.database_path = database_path
self.connection = None
self.cursor = None
def __enter__(self):
"""Enter the context - establish database connection."""
print(f"Connecting to database: {self.database_path}")
self.connection = sqlite3.connect(self.database_path)
self.cursor = self.connection.cursor()
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - close database connection."""
if exc_type is None:
# No exception occurred, commit the transaction
print("Committing database transaction")
self.connection.commit()
else:
# Exception occurred, rollback the transaction
print(f"Exception occurred: {exc_value}")
print("Rolling back database transaction")
self.connection.rollback()
if self.cursor:
self.cursor.close()
if self.connection:
print("Closing database connection")
self.connection.close()
# Return False to propagate exceptions
return False
def execute(self, query: str, params: tuple = ()):
"""Execute a database query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.execute(query, params)
def fetchall(self):
"""Fetch all results from the last query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.fetchall()
def fetchone(self):
"""Fetch one result from the last query."""
if not self.cursor:
raise RuntimeError("Database connection not established")
return self.cursor.fetchone()
class CustomResourceManager:
"""Context manager for custom resources with complex cleanup logic."""
def __init__(self, resource_name: str, cleanup_delay: float = 0.1):
self.resource_name = resource_name
self.cleanup_delay = cleanup_delay
self.resources: List[str] = []
self.is_active = False
self.start_time = None
def __enter__(self):
"""Enter the context - acquire resources."""
print(f"Acquiring resource: {self.resource_name}")
self.start_time = time.time()
self.is_active = True
# Simulate acquiring multiple sub-resources
self.resources = [
f"{self.resource_name}_connection",
f"{self.resource_name}_buffer",
f"{self.resource_name}_lock"
]
for resource in self.resources:
print(f" - Acquired: {resource}")
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the context - release resources with proper cleanup."""
duration = time.time() - self.start_time if self.start_time else 0
print(f"Releasing resource: {self.resource_name} (used for {duration:.2f}s)")
if exc_type is not None:
print(f"Exception during resource usage: {exc_type.__name__}: {exc_value}")
print("Performing emergency cleanup...")
# Clean up resources in reverse order (LIFO)
for resource in reversed(self.resources):
try:
print(f" - Releasing: {resource}")
# Simulate cleanup delay
time.sleep(self.cleanup_delay)
except Exception as cleanup_error:
print(f" - Error releasing {resource}: {cleanup_error}")
self.is_active = False
self.resources.clear()
print(f"Resource cleanup completed: {self.resource_name}")
# Return False to propagate exceptions
return False
def use_resource(self, operation: str):
"""Simulate using the resource."""
if not self.is_active:
raise RuntimeError(f"Resource {self.resource_name} is not active")
print(f"Using {self.resource_name} for: {operation}")
return f"Result of {operation} on {self.resource_name}"
def get_status(self):
"""Get the current status of the resource."""
return {
'name': self.resource_name,
'active': self.is_active,
'resources_count': len(self.resources),
'uptime': time.time() - self.start_time if self.start_time else 0
}
@contextmanager
def temporary_directory():
"""Context manager using @contextmanager decorator."""
temp_dir = tempfile.mkdtemp()
print(f"Created temporary directory: {temp_dir}")
try:
yield temp_dir
finally:
import shutil
shutil.rmtree(temp_dir)
print(f"Cleaned up temporary directory: {temp_dir}")
@contextmanager
def timer_context(operation_name: str):
"""Context manager to time operations."""
print(f"Starting timer for: {operation_name}")
start_time = time.time()
try:
yield
finally:
duration = time.time() - start_time
print(f"Operation '{operation_name}' took {duration:.3f} seconds")
def demonstrate_file_manager():
"""Demonstrate FileManager with normal and exception scenarios."""
print("=" * 60)
print("DEMONSTRATING FILE MANAGER")
print("=" * 60)
# Normal operation
print("\n1. Normal file operation:")
try:
with FileManager("test_file.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a test file.\n")
print("File operation completed successfully")
except Exception as e:
print(f"Error: {e}")
# Exception during file operation
print("\n2. File operation with exception:")
try:
with FileManager("test_file2.txt", "w") as file:
file.write("Starting to write...\n")
# Simulate an error
raise ValueError("Simulated error during file operation")
file.write("This won't be written\n")
except Exception as e:
print(f"Caught exception: {e}")
# Clean up test files
for filename in ["test_file.txt", "test_file2.txt"]:
if os.path.exists(filename):
os.remove(filename)
print(f"Cleaned up: {filename}")
def demonstrate_database_manager():
"""Demonstrate DatabaseManager with normal and exception scenarios."""
print("\n" + "=" * 60)
print("DEMONSTRATING DATABASE MANAGER")
print("=" * 60)
db_path = "test_database.db"
# Normal database operation
print("\n1. Normal database operation:")
try:
with DatabaseManager(db_path) as db:
# Create table
db.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE
)
""")
# Insert data
db.execute("INSERT INTO users (name, email) VALUES (?, ?)",
("Alice", "alice@example.com"))
db.execute("INSERT INTO users (name, email) VALUES (?, ?)",
("Bob", "bob@example.com"))
# Query data
db.execute("SELECT * FROM users")
users = db.fetchall()
print(f"Users in database: {users}")
print("Database operation completed successfully")
except Exception as e:
print(f"Error: {e}")
# Exception during database operation
print("\n2. Database operation with exception:")
try:
with DatabaseManager(db_path) as db:
# Try to insert duplicate email (should cause rollback)
db.execute("INSERT INTO users (name, email) VALUES (?, ?)",
("Charlie", "alice@example.com")) # Duplicate email
except Exception as e:
print(f"Caught exception: {e}")
# Verify rollback worked
print("\n3. Verifying rollback:")
try:
with DatabaseManager(db_path) as db:
db.execute("SELECT COUNT(*) FROM users")
count = db.fetchone()[0]
print(f"Number of users after rollback: {count}")
except Exception as e:
print(f"Error: {e}")
# Clean up
if os.path.exists(db_path):
os.remove(db_path)
print(f"Cleaned up: {db_path}")
def demonstrate_custom_resource_manager():
"""Demonstrate CustomResourceManager with normal and exception scenarios."""
print("\n" + "=" * 60)
print("DEMONSTRATING CUSTOM RESOURCE MANAGER")
print("=" * 60)
# Normal resource operation
print("\n1. Normal resource operation:")
try: