I'm new to IronPython and Python in general. I'm trying to work with C# decimals and IronPython math functions. When I try to return the absolute value of an argument, I get a type exception when the argument is a decimal. Here's my code:
[TestMethod]
public void CallDecimal()
{
var pySrc =
@"def MyAbs(arg):
return abs(arg)";
// host python and execute script
var engine = IronPython.Hosting.Python.CreateEngine();
var scope = engine.CreateScope();
engine.Execute(pySrc, scope);
// get function with a strongly typed signature
var myAbs = scope.GetVariable<Func<decimal, decimal>>("MyAbs");
Assert.AreEqual(5m, myAbs(-5m));
}
The error message I get says:
IronPython.Runtime.Exceptions.TypeErrorException: bad operand type for abs(): 'Decimal'
Is there a Python absolute value function that accepts decimals? If not, is it easy to write one? If I could specify the types of function parameters, I'd try to create my own abs function like this:
define abs(Decimal arg):
return arg < 0 ? -arg : arg