Skip to content

Commit

Permalink
Fixes to typesystem, with tests
Browse files Browse the repository at this point in the history
  • Loading branch information
erezsh committed Dec 30, 2023
1 parent baa18d9 commit d89cf87
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
22 changes: 21 additions & 1 deletion runtype/base_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ def __ge__(self, other):

def __le__(self, other):
if isinstance(other, Type):
return other is self
if other is self: # Optimization
return True

return NotImplemented

Expand All @@ -72,6 +73,12 @@ def __le__(self, other):

return super().__le__(other)

def __ge__(self, other):
# XXX hack
if isinstance(other, AnyType):
return False
return NotImplemented


class SumType(Type):
"""Implements a sum type, i.e. a disjoint union of a set of types.
Expand Down Expand Up @@ -170,6 +177,11 @@ class ContainerType(DataType):
def __getitem__(self, other):
return GenericType(self, other)

def __le__(self, other):
# XXX hack
if isinstance(other, AnyType):
return True
return super().__le__(other)

class GenericType(ContainerType):
"""Implements a generic type. i.e. a container for items of a specific type.
Expand Down Expand Up @@ -214,6 +226,10 @@ def __le__(self, other):
elif isinstance(other, DataType):
return self.base <= other

elif isinstance(other, AnyType):
# HACK
return True

return NotImplemented

def __ge__(self, other):
Expand All @@ -223,6 +239,10 @@ def __ge__(self, other):
elif isinstance(other, DataType):
return self.base >= other

elif isinstance(other, AnyType):
# HACK
return False

return NotImplemented

def __hash__(self):
Expand Down
14 changes: 11 additions & 3 deletions tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1035,9 +1035,17 @@ class Foo:
"d": {"a": {"baz": 2}}
}




def test_any(self):
assert is_subtype(int, Any)
assert not is_subtype(Any, int)
assert is_subtype(Any, Any)
assert is_subtype(Any, Union[Any, int])
assert is_subtype(Any, Union[Any, None])
assert is_subtype(Union[Any, int], Any)
assert is_subtype(Union[Any, None], Any)
assert is_subtype(Union[Any, None], Union[Any, None])
assert is_subtype(dict, Any, )
assert not is_subtype(Any, dict)

if __name__ == '__main__':
unittest.main()

0 comments on commit d89cf87

Please sign in to comment.