Skip to content

Add context manager protocol for .NET IDisposable types #2568

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
update docs
  • Loading branch information
den-run-ai authored and den-run-ai committed Mar 23, 2025
commit ac7e69c22a6f206ffd2c914cc97454c7bcc73c3d
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
## Unreleased

### Added

- Add context manager protocol for .NET IDisposable types, allowing use of `with` statements for IDisposable objects (#9c73c35)

### Changed
### Fixed

Expand Down
28 changes: 28 additions & 0 deletions doc/source/python.rst
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,34 @@ Python idioms:
for item in domain.GetAssemblies():
name = item.GetName()

Using Context Managers (IDisposable)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.NET types that implement ``IDisposable`` can be used with Python's context manager
protocol using the standard ``with`` statement. This automatically calls the object's
``Dispose()`` method when exiting the ``with`` block:

.. code:: python

from System.IO import MemoryStream, StreamWriter

# Use a MemoryStream as a context manager
with MemoryStream() as stream:
# The stream is automatically disposed when exiting the with block
writer = StreamWriter(stream)
writer.Write("Hello, context manager!")
writer.Flush()

# Do something with the stream
stream.Position = 0
# ...

# After exiting the with block, the stream is disposed
# Attempting to use it here would raise an exception

This works for any .NET type that implements ``IDisposable``, making resource
management much cleaner and safer in Python code.

Type Conversion
---------------

Expand Down
Loading