Skip to content

Commit

Permalink
Require that NonemptyMapping value types have a copy method.
Browse files Browse the repository at this point in the history
We're only using it with list, dict, and set values, and it's really
only useful when the value type is a mutable container anyway.
  • Loading branch information
TallJimbo committed Oct 25, 2024
1 parent 1438993 commit 2bab92a
Showing 1 changed file with 12 additions and 5 deletions.
17 changes: 12 additions & 5 deletions python/lsst/daf/butler/nonempty_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,18 @@

__all__ = ("NonemptyMapping",)

import copy
from collections.abc import Callable, Iterator, Mapping
from typing import Any, TypeVar, overload
from typing import Any, Protocol, Self, TypeVar, overload


class Copyable(Protocol):

def copy(self) -> Self: ...


_K = TypeVar("_K")
_T = TypeVar("_T")
_V = TypeVar("_V", covariant=True)
_V = TypeVar("_V", bound=Copyable, covariant=True)


class NonemptyMapping(Mapping[_K, _V]):
Expand All @@ -56,7 +61,8 @@ class NonemptyMapping(Mapping[_K, _V]):
it can be modified only by invoking ``__getitem__`` with a key that does
not exist. It is expected that the value type will be a mutable container
like `set` or `dict`, and that an empty nested container should be
considered equivalent to the absence of a key.
considered equivalent to the absence of a key. The value type must have
a `copy` method that copies all mutable state.
"""

def __init__(self, default_factory: Callable[[], _V]) -> None:
Expand Down Expand Up @@ -106,5 +112,6 @@ def copy(self) -> NonemptyMapping[_K, _V]:
callback and keys.
"""
result = NonemptyMapping[_K, _V](self._default_factory)

Check warning on line 114 in python/lsst/daf/butler/nonempty_mapping.py

View check run for this annotation

Codecov / codecov/patch

python/lsst/daf/butler/nonempty_mapping.py#L114

Added line #L114 was not covered by tests
result._mapping = copy.deepcopy(self._mapping)
for k, v in self._mapping.items():
result._mapping[k] = v.copy()
return result

Check warning on line 117 in python/lsst/daf/butler/nonempty_mapping.py

View check run for this annotation

Codecov / codecov/patch

python/lsst/daf/butler/nonempty_mapping.py#L116-L117

Added lines #L116 - L117 were not covered by tests

0 comments on commit 2bab92a

Please sign in to comment.