Expressions functions and Python types

The simplest example of this is to use IronPython to evaluate individual expressions. IronPython makes a great calculator!21

So far, whenever we have executed Python code from a string we have passed in the enumeration member SourceCodeKind.Statements. This member has a sister, SourceCodeKind.Expression, that allows us to evaluate an expression and return an object. It is used in this snippet of C# to evaluate a simple mathematical expression:

string code = "2 + 3 + 5"; ScriptSource source;

21 You can see an example of embedded IronPython as a calculator at http://www.voidspace.org.uk/ironpython/ dlr_hosting.shtml.

source = runtime.CreateScriptSourceFromString(code,

SourceCodeKind.Expression); int result = source.Execute<int>(scope);

This code uses the generic form of Execute that allows us to specify the type of the returned object. Using the generic version requires us to pass in an explicit scope to Execute. If we wanted to use the default scope, we could instead cast the returned object to retrieve the integer.

0 0

Post a comment

  • Receive news updates via email from this site