Skip to content
Snippets Groups Projects
Commit f8ee9a21 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

add equality and membership tests to Optional

parent 815afb7a
No related branches found
Tags v2.15.6
No related merge requests found
# v2.15.6
* added equality checking and membership test to Optional
__version__ = '2.15.6a1'
__version__ = '2.15.6'
......@@ -54,12 +54,32 @@ class Optional(Proxy):
* getattr
* getitem/setitem/delitem
* testing for truth
* comparison (with nonexistent elements always comparing false)
* membership test (with nonexistent elements always returning false)
.. warning:: Returned objects via getattr and getitem are NOT wrapped in an
Optional. You need to do it by hand or just file an issue. I'll add that when I
need it.
:param obj: object to wrap
"""
__slots__ = ()
def __init__(self, obj):
super().__init__(obj)
def __contains__(self, item) -> bool:
me = getattr(self, '_Proxy__obj')
if me is None:
return False
return item in me
def __eq__(self, other) -> bool:
me = getattr(self, '_Proxy__obj')
if me is None:
return False
return me == other
def __getattr__(self, item):
if getattr(self, '_Proxy__obj') is None:
return EMPTY_OPTIONAL
......
......@@ -15,6 +15,17 @@ class TestOptionals(unittest.TestCase):
self.assertFalse(c)
self.assertTrue(b)
def test_optional_eq(self):
class Opt:
a = 5
b = [2]
a = Opt()
self.assertEqual(Optional(a).a, 5)
self.assertIn(2, Optional(a).b)
self.assertNotEqual(Optional(None).a, 5)
self.assertNotIn(2, Optional(None).b)
def test_optional(self):
self.assertIsNone(call_if_nnone(None))
b = call_if_nnone(lambda y: y, 5)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment