Skip to content

Commit 8a6f25a

Browse files
authored
Implement __radd__ for Quantity and BaseObj (#23)
Fixes #17
2 parents 21e51db + be55c2b commit 8a6f25a

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/cooklang_py/base_objects.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,11 @@ def __format__(self, format_spec: str) -> str:
128128
continue
129129
return s
130130

131+
def __radd__(self, other) -> str:
132+
if not isinstance(other, str):
133+
raise TypeError(f'Cannot add {self} to {other.__class__.__name__}')
134+
return f'{other}{self}'
135+
131136

132137
class BaseObj:
133138
"""Base Object for Ingredient, Cookware, and Timing"""
@@ -256,6 +261,11 @@ def factory(cls, raw: str):
256261
name = re.sub(r'\W+$', '', name) or name
257262
return cls(f'{cls.prefix}{name}', name=name)
258263

264+
def __radd__(self, other) -> str:
265+
if not isinstance(other, str):
266+
raise TypeError(f'Cannot add {self} to {other.__class__.__name__}')
267+
return f'{other}{self}'
268+
259269

260270
class Ingredient(BaseObj):
261271
"""Ingredient"""

tests/test_base_object.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,25 @@ def test_formatting_no_unit_or_notes():
6868
"""Test formatting with name and amount"""
6969
ing = Ingredient(raw='@eggs{3}', name='eggs', quantity='3')
7070
assert f'{ing:%q[%af %us] %n (%c)}' == '3 eggs ()'
71+
72+
73+
def test_quantity_string_addition():
74+
"""Test string addition"""
75+
assert 'Testing: ' + Quantity('1%cup') == 'Testing: 1 c'
76+
77+
78+
def test_quantity_quantity_addition():
79+
"""Test quantity addition"""
80+
with pytest.raises(TypeError):
81+
Quantity('1%cup') + Quantity('1%cup')
82+
83+
84+
def test_baseobj_string_addition():
85+
"""Test string addition"""
86+
assert 'Testing: ' + Ingredient('', name='flour', quantity='1%cup') == 'Testing: flour (1 c)'
87+
88+
89+
def test_baseobj_baseobj_addition():
90+
"""Test quantity addition"""
91+
with pytest.raises(TypeError):
92+
Ingredient('', name='flour', quantity='1%cup') + Ingredient('', name='flour', quantity='1%cup')

0 commit comments

Comments
 (0)