Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 4 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -564,12 +564,15 @@ jobs:
--test implementation_naming_test `
--test python_overload_legacy_compat_test `
--test python_released_implementation_test
- name: Test generated nullable collection values
- name: Test generated collection protocols
shell: pwsh
run: |
$env:DYNWINRT_TEST_PYTHON = (Resolve-Path .\bindings\py\.venv\Scripts\python.exe).Path
$env:DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME = '1'
$env:DYNWINRT_REQUIRE_MYPY = '1'
cargo test -p dynwinrt-codegen --test python_consumer_typing_test `
collection_comparisons_preserve_native_identity_and_python_value_semantics -- --exact
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
cargo test -p dynwinrt-codegen --test python_consumer_typing_test `
mutable_collection_mutators_accept_none -- --exact
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
Expand Down
16 changes: 16 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,22 @@ and iterators work with `iter()` and `next()`. Mutable vectors support indexing,
slicing, assignment, insertion, and deletion; mutable maps support standard
mapping assignment and deletion.

Sequence containment, `index()`, `count()`, and `remove()`, mapping equality,
and value/item-view membership compare WinRT references by canonical COM
identity, including different generated class/interface views and raw
`DynWinRTValue` carriers of the same object. This is reference identity, not a
runtime class's `equals()` or content comparison. Python scalars and generated
structs retain their normal equality, and released or wrong-thread native
access still raises. Wrapper/value `==` and hashing outside these collection
operations are unchanged.
Mapping equality also preserves entry counts: distinct Python keys are not
collapsed into one entry just because they alias the same native reference.

Raw `Object` collections do not implicitly box or unbox for comparison:
different boxes remain different references. An opt-in `object_value_view()`
compares its converted Python values normally and any remaining native
references by COM identity.

Method inputs accept normal Python sequences and mappings in place of compatible
WinRT collection interfaces, subject to the producer limits below.
Byte arrays accept `bytes` and `bytearray`; GUID,
Expand Down
29 changes: 27 additions & 2 deletions bindings/py/python/dynwinrt/values.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,18 @@

