Skip to content

Commit

Permalink
importers.csvbase: Allow to negate the value parsed by Amount column
Browse files Browse the repository at this point in the history
  • Loading branch information
wzyboy authored and dnicolodi committed Jan 24, 2025
1 parent 1dbcf2c commit 73d07da
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
9 changes: 7 additions & 2 deletions beangulp/importers/csvbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,17 +144,22 @@ class Amount(Column):
subs: Dictionary mapping regular expression patterns to
replacement strings. Substitutions are performed with
re.sub() in the order they are specified.
negate: If true, negate the amount.
default: Value to return if the field is empty, if specified.
"""
def __init__(self, name, subs=None, default=NA):
def __init__(self, name, subs=None, negate=False, default=NA):
super().__init__(name, default=default)
self.subs = subs if subs is not None else {}
self.negate = negate

def parse(self, value):
for pattern, replacement in self.subs.items():
value = re.sub(pattern, replacement, value)
return decimal.Decimal(value)
parsed = decimal.Decimal(value)
if self.negate:
parsed = -parsed
return parsed


# The CSV Importer class needs to inherit from beangulp.Importer which
Expand Down
7 changes: 7 additions & 0 deletions beangulp/importers/csvbase_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,13 @@ def test_default_value_none(self):
value = func(('', ))
self.assertIsNone(value)

def test_parse_negate(self):
column = Amount(0, negate=True)
func = column.getter(None)
value = func(('123.45', ))
self.assertIsInstance(value, decimal.Decimal)
self.assertEqual(value, -decimal.Decimal('123.45'))


class TestCSVMeta(unittest.TestCase):

Expand Down

0 comments on commit 73d07da

Please sign in to comment.