File tree 2 files changed +31
-0
lines changed
2 files changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -8,6 +8,9 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
8
8
## Unreleased
9
9
10
10
### Added
11
+
12
+ - Add context manager protocol for .NET IDisposable types, allowing use of ` with ` statements for IDisposable objects (#9c73c35)
13
+
11
14
### Changed
12
15
### Fixed
13
16
Original file line number Diff line number Diff line change @@ -479,6 +479,34 @@ Python idioms:
479
479
for item in domain.GetAssemblies():
480
480
name = item.GetName()
481
481
482
+ Using Context Managers (IDisposable)
483
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
484
+
485
+ .NET types that implement ``IDisposable `` can be used with Python's context manager
486
+ protocol using the standard ``with `` statement. This automatically calls the object's
487
+ ``Dispose() `` method when exiting the ``with `` block:
488
+
489
+ .. code :: python
490
+
491
+ from System.IO import MemoryStream, StreamWriter
492
+
493
+ # Use a MemoryStream as a context manager
494
+ with MemoryStream() as stream:
495
+ # The stream is automatically disposed when exiting the with block
496
+ writer = StreamWriter(stream)
497
+ writer.Write(" Hello, context manager!" )
498
+ writer.Flush()
499
+
500
+ # Do something with the stream
501
+ stream.Position = 0
502
+ # ...
503
+
504
+ # After exiting the with block, the stream is disposed
505
+ # Attempting to use it here would raise an exception
506
+
507
+ This works for any .NET type that implements ``IDisposable ``, making resource
508
+ management much cleaner and safer in Python code.
509
+
482
510
Type Conversion
483
511
---------------
484
512
You can’t perform that action at this time.
0 commit comments