scripts: csv.py: Implicitly convert during string concatenation

This may be a (very javascript-esque) mistake, but implicit conversion
to strings is useful when mixing fields and strings in -b/--by field
exprs:

  $ ./scripts/csv.py input.csv -bcase='"test"+n' -fn

Note that this now (mostly) matches the behavior when the n field is
unspecified:

  $ ./scripts/csv.py input.csv -bcase='"test"+n'

Er... well... mostly. When we specify n as a field, csv.py does
typecheck and parse the field, which ends up sort of canonicalizing the
field, unlike omitting n which leaves n as a string... But at least if
the field was already canonicalized the behavior matches...

It may also be better to force all -b/--by expr inputs to strings first,
but this would require us to know which expr came from where. It also
wouldn't solve the canonicalization problem.
This commit is contained in:
Christopher Haster
2024-11-14 00:09:54 -06:00
parent 47f28946f6
commit 14687a20bf

View File

@@ -878,7 +878,12 @@ class RExpr:
class Add(Expr):
"""Addition"""
def eval(self, fields={}):
return self.a.eval(fields) + self.b.eval(fields)
a = self.a.eval(fields)
b = self.b.eval(fields)
if isinstance(a, str) or isinstance(b, str):
return str(a) + str(b)
else:
return a + b
@bop('-', 9)
class Sub(Expr):