import operator
import struct
from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping
from collections.abc import (
Callable,
Iterable,
Iterator,
ItemsView,
Mapping,
MutableMapping,
ValuesView,
)
from datetime import datetime, timedelta
from enum import IntEnum
from importlib import import_module as _import_module
from typing import (
TYPE_CHECKING,
Any,
Expand All @@ -50,6 +59,8 @@

from dynwinrt import DynWinRTType, DynWinRTValue, WinGUID, to_winrt_object, unbox_object

_native = _import_module("dynwinrt.dynwinrt")

if TYPE_CHECKING:
from _typeshed import SupportsKeysAndGetItem

Expand Down Expand Up @@ -790,7 +801,9 @@ class ObjectValueView(Mapping[_K, WinRTObjectValue]):
``datetime.datetime``. Other errors propagate.

Every operation goes to the map; the view holds no WinRT reference of its
own. ``raw`` is the generated map, whose values stay native.
own. ``raw`` is the generated map, whose values stay native. Equality and
value/item membership compare remaining native references by COM identity;
converted Python values retain their normal equality.
"""

__slots__ = ("_map", "_preserve_type")
Expand Down Expand Up @@ -833,6 +846,18 @@ def __len__(self) -> int:
def __contains__(self, key: object) -> bool:
return key in self._map

def __eq__(self, other: object) -> bool:
mapping_equal: Callable[[object, object], bool] = _native._dynwinrt_mapping_equal
return mapping_equal(self, other)

def items(self) -> ItemsView[_K, WinRTObjectValue]:
view: ItemsView[_K, WinRTObjectValue] = _native._WinRTItemsView(self)
return view

def values(self) -> ValuesView[WinRTObjectValue]:
view: ValuesView[WinRTObjectValue] = _native._WinRTValuesView(self)
return view

def __repr__(self) -> str:
options = ", preserve_type=True" if self._preserve_type else ""
return f"dynwinrt.values.{type(self).__name__}({self._map!r}{options})"
Expand Down
124 changes: 106 additions & 18 deletions bindings/py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,12 @@ from collections.abc import (
Coroutine as _Coroutine,
Iterable as _Iterable,
Iterator as _Iterator,
ItemsView as _ItemsView,
Mapping as _Mapping,
MutableMapping as _MutableMapping,
MutableSequence as _MutableSequence,
Sequence as _Sequence,
ValuesView as _ValuesView,
)
from datetime import datetime as _datetime, timedelta as _timedelta, timezone as _timezone
from itertools import count as _count
Expand Down Expand Up @@ -515,16 +517,67 @@ def _dynwinrt_preflight_non_null_collection(self, values):
native._validate_non_null_collection_input(raw, *contract)
return items

class _WinRTSequenceMixin(_Sequence):
def __len__(self):
return self.size
_dynwinrt_no_collection_identity = object()
_dynwinrt_collection_iunknown = None

def __getitem__(self, index):
if isinstance(index, slice):
return [self.get_at(i) for i in range(*index.indices(len(self)))]
return self.get_at(_dynwinrt_normalize_index(index, len(self)))
def _dynwinrt_collection_identity(value):
if value is None:
return None
native = getattr(value, '_obj', value)
if not isinstance(native, DynWinRTValue):
return _dynwinrt_no_collection_identity
global _dynwinrt_collection_iunknown
if _dynwinrt_collection_iunknown is None:
_dynwinrt_collection_iunknown = WinGUID.parse(
'00000000-0000-0000-c000-000000000046'
)
# The probe checks lifetime/thread access even for scalar and null carriers.
if native._try_query_interface(_dynwinrt_collection_iunknown):
identity = native.cast(_dynwinrt_collection_iunknown)
try:
return identity.as_raw()
finally:
identity.release()
return None if native.is_null() else _dynwinrt_no_collection_identity

def _dynwinrt_collection_equal(left, right):
left_identity = _dynwinrt_collection_identity(left)
right_identity = _dynwinrt_collection_identity(right)
if (
left_identity is not _dynwinrt_no_collection_identity
and right_identity is not _dynwinrt_no_collection_identity
):
return left_identity == right_identity
return left is right or left == right

def _dynwinrt_collection_key(key):
identity = _dynwinrt_collection_identity(key)
if identity is _dynwinrt_no_collection_identity:
return key
if identity is None:
return None
return (_dynwinrt_no_collection_identity, identity)

def _dynwinrt_mapping_equal(left, right):
if not isinstance(right, _Mapping):
return NotImplemented
# Retain native keys while their canonical identities are dictionary keys.
left_pairs = list(left.items())
right_pairs = list(right.items())
left_keys = [_dynwinrt_collection_key(key) for key, _ in left_pairs]
right_values = {}
for key, value in right_pairs:
right_values.setdefault(_dynwinrt_collection_key(key), []).append(value)
if len(left_pairs) != len(right_pairs):
return False
# Identity normalization must match entries one-to-one, not collapse aliases.
for key, (_, value) in zip(left_keys, left_pairs):
candidates = right_values.pop(key, ())
if len(candidates) != 1 or not _dynwinrt_collection_equal(value, candidates[0]):
return False
return not right_values

class _WinRTMutableSequenceMixin(_MutableSequence):
class _WinRTSequenceMixin(_Sequence):
def __len__(self):
return self.size

Expand All @@ -533,6 +586,31 @@ class _WinRTMutableSequenceMixin(_MutableSequence):
return [self.get_at(i) for i in range(*index.indices(len(self)))]
return self.get_at(_dynwinrt_normalize_index(index, len(self)))

def __contains__(self, value):
return any(_dynwinrt_collection_equal(item, value) for item in self)

def index(self, value, start=0, stop=None):
start = _index(start)
if start < 0:
start = max(0, len(self) + start)
if stop is not None:
stop = _index(stop)
if stop < 0:
stop += len(self)
while stop is None or start < stop:
try:
item = self[start]
except IndexError:
break
if _dynwinrt_collection_equal(item, value):
return start
start += 1
raise ValueError

def count(self, value):
return sum(1 for item in self if _dynwinrt_collection_equal(item, value))

class _WinRTMutableSequenceMixin(_WinRTSequenceMixin, _MutableSequence):
def __setitem__(self, index, value):
if isinstance(index, slice):
items = list(self)
Expand Down Expand Up @@ -577,6 +655,19 @@ class _WinRTIteratorMixin(_Iterator):
self.move_next()
return value

class _WinRTItemsView(_ItemsView):
def __contains__(self, item):
key, value = item
try:
candidate = self._mapping[key]
except KeyError:
return False
return _dynwinrt_collection_equal(candidate, value)

class _WinRTValuesView(_ValuesView):
def __contains__(self, value):
return any(_dynwinrt_collection_equal(item, value) for item in self)

class _WinRTMappingMixin(_Mapping):
def __len__(self):
return self.size
Expand All @@ -590,19 +681,16 @@ class _WinRTMappingMixin(_Mapping):
raise KeyError(key)
return self.lookup(key)

class _WinRTMutableMappingMixin(_MutableMapping):
def __len__(self):
return self.size
def __eq__(self, other):
return _dynwinrt_mapping_equal(self, other)

def __iter__(self):
for pair in self._iter_pairs():
yield pair.key
def items(self):
return _WinRTItemsView(self)

def __getitem__(self, key):
if not self.has_key(key):
raise KeyError(key)
return self.lookup(key)
def values(self):
return _WinRTValuesView(self)

class _WinRTMutableMappingMixin(_WinRTMappingMixin, _MutableMapping):
def __setitem__(self, key, value):
self.insert(key, value)

Expand Down
Loading
Loading