Skip to content

Commit a9c59e3

Browse files
dlangermdlangerm-stackav
authored andcommitted
fix mutable optional attribute if using shared annotation type
1 parent 06ab0fc commit a9c59e3

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

dltype/_lib/_core.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import inspect
66
import itertools
77
import warnings
8+
from copy import copy
89
from functools import lru_cache, wraps
910
from types import EllipsisType
1011
from typing import (
@@ -124,6 +125,7 @@ def from_hint( # noqa: PLR0911
124125
msg = f"Invalid base type=<{tensor_type}> in DLType hint, expected a subtype of {_dtypes.SUPPORTED_TENSOR_TYPES}"
125126
raise TypeError(msg)
126127

128+
dltype_hint = copy(dltype_hint) if optional else dltype_hint
127129
dltype_hint.optional = optional
128130
return (cls(tensor_type_hint=tensor_type, dltype_annotation=dltype_hint),)
129131

dltype/tests/dltype_test.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1711,3 +1711,24 @@ def tuple_function(
17111711
) -> Self:
17121712
"""A function that takes a tensor and returns a tensor."""
17131713
return self
1714+
1715+
1716+
SomeTensorT: TypeAlias = Annotated[torch.Tensor, dltype.FloatTensor["1 2 3"]]
1717+
1718+
1719+
def test_aliased_optional() -> None:
1720+
1721+
@dltype.dltyped()
1722+
def func(non_optional_tensor: SomeTensorT, optional_tensor: SomeTensorT | None = None) -> None:
1723+
pass
1724+
1725+
func(torch.zeros((1, 2, 3)))
1726+
1727+
func(torch.zeros((1, 2, 3)), None)
1728+
1729+
func(torch.zeros((1, 2, 3)), torch.zeros((1, 2, 3)))
1730+
1731+
func(torch.zeros((1, 2, 3)))
1732+
1733+
with pytest.raises(dltype.DLTypeUnsupportedTensorTypeError):
1734+
func(None, torch.zeros((1, 2, 3))) # pyright: ignore[reportArgumentType]

0 commit comments

Comments
 (0)