Ironpython and future statements

402 views Asked by At

I am using IronPython as a math parser with the DLR in my Silverlight project: it works, but computes incorrect results in cases involving division, as it uses integer instead of floating point math at times (so 4/3 returns 1). Google suggests adding from __future__ import division to the python script, but doing so throws an exception when I try to run it.

Are __future__ statements supported at all in IronPython? What can I do to make them work?

2

There are 2 answers

1
Jeff Hardy On

You'll have to make sure that __future__.py is available for import. I'm not sure how to do that for Silverlight, though.

1
Christian On

Besides what Jeff suggested, you can also set the division behaviour when setting up the engine

var engineOptions = new Dictionary<string, object>();
engineOptions["DivisionOptions"] = PythonDivisionOptions.New;
var engine = Python.CreateEngine(engineOptions);
Console.WriteLine("{0}", engine.Execute("4 / 3"));

or when you compile your script:

var engine = Python.CreateEngine();
var compilerOptions = (PythonCompilerOptions)engine.GetCompilerOptions();
compilerOptions.Module |= ModuleOptions.TrueDivision;
var code = engine.CreateScriptSourceFromString("4 / 3").Compile(compilerOptions);
Console.WriteLine("{0}", code.Execute());