Skip to content

Commit

Permalink
Merge pull request #252 from specklesystems/gergo/set_type_fix
Browse files Browse the repository at this point in the history
fix(typing-system): add set type into type validation
  • Loading branch information
gjedlicska authored Jan 11, 2023
2 parents ac6ba87 + 1668c80 commit 1fb9a4f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/specklepy/objects/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,17 @@ def _validate_type(t: Optional[type], value: Any) -> Tuple[bool, Any]:
values.append(item_value)
return True, tuple(values)

if origin is set:
if not isinstance(value, set):
return False, value
if not hasattr(t, "__args__"):
return True, value
t_items = t.__args__[0] # type: ignore
first_item_valid, _ = _validate_type(t_items, next(iter(value)))
if first_item_valid:
return True, value
return False, value

if isinstance(value, t):
return True, value

Expand Down
10 changes: 9 additions & 1 deletion tests/unit/test_type_validation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from enum import Enum, IntEnum
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import Any, Dict, List, Optional, Set, Tuple, Union

import pytest

Expand Down Expand Up @@ -88,6 +88,14 @@ def __init__(self, foo: str) -> None:
# given our current rules, this is the reality. Its just sad...
(Tuple[str, str, str], (1, "foo", "bar"), True, ("1", "foo", "bar")),
(Tuple[str, Optional[str], str], (1, None, "bar"), True, ("1", None, "bar")),
(Set[bool], set([1, 2]), False, set([1, 2])),
(Set[int], set([1, 2]), True, set([1, 2])),
(Set[int], set([None, 2]), True, set([None, 2])),
# not testing this, since order of input iterables in sets are not preserved
# easily produces false reports since we're only checking the type of the
# first item
# (Set[int], set(["None", 2]), False, set(["None", 2])),
(Set[Optional[int]], set([None, 2]), True, set([None, 2])),
(Optional[Union[List[int], List[FakeBase]]], None, True, None),
(Optional[Union[List[int], List[FakeBase]]], "foo", False, "foo"),
(Union[List[int], List[FakeBase], None], "foo", False, "foo"),
Expand Down

0 comments on commit 1fb9a4f

Please sign in to comment.