Skip to content

Add Python close and context managers for closable WinRT interfaces - #233

Merged
leileizhang (lei9444) merged 2 commits into
mainfrom
lei9444-python-stream-context-managers
Oct 30, 2026
Merged

leileizhang (lei9444) merged 2 commits into
mainfrom
lei9444-python-stream-context-managers

Conversation

@lei9444

@lei9444 leileizhang (lei9444) commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Python stream results such as IRandomAccessStream and IInputStream lack close() and context-manager methods even though their WinMD contracts require IClosable. Add helpers only where that explicit, transitive requirement exists, reusing the existing concrete-class implementation to QueryInterface to IClosable and call native Close. Successful helper calls are idempotent, failed closes remain retryable, and context exit does not suppress body exceptions. IClosable itself gains context-manager methods while retaining its metadata-defined close() behavior.

Runtime and .pyi generation share the same member plan, including Self and Literal[False] context-manager declarations. Existing metadata methods, properties, CLR names, and compatibility aliases retain their meanings; helpers yield when their names are occupied. Existing concrete-class closing behavior is preserved. Native and typing fixtures use the generated project's src layout, including the constructor-diagnostics regression.

Reproduction

Prerequisites: Windows 10/11 with Windows SDK metadata, a supported CPython version, and dynwinrt-codegen with its matching dynwinrt runtime installed.

Steps:

  1. Generate and install the bindings:
dynwinrt-codegen generate --lang py --class-name Windows.Storage.StorageFile --output generated
python -m pip install .\generated
  1. Save this as probe.py and run python probe.py:
import asyncio
from pathlib import Path
from tempfile import TemporaryDirectory
from dynwinrt import RoApartment, projected_lifetime_scope
from generated import FileAccessMode, StorageFile

async def main():
    with TemporaryDirectory() as directory:
        path = Path(directory) / "stream.txt"
        path.write_bytes(b"closable")
        file = await StorageFile.get_file_from_path_async(str(path))
        with await file.open_async(FileAccessMode.Read) as stream:
            print(stream.size)
        try:
            _ = stream.size
        except OSError as error:
            assert error.winerror & 0xFFFFFFFF == 0x80000013
            print("RO_E_CLOSED")
        else:
            raise AssertionError("stream was not closed")

with RoApartment(), projected_lifetime_scope():
    asyncio.run(main())

Actual behavior: The with statement raises TypeError because the returned IRandomAccessStream projection has no context-manager methods. Explicit stream.close() also raises AttributeError.

After the fix: The script prints 8 followed by RO_E_CLOSED: context exit closes the actual native stream rather than merely releasing a Python reference.

Validation

Fresh generation with and without .pyi files exercises actual file, input, output, and content-type streams, exception propagation, failed-close retry, native aliases, and existing concrete classes. An installed generated project also closes a real file stream under isolated Python imports. Strict mypy checks preserve Self and non-suppressing exits while rejecting closing methods on IBuffer; metadata cases cover transitive and closed-generic requirements, native-name collisions, and compatibility aliases. Constructor diagnostics and concrete-class snapshots remain intact.

Compatibility and risks

Regenerate and reinstall bindings to obtain the interface helpers. Closing a resource does not release its Python projection or dispose an interface-implementation owner. Interfaces without an explicit IClosable requirement and arbitrary Object values are unchanged. When a native member occupies a helper name, use with stream.as_interface(IClosable): instead. Direct IClosable.close() retains native repeat-call behavior.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Mixed-language test coverage

Workflow status: ✅ Passed

Layer Lines Functions Branches/regions
Rust, including native .pyd/.node 86.61% 82.05% 86.22% regions
Python aggregate 70.6% n/a 37.99% branches
Python runtime 98.28% n/a 95% branches
Generated Python WinRT projections 68.46% n/a 30.26% branches
Generated Python WinRT implementations 71.75% n/a 46.08% branches
JavaScript aggregate 18.38% 24.85% 55.94% branches
JavaScript runtime 41.73% 41.53% 78.33% branches
Generated WinRT projections 17.27% 19.36% 52.51% branches
Generated WinRT implementations 45.99% 59.19% 60.97% branches
Generated Classic COM projections 11.38% 23.88% 53.1% branches

View workflow run and download full HTML/LCOV/XML reports

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@lei9444
leileizhang (lei9444) merged commit 8d20d8e into main Oct 30, 2026
14 checks passed
@lei9444
leileizhang (lei9444) deleted the lei9444-python-stream-context-managers branch October 30, 2026 05:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants