IronPython Hosting Reference

IronPython Hosting API
CollapseAll image
This file provides documentation for the classes that are needed to host IronPython in applications written for the common language runtime.

Expand image Namespaces

Namespace | Description
IronPython.Hosting | Provides classes that allow applications to host IronPython. A host application can use the PythonEngine class to run, interact with, and control one or more IronPython sessions. The host can execute user code and application code written in IronPython, and can expose an object model that the IronPython code can call. PythonEngine provides several ways to enable user customization of host applications.
IronPython.Modules | Provides host applications with access to the ClrModule class, which supports interoperation between IronPython and the common language runtime (CLR). A host application uses ClrModule to load assemblies and make their objects available to IronPython sessions. Importing ClrModule provides access to the most commonly-used assemblies in the .NET Framework.
IronPython.Runtime.Exceptions | Contains exceptions that can be thrown by IronPython code. If the exceptions are not handled in IronPython code executed by the host application, the host must handle them.
To make a suggestion or report a bug about Help or another feature of this product, go to the feedback site.


IronPython.Hosting Namespace
CollapseAll image
The IronPython.Hosting namespace provides classes that allow applications to host IronPython. A host application can use the PythonEngine class to run, interact with, and control one or more IronPython sessions. The host can execute user code and application code written in IronPython, and can expose an object model that the IronPython code can call. PythonEngine provides several ways to enable user customization of host applications.

Expand image Classes

 | Class | Description
Public class | CompiledCode | Represents a set of statements that have been compiled.
Public class | EngineModule | Represents a global scope in which the IronPython execution engine can maintain variables and execute code.
Public class | EngineOptions | Provides PythonEngine execution options.
Public class | OptimizedEngineModule | Represents a module that has been optimized for access to global data.
Public class | PythonEngine | Represents a running instance of the IronPython execution engine, which can be controlled by host applications.
Public class | ResourceFile |

Expand image Delegates

 | Delegate | Description
Public delegate | ModuleBinder | Returns a delegate of the specified type, bound to the specified IronPython module.
Public delegate | PythonEngine.CommandDispatcher | Represents a method that executes compiled IronPython statements on another thread.
Public delegate | PythonEngine.FilterStackFrame | Represents a method that determines whether the specified stack frame is included in a stack trace.
To make a suggestion or report a bug about Help or another feature of this product, go to the feedback site.


CompiledCode Class
See Also Example Members
CollapseAll image DropDown image

Represents a set of statements that have been compiled.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Class CompiledCode
Visual Basic (Usage)
Dim instance As CompiledCode
C#
public class CompiledCode
C++
public ref class CompiledCode
J#
public class CompiledCode
JScript
public class CompiledCode

Expand image Remarks

Compilation resolves symbols in the IronPython code and converts it to Microsoft intermediate language (MSIL). When the same code is executed repeatedly, execution time is significantly reduced if the code is compiled first, instead of calling the IronPython.Hosting.PythonEngine.Execute method every time. To create a CompiledCode object, use the IronPython.Hosting.PythonEngine.Compile or PythonEngine.CompileFile methods.

Expand image Example

The following code example demonstrates the advantage of executing compiled code repeatedly, instead of compiling every time.

The code example creates a new module with two global variables and executes a set of statements 1000 times, using the PythonEngine.Execute(String,EngineModule,Generic IDictionary) method overload and supplying dictionary of local variables. The statements are then compiled using the PythonEngine.Compile method, and the compiled code is executed 1000 times, using the same dictionary of locals. The ratio of the elapsed times is displayed.

Before each timing, the method to be tested is executed once to eliminate any initialization time from the timed interval.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine

        Dim testModule As EngineModule = engine.CreateModule("tm", True)
        testModule.Globals.Add("g1", 1000)
        testModule.Globals.Add("g2", 2000)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("loc1", 10)
        locals.Add("loc2", 20)

        Dim statements As String = _
            "def test(a):" & vbLf & _
            "  return (a, a * a, a ** .5)" & vbLf & _
            "def add(a, b):" & vbLf & _
            "  return a + b" & vbLf & _
            "v1 = test(loc1)[2] + g1" & vbLf & _
            "v2 = add(g2, loc1)"

        ' Execute once to eliminate initialization overhead.
        engine.Execute(statements, testModule, locals)
        Const c_iterations As Integer = 1000

        Dim st As New Stopwatch
        st.Start()

        For i As Integer = 1 To c_iterations
            engine.Execute(statements, testModule, locals)
        Next

        st.Stop()
        Dim executed As Double = st.ElapsedTicks

        Dim cc As CompiledCode = engine.Compile(statements)
        ' Execute once to eliminate initialization overhead.
        cc.Execute(testModule, locals)

        st.Reset()
        st.Start()

        For i As Integer = 1 To c_iterations
            cc.Execute(testModule, locals)
        Next

        st.Stop()
        Dim compiled As Double = st.ElapsedTicks

        Console.WriteLine("Compiling every time takes {0:F} times longer.", _
            executed / compiled)
    End Sub

End Class

' This code produces output similar to the following:
'
'Compiling every time takes 145.06 times longer.
C# CopyCode image Copy Code
using System;
using System.Collections.Generic;
using System.Diagnostics;
using IronPython.Hosting;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        EngineModule testModule = engine.CreateModule("tm", true);
        testModule.Globals.Add("g1", 1000);
        testModule.Globals.Add("g2", 2000);

        Dictionary<string, object> locals = new Dictionary<string, object>();
        locals.Add("loc1", 10);
        locals.Add("loc2", 20);

        string statements = "def test(a):\n" +
                            "  return (a, a * a, a ** .5)\n" +
                            "def add(a, b):\n" +
                            "  return a + b\n" +
                            "v1 = test(loc1)[2] + g1\n" +
                            "v2 = add(g2, loc1)";

        // Execute once to eliminate initialization overhead.
        engine.Execute(statements, testModule, locals);
        const int c_iterations = 1000;

        Stopwatch st = new Stopwatch();
        st.Start();

        for (int i = 1; i <= c_iterations; i++)
        {
            engine.Execute(statements, testModule, locals);
        }

        st.Stop();
        double executed = st.ElapsedTicks;

        CompiledCode cc = engine.Compile(statements);
        // Execute once to eliminate initialization overhead.
        cc.Execute(testModule, locals);

        st.Reset();
        st.Start();

        for (int i = 1; i <= c_iterations; i++)
        {
            cc.Execute(testModule, locals);
        }

        st.Stop();
        double compiled = st.ElapsedTicks;

        Console.WriteLine("Compiling every time takes {0:F} times longer.", executed / compiled);
    }
}

/* This code produces output similar to the following:

Compiling every time takes 145.06 times longer.
 */

Expand image Inheritance Hierarchy

System.Object
IronPython.Hosting.CompiledCode

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

CompiledCode Members
IronPython.Hosting Namespace
To learn more about this product, make a suggestion, or file a bug, go to the IronPython site.


CompiledCode Members
See Also Methods
CollapseAll image DropDown image

Represents a set of statements that have been compiled.

The following tables list the members exposed by the CompiledCode type.

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | Execute | Overloaded. Executes the compiled code.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
 | ReferenceEquals | (Inherited from Object.)
Public method | ToString | Overridden. A string containing information about the compiled code.
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

CompiledCode Class
IronPython.Hosting Namespace


CompiledCode Methods
See Also
CollapseAll image DropDown image

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | Execute | Overloaded. Executes the compiled code.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
 | ReferenceEquals | (Inherited from Object.)
Public method | ToString | Overridden. A string containing information about the compiled code.
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

CompiledCode Class


CompiledCode.Execute Method
See Also
CollapseAll image DropDown image

Executes the compiled code.

Expand image Overload List

Name | Description
CompiledCode.Execute () | Executes the compiled statements in the scope of the default module.
CompiledCode.Execute (EngineModule) | Executes the compiled statements in the scope of the specified module.
CompiledCode.Execute (EngineModule, Generic IDictionary) | Executes the compiled statements in the scope of the specified module, using the specified local variables.

Expand image See Also

Reference

CompiledCode Class
CompiledCode Members


CompiledCode.Execute Method ()
See Also Example
collapseAll image DropDown image

Executes the compiled statements in the scope of the default module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Execute
Visual Basic (Usage)
Dim instance As CompiledCode

instance.Execute
C#
public void Execute ()
C++
public:
void Execute ()
J#
public void Execute ()
JScript
public function Execute ()

Expand image Exceptions

Exception type | Condition
PythonSystemExitException | The compiled code calls sys.exit.
PythonNameErrorException | The compiled code contains a symbol that cannot be resolved in the scope of the default module.

Expand image Remarks

This method throws any exceptions raised by the compiled code, or caused by the absence of expected variables.

New names defined by the compiled code, such as variables and functions, are added to the global dictionary of the default module. If you want to supply a local dictionary, use the Execute(EngineModule,Generic IDictionary) method overload.

Expand image Example

The following code example demonstrates the advantage of executing compiled code repeatedly, instead of compiling every time.

The code example executes a set of statements 1000 times, using the PythonEngine.Execute(String) method overload. The statements are the compiled using the PythonEngine.Compile method, and the compiled code is executed 1000 times. The ratio of the elapsed times is displayed.

Before each timing, the method to be tested is executed once to eliminate any initialization time from the timed interval.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Diagnostics
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine

        engine.Globals.Add("g1", 1000)
        engine.Globals.Add("g2", 2000)

        Dim statements As String = _
            "def test(a):" & vbLf & _
            "  return (a, a * a, a ** .5)" & vbLf & _
            "def add(a, b):" & vbLf & _
            "  return a + b" & vbLf & _
            "v1 = test(22)[2] + g1" & vbLf & _
            "v2 = add(g2, 1491)"

        ' Execute once to eliminate initialization overhead.
        engine.Execute(statements)
        Const c_iterations As Integer = 1000

        Dim st As New Stopwatch
        st.Start()

        For i As Integer = 1 To c_iterations
            engine.Execute(statements)
        Next

        st.Stop()
        Dim executed As Double = st.ElapsedTicks

        Dim cc As CompiledCode = engine.Compile(statements)
        ' Execute once to eliminate initialization overhead.
        cc.Execute()

        st.Reset()
        st.Start()

        For i As Integer = 1 To c_iterations
            cc.Execute()
        Next

        st.Stop()
        Dim compiled As Double = st.ElapsedTicks

        Console.WriteLine("Compiling every time takes {0:F} times longer.", _
            executed / compiled)
    End Sub

End Class

' This code produces output similar to the following:
'
'Compiling every time takes 156.35 times longer.
C# CopyCode image Copy Code
using System;
using System.Diagnostics;
using IronPython.Hosting;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        engine.Globals.Add("g1", 1000);
        engine.Globals.Add("g2", 2000);

        string statements = "def test(a):\n" +
                            "  return (a, a * a, a ** .5)\n" +
                            "def add(a, b):\n" +
                            "  return a + b\n" +
                            "v1 = test(22)[2] + g1\n" +
                            "v2 = add(g2, 1491)";

        // Execute once to eliminate initialization overhead.
        engine.Execute(statements);
        const int c_iterations = 1000;

        Stopwatch st = new Stopwatch();
        st.Start();

        for (int i = 1; i <= c_iterations; i++)
        {
            engine.Execute(statements);
        }

        st.Stop();
        double executed = st.ElapsedTicks;

        CompiledCode cc = engine.Compile(statements);
        // Execute once to eliminate initialization overhead.
        cc.Execute();

        st.Reset();
        st.Start();

        for (int i = 1; i <= c_iterations; i++)
        {
            cc.Execute();
        }

        st.Stop();
        double compiled = st.ElapsedTicks;

        Console.WriteLine("Compiling every time takes {0:F} times longer.", executed / compiled);
    }
}

/* This code produces output similar to the following:

Compiling every time takes 156.35 times longer.
 */

Expand image See Also

Reference

CompiledCode Class
CompiledCode Members


CompiledCode.Execute Method (EngineModule)
See Also Example
collapseAll image DropDown image

Executes the compiled statements in the scope of the specified module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Execute ( _
    engineModule As EngineModule _
)
Visual Basic (Usage)
Dim instance As CompiledCode
Dim engineModule As EngineModule

instance.Execute(engineModule)
C#
public void Execute (
    EngineModule engineModule
)
C++
public:
void Execute (
    EngineModule^ engineModule
)
J#
public void Execute (
    EngineModule engineModule
)
JScript
public function Execute (
    engineModule : EngineModule
)

Parameters

engineModule

The module in whose scope the compiled code is executed.

Expand image Exceptions

Exception type | Condition
PythonSystemExitException | The compiled code calls sys.exit.
PythonNameErrorException | The compiled code contains a symbol that cannot be resolved in the scope of engineModule.

Expand image Remarks

This method throws any exceptions raised by the compiled code, or caused by the absence of expected variables.

New names defined by the compiled code, such as variables and functions, are added to the global dictionary of engineModule. If you want to supply a local dictionary, use the Execute(EngineModule,Generic IDictionary) method overload.

Expand image Example

The following code example demonstrates the advantage of executing compiled code repeatedly, instead of compiling every time.

The code example creates a new module with two global variables and executes a set of statements 1000 times, using the PythonEngine.Execute(String,EngineModule) method overload. The statements are then compiled using the PythonEngine.Compile method, and the compiled code is executed 1000 times. The ratio of the elapsed times is displayed.

Before each timing, the method to be tested is executed once to eliminate any initialization time from the timed interval.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Diagnostics
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine

        Dim testModule As EngineModule = engine.CreateModule("tm", True)
        testModule.Globals.Add("g1", 1000)
        testModule.Globals.Add("g2", 2000)

        Dim statements As String = _
            "def test(a):" & vbLf & _
            "  return (a, a * a, a ** .5)" & vbLf & _
            "def add(a, b):" & vbLf & _
            "  return a + b" & vbLf & _
            "v1 = test(22)[2] + g1" & vbLf & _
            "v2 = add(g2, 1491)"

        ' Execute once to eliminate initialization overhead.
        engine.Execute(statements, testModule)
        Const c_iterations As Integer = 1000

        Dim st As New Stopwatch
        st.Start()

        For i As Integer = 1 To c_iterations
            engine.Execute(statements, testModule)
        Next

        st.Stop()
        Dim executed As Double = st.ElapsedTicks

        Dim cc As CompiledCode = engine.Compile(statements)
        ' Execute once to eliminate initialization overhead.
        cc.Execute(testModule)

        st.Reset()
        st.Start()

        For i As Integer = 1 To c_iterations
            cc.Execute(testModule)
        Next

        st.Stop()
        Dim compiled As Double = st.ElapsedTicks

        Console.WriteLine("Compiling every time takes {0:F} times longer.", _
            executed / compiled)
    End Sub

End Class

' This code produces output similar to the following:
'
'Compiling every time takes 154.76 times longer.
C# CopyCode image Copy Code
using System;
using System.Diagnostics;
using IronPython.Hosting;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        EngineModule testModule = engine.CreateModule("tm", true);
        testModule.Globals.Add("g1", 1000);
        testModule.Globals.Add("g2", 2000);

        string statements = "def test(a):\n" +
                            "  return (a, a * a, a ** .5)\n" +
                            "def add(a, b):\n" +
                            "  return a + b\n" +
                            "v1 = test(22)[2] + g1\n" +
                            "v2 = add(g2, 1491)";

        // Execute once to eliminate initialization overhead.
        engine.Execute(statements, testModule);
        const int c_iterations = 1000;

        Stopwatch st = new Stopwatch();
        st.Start();

        for (int i = 1; i <= c_iterations; i++)
        {
            engine.Execute(statements, testModule);
        }

        st.Stop();
        double executed = st.ElapsedTicks;

        CompiledCode cc = engine.Compile(statements);
        // Execute once to eliminate initialization overhead.
        cc.Execute(testModule);

        st.Reset();
        st.Start();

        for (int i = 1; i <= c_iterations; i++)
        {
            cc.Execute(testModule);
        }

        st.Stop();
        double compiled = st.ElapsedTicks;

        Console.WriteLine("Compiling every time takes {0:F} times longer.", executed / compiled);
    }
}

/* This code produces output similar to the following:

Compiling every time takes 154.76 times longer.
 */

Expand image See Also

Reference

CompiledCode Class
CompiledCode Members


CompiledCode.Execute Method (EngineModule, Generic IDictionary)
See Also Example
collapseAll image DropDown image

Executes the compiled statements in the scope of the specified module, using the specified local variables.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Execute ( _
    engineModule As EngineModule, _
    locals As IDictionary(Of String, Object) _
)
Visual Basic (Usage)
Dim instance As CompiledCode
Dim engineModule As EngineModule
Dim locals As IDictionary(Of String, Object)

instance.Execute(engineModule, locals)
C#
public void Execute (
    EngineModule engineModule,
    IDictionary<string,Object> locals
)
C++
public:
void Execute (
    EngineModule^ engineModule,
    IDictionary<String^, Object^>^ locals
)
J#
public void Execute (
    EngineModule engineModule,
    IDictionary<String,Object> locals
)
JScript
public function Execute (
    engineModule : EngineModule,
    locals : IDictionary<String,Object>
)

Parameters

engineModule

The module in whose scope the compiled code is executed.

locals

A Dictionary of objects with string keys, representing local variables and their values to be used when executing scriptCode.

Expand image Exceptions

Exception type | Condition
PythonSystemExitException | The compiled code calls sys.exit.
PythonNameErrorException | The compiled code contains a symbol that cannot be resolved in the scope of engineModule and locals.

Expand image Remarks

This method throws any exceptions raised by the compiled code, or caused by the absence of expected variables.

Expand image Example

The following code example demonstrates the advantage of executing compiled code repeatedly, instead of compiling every time.

The code example creates a new module with two global variables and executes a set of statements 1000 times, using the PythonEngine.Execute(String,EngineModule,Generic IDictionary) method overload and supplying dictionary of local variables. The statements are then compiled using the PythonEngine.Compile method, and the compiled code is executed 1000 times, using the same dictionary of locals. The ratio of the elapsed times is displayed.

Before each timing, the method to be tested is executed once to eliminate any initialization time from the timed interval.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine

        Dim testModule As EngineModule = engine.CreateModule("tm", True)
        testModule.Globals.Add("g1", 1000)
        testModule.Globals.Add("g2", 2000)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("loc1", 10)
        locals.Add("loc2", 20)

        Dim statements As String = _
            "def test(a):" & vbLf & _
            "  return (a, a * a, a ** .5)" & vbLf & _
            "def add(a, b):" & vbLf & _
            "  return a + b" & vbLf & _
            "v1 = test(loc1)[2] + g1" & vbLf & _
            "v2 = add(g2, loc1)"

        ' Execute once to eliminate initialization overhead.
        engine.Execute(statements, testModule, locals)
        Const c_iterations As Integer = 1000

        Dim st As New Stopwatch
        st.Start()

        For i As Integer = 1 To c_iterations
            engine.Execute(statements, testModule, locals)
        Next

        st.Stop()
        Dim executed As Double = st.ElapsedTicks

        Dim cc As CompiledCode = engine.Compile(statements)
        ' Execute once to eliminate initialization overhead.
        cc.Execute(testModule, locals)

        st.Reset()
        st.Start()

        For i As Integer = 1 To c_iterations
            cc.Execute(testModule, locals)
        Next

        st.Stop()
        Dim compiled As Double = st.ElapsedTicks

        Console.WriteLine("Compiling every time takes {0:F} times longer.", _
            executed / compiled)
    End Sub

End Class

' This code produces output similar to the following:
'
'Compiling every time takes 145.06 times longer.
C# CopyCode image Copy Code
using System;
using System.Collections.Generic;
using System.Diagnostics;
using IronPython.Hosting;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        EngineModule testModule = engine.CreateModule("tm", true);
        testModule.Globals.Add("g1", 1000);
        testModule.Globals.Add("g2", 2000);

        Dictionary<string, object> locals = new Dictionary<string, object>();
        locals.Add("loc1", 10);
        locals.Add("loc2", 20);

        string statements = "def test(a):\n" +
                            "  return (a, a * a, a ** .5)\n" +
                            "def add(a, b):\n" +
                            "  return a + b\n" +
                            "v1 = test(loc1)[2] + g1\n" +
                            "v2 = add(g2, loc1)";

        // Execute once to eliminate initialization overhead.
        engine.Execute(statements, testModule, locals);
        const int c_iterations = 1000;

        Stopwatch st = new Stopwatch();
        st.Start();

        for (int i = 1; i <= c_iterations; i++)
        {
            engine.Execute(statements, testModule, locals);
        }

        st.Stop();
        double executed = st.ElapsedTicks;

        CompiledCode cc = engine.Compile(statements);
        // Execute once to eliminate initialization overhead.
        cc.Execute(testModule, locals);

        st.Reset();
        st.Start();

        for (int i = 1; i <= c_iterations; i++)
        {
            cc.Execute(testModule, locals);
        }

        st.Stop();
        double compiled = st.ElapsedTicks;

        Console.WriteLine("Compiling every time takes {0:F} times longer.", executed / compiled);
    }
}

/* This code produces output similar to the following:

Compiling every time takes 145.06 times longer.
 */

Expand image See Also

Reference

CompiledCode Class
CompiledCode Members


CompiledCode.ToString Method
See Also Example
collapseAll image DropDown image

A string containing information about the compiled code.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Overrides Function ToString As String
Visual Basic (Usage)
Dim instance As CompiledCode
Dim returnValue As String

returnValue = instance.ToString
C#
public override string ToString ()
C++
public:
virtual String^ ToString () override
J#
public String ToString ()
JScript
public override function ToString () : String

Return Value

A string indicating where the code was compiled from. For example, the file name that was specified for the PythonEngine.CompileFile method, or stdin if the code was compiled with the PythonEngine.Compile method.

Expand image Remarks

The ToString does not provide a listing of the original source code.

Expand image Example

The following code example shows examples of output from the ToString method.

Visual Basic CopyCode image Copy Code
            cc = engine.Compile(statements)
            Console.WriteLine(cc.ToString())

            ccf = engine.CompileFile(".\test\TestE.py")
            Console.WriteLine(ccf.ToString())

' This code produces output similar to the following:
'<code <stdin>>
'<code .\test\TestE.py>
C# CopyCode image Copy Code
            cc = engine.Compile(statements)
            Console.WriteLine(cc.ToString())

            ccf = engine.CompileFile(".\test\TestE.py")
            Console.WriteLine(ccf.ToString())

/* This code produces output similar to the following:
<code <stdin>>
<code .\test\TestE.py>
 */

Expand image See Also

Reference

CompiledCode Class
CompiledCode Members


EngineModule Class
See Also Example Members
CollapseAll image DropDown image

Represents a global scope in which the IronPython execution engine can maintain variables and execute code.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Class EngineModule
Visual Basic (Usage)
Dim instance As EngineModule
C#
public class EngineModule
C++
public ref class EngineModule
J#
public class EngineModule
JScript
public class EngineModule

Expand image Remarks

Modules are required in order to execute code. Every PythonEngine instance has a default module, which can be obtained using the DefaultModule property. The default module is provided for ease of use when you only need a single module. You can create additional modules in order to provide different scopes for executing code.

Every module has a dictionary of global variables, which the host application can access using the Globals property. This dictionary is a Dictionary of objects with string keys. The host can supply the dictionary when creating the module, or allow an empty dictionary to be created. The host can use the properties and methods of Dictionary to add, remove, and change the values of a module's global variables. The host application typically adds variables that refer to objects created by the host application, so that the IronPython code can manipulate them.

A host application can create modules by using the IronPython.Hosting.PythonEngine.CreateModule method or the PythonEngine.CreateOptimizedModule method.

Expand image Example

The following code example creates a Dictionary of objects with string keys, representing global variables for a new module, populates the dictionary with two variables, and then creates a published module named "tm", with the predefined global variables.

The code example uses the IronPython.Hosting.PythonEngine.Evaluate method to evaluate an expression containing the global variables in the scope of the module, and then deletes one of the global variables.

The code example uses the IronPython.Hosting.PythonEngine.Execute method to execute a series of statements in the module, creating a function and additional global variables, calling the function, and printing the output of the function.

Finally, the code example imports the module into the scope of the default module, and uses the dir function to display the contents of the imported module.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Collections.Generic
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' Create an initial set of global variables for the module.
        Dim globals As New Dictionary(Of String, Object)
        globals.Add("forty", 40)
        globals.Add("thirty", 30)

        ' Create a published module with an initial set of global
        ' variables.
        Dim testModule As EngineModule = _
            engine.CreateModule("tm", globals, True)

        Console.WriteLine("forty + thirty = {0}", _
            engine.Evaluate("forty + thirty", testModule))

        testModule.Globals.Remove("forty")

        Dim statements As String = _
            "def sum(a, b, c):" & vbLf & _
            "  return a + b + c" & vbLf & _
            "x = 32" & vbLf & _
            "y = 100" & vbLf & _
            "z = sum(x, y, thirty)"

        engine.Execute(statements, testModule)
        Console.WriteLine("z = {0}", testModule.Globals("z"))

        engine.Execute("import tm")
        Console.WriteLine(engine.Evaluate("dir(tm)"))

    End Sub
End Class

' This code example produces the following output:
'
'forty + thirty = 70
'z = 162
'['__builtins__', '__dict__', '__name__', 'sum', 'thirty', 'x', 'y', 'z']
'
C# CopyCode image Copy Code
using System;
using System.Collections.Generic;
using IronPython.Hosting;

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // Create an initial set of global variables for the module.
        Dictionary<string,object> globals = new Dictionary<string,object>();
        globals.Add("forty", 40);
        globals.Add("thirty", 30);

        // Create a published module with an initial set of global
        // variables.
        EngineModule testModule = engine.CreateModule("tm", globals, true);

        Console.WriteLine("forty + thirty = {0}",
            engine.Evaluate("forty + thirty", testModule));

        testModule.Globals.Remove("forty");

        string statements = "def sum(a, b, c):\n" +
                            "  return a + b + c\n" +
                            "x = 32\n" +
                            "y = 100\n" +
                            "z = sum(x, y, thirty)";

        engine.Execute(statements, testModule);
        Console.WriteLine("z = {0}", testModule.Globals["z"]);

        engine.Execute("import tm");
        Console.WriteLine(engine.Evaluate("dir(tm)"));
    }
}

/* This code example produces the following output:

forty + thirty = 70
z = 162
['__builtins__', '__dict__', '__name__', 'sum', 'thirty', 'x', 'y', 'z']
 */

Expand image Inheritance Hierarchy

System.Object
IronPython.Hosting.EngineModule
IronPython.Hosting.OptimizedEngineModule

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

EngineModule Members


EngineModule Members
See Also Methods Properties
CollapseAll image DropDown image

Represents a global scope in which the IronPython execution engine can maintain variables and execute code.

The following tables list the members exposed by the EngineModule type.

Expand image Public Properties

 | Name | Description
Public property | Globals | Gets the dictionary of global variables for the module.
Public property | Name | Gets the name of the module.
Public property | TrueDivision | Gets or sets a value that specifies whether division in the current module is done in backward-compatibility mode.
Top

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | Import | Imports a module into the global dictionary of the current module.
 | ReferenceEquals | (Inherited from Object.)
Public method | ToString | Overridden. Returns the type name and the name of the module.
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

EngineModule Class


EngineModule Methods
See Also
CollapseAll image DropDown image

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | Import | Imports a module into the global dictionary of the current module.
 | ReferenceEquals | (Inherited from Object.)
Public method | ToString | Overridden. Returns the type name and the name of the module.
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

EngineModule Class


EngineModule.Import Method
See Also
collapseAll image DropDown image

Imports a module into the global dictionary of the current module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Import ( _
    moduleName As String _
) As Object
Visual Basic (Usage)
Dim instance As EngineModule
Dim moduleName As String
Dim returnValue As Object

returnValue = instance.Import(moduleName)
C#
public Object Import (
    string moduleName
)
C++
public:
Object^ Import (
    String^ moduleName
)
J#
public Object Import (
    String moduleName
)
JScript
public function Import (
    moduleName : String
) : Object

Parameters

moduleName

The name of the module to import. For example, "System.Threading" imports that namespace as "Threading".

Return Value

A reference to the imported module.

Expand image Remarks

When a namespace from the .NET Framework is imported, the name used in the global symbol table is the last segment of the namespace name. Thus, "System.Collections.Generic" is imported as "Generic".

Use the Import method, specifying "clr" for moduleName, to import ClrModule into a module. The host can cache the reference, and use the methods of ClrModule to load assemblies and make them available for import.

Note Note

It is sufficient to cache ClrModule once for any given PythonEngine instance. The same ClrModule instance is used for every EngineModule that imports "clr" and is created with that PythonEngine instance.

The IronPython import statement throws an ImportError if the module is not found. However, the Import method does not throw an exception if the module is not found. This might change in a future release. See the issue discussed here.

Expand image See Also

Reference

EngineModule Class
EngineModule Members


EngineModule.ToString Method
See Also
collapseAll image DropDown image

Returns the type name and the name of the module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Overrides Function ToString As String
Visual Basic (Usage)
Dim instance As EngineModule
Dim returnValue As String

returnValue = instance.ToString
C#
public override string ToString ()
C++
public:
virtual String^ ToString () override
J#
public String ToString ()
JScript
public override function ToString () : String

Return Value

A string containing the type name and the name of the module, separated by a colon.

Expand image See Also

Reference

EngineModule Class
EngineModule Members


EngineModule Properties
See Also
CollapseAll image DropDown image

Expand image Public Properties

 | Name | Description
Public property | Globals | Gets the dictionary of global variables for the module.
Public property | Name | Gets the name of the module.
Public property | TrueDivision | Gets or sets a value that specifies whether division in the current module is done in backward-compatibility mode.
Top

Expand image See Also

Reference

EngineModule Class


EngineModule.Globals Property
See Also Example
CollapseAll image DropDown image

Gets the dictionary of global variables for the module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public ReadOnly Property Globals As IDictionary(Of String, Object)
Visual Basic (Usage)
Dim instance As EngineModule
Dim value As IDictionary(Of String, Object)

value = instance.Globals
C#
public IDictionary<string,Object> Globals { get; }
C++
public:
property IDictionary<String^, Object^>^ Globals {
    IDictionary<String^, Object^>^ get ();
}
J#
/** @property */
public IDictionary<String,Object> get_Globals ()
JScript
public function get Globals () : IDictionary<String,Object>

Property Value

A IDictionary of objects with string keys, representing the global variables of the module and their values.

Expand image Remarks

You can add, remove, and change global variables for the module by using the methods of the IDictionary. This has the same effect as adding, deleting, and changing the global variables using IronPython code.

To assign global variables when creating a module, use the CreateModule(String,Generic IDictionary,Boolean) method overload.

Expand image Example

The following code example uses the Globals property to list the global variables in a module, and to remove a global variable. The output of the dir function is shown for comparison.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Collections.Generic
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' Create an initial set of global variables for the module.
        Dim globals As New Dictionary(Of String, Object)
        globals.Add("forty", 40)
        globals.Add("thirty", 30)

        ' Create a published module with an initial set of global
        ' variables.
        Dim testModule As EngineModule = _
            engine.CreateModule("tm", globals, True)

        Console.WriteLine("Contents of Globals:")
        Dim key As String
        For Each key In testModule.Globals.Keys
            Console.WriteLine(vbTab + "{0}", key)
        Next key
        testModule.Globals.Remove("forty")

        Dim statements As String = _
            "def sum(a, b, c):" & vbLf & _
            "  return a + b + c" & vbLf & _
            "x = 32" & vbLf & _
            "y = 100" & vbLf & _
            "print sum(x, y, thirty)"

        engine.Execute(statements, testModule)

        Console.WriteLine("Contents of Globals:")
        For Each key In testModule.Globals.Keys
            Console.WriteLine(vbTab & "{0}", key)
        Next key
        Console.WriteLine(engine.Evaluate("dir()", testModule))

    End Sub
End Class

' This code example produces the following output:
'
'Contents of Globals:
'        forty
'        thirty
'        __name__
'        __builtins__
'162
'Contents of Globals:
'        sum
'        thirty
'        __name__
'        __builtins__
'        x
'        y
'['__builtins__', '__name__', 'sum', 'thirty', 'x', 'y']
'
C# CopyCode image Copy Code
using System;
using System.Collections.Generic;
using IronPython.Hosting;

delegate double Example(int p1);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // Create an initial set of global variables for the module.
        Dictionary<string,object> globals = new Dictionary<string,object>();
        globals.Add("forty", 40);
        globals.Add("thirty", 30);

        // Create a published module with an initial set of global
        // variables.
        EngineModule testModule = engine.CreateModule("tm", globals, true);

        Console.WriteLine("Contents of Globals:");
        foreach (string key in testModule.Globals.Keys)
            Console.WriteLine("\t{0}", key);

        testModule.Globals.Remove("forty");

        string statements = "def sum(a, b, c):\n" +
                            "  return a + b + c\n" +
                            "x = 32\n" +
                            "y = 100\n" +
                            "print sum(x, y, thirty)";

        engine.Execute(statements, testModule);

        Console.WriteLine("Contents of Globals:");
        foreach (string key in testModule.Globals.Keys)
            Console.WriteLine("\t{0}", key);

        Console.WriteLine(engine.Evaluate("dir()", testModule));
    }
}

/* This code example produces the following output:

Contents of Globals:
        forty
        thirty
        __name__
        __builtins__
162
Contents of Globals:
        sum
        thirty
        __name__
        __builtins__
        x
        y
['__builtins__', '__name__', 'sum', 'thirty', 'x', 'y']
 */

Expand image See Also

Reference

EngineModule Class
EngineModule Members


EngineModule.Name Property
See Also
CollapseAll image DropDown image

Gets the name of the module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public ReadOnly Property Name As String
Visual Basic (Usage)
Dim instance As EngineModule
Dim value As String

value = instance.Name
C#
public string Name { get; }
C++
public:
property String^ Name {
    String^ get ();
}
J#
/** @property */
public String get_Name ()
JScript
public function get Name () : String

Property Value

A string that represents the name of the module.

Expand image Remarks

The name is set using the name parameter of the IronPython.Hosting.PythonEngine.CreateModule method, when you create the module.

If the EngineModule was published, by specifying true for the publish parameter of the IronPython.Hosting.PythonEngine.CreateModule method, you can use the module name with the import statement in IronPython code, to import a module into the scope of another module, or as a key for the sys.modules list, to obtain a reference to the module.

Expand image See Also

Reference

EngineModule Class
EngineModule Members


EngineModule.TrueDivision Property
See Also Example
CollapseAll image DropDown image

Gets or sets a value that specifies whether division in the current module is done in backward-compatibility mode.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Property TrueDivision As Boolean
Visual Basic (Usage)
Dim instance As EngineModule
Dim value As Boolean

value = instance.TrueDivision

instance.TrueDivision = value
C#
public bool TrueDivision { get; set; }
C++
public:
property bool TrueDivision {
    bool get ();
    void set (bool value);
}
J#
/** @property */
public boolean get_TrueDivision ()

/** @property */
public void set_TrueDivision (boolean value)
JScript
public function get TrueDivision () : boolean

public function set TrueDivision (value : boolean)

Property Value

true if division is done according to the future meaning; otherwise false. The default value is false.

Expand image Remarks

In compatibility mode, the division operator produces different results for "1/2" and "1.0/2.0". In the first case integer division is performed, resulting in the value 0. In the second case floating point division is performed, resulting in the value 0.5.

By contrast, when TrueDivision is set to true, floating division is always performed, even if the arguments are integers.

Note Important

In IronPython 1.0, the behavior of compiled code is only affected by the setting of the TrueDivision property for the default module of a PythonEngine instance. This is because in IronPython 1.0 all code is compiled in the context of the default module, no matter where it is executed. When code is compiled to Microsoft intermediate language (MSIL), only one behavior of the division operator can be used. For example, code executed using the PythonEngine.Execute(String,EngineModule) method does not use the TrueDivision setting of the specified module; instead the setting for the default module is used. This behavior will change in a future release. The behavior of the Evaluate method and the EvaluateAs generic method is not affected.

Expand image Example

Example 1: The following code example demonstrates the behavior of division when the TrueDivision property of the default module is set to the default value, false, and when it is changed to true.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Module Example

    Sub Main()

        Dim engine As New PythonEngine()

        Dim em As EngineModule = engine.CreateModule()
        engine.Execute("print 1/2", em)

        engine.DefaultModule.TrueDivision = True

        engine.Execute("print 1/2", em)

    End Sub
End Module

' In IronPython 1.0, this code example produces the
' following output:
'
'0
'0.5
C# CopyCode image Copy Code
        PythonEngine engine = new PythonEngine();
        EngineModule em = engine.CreateModule("em", true);

        Object a = engine.Evaluate("1/2", em);
        Double b = engine.EvaluateAs<Double>("1/2", em);
        Console.WriteLine("Compatibility mode: {0}, {1}", a, b);

        em.TrueDivision = true;

        a = engine.Evaluate("1/2", em);
        b = engine.EvaluateAs<Double>("1/2", em);
        Console.WriteLine("Compatibility mode: {0}, {1}", a, b);

Output:
Compatibility mode: 0, 0
Compatibility mode: 0.5, 0.5

Example 2: The following code fragment shows the effect of the TrueDivision property on the IronPython.Hosting.PythonEngine.Evaluate method and the IronPython.Hosting.PythonEngine.EvaluateAs generic method.

CopyCode image Copy Code
        Dim engine As New PythonEngine()
        Dim em As EngineModule = engine.CreateModule("em", True)

        Dim a As Object = engine.Evaluate("1/2", em)
        Dim b As Double = engine.EvaluateAs(Of Double)("1/2", em)
        Console.WriteLine("Compatibility mode: {0}, {1}", a, b)

        em.TrueDivision = True

        a = engine.Evaluate("1/2", em)
        b = engine.EvaluateAs(Of Double)("1/2", em)
        Console.WriteLine("Compatibility mode: {0}, {1}", a, b)

Output:
Compatibility mode: 0, 0
Compatibility mode: 0.5, 0.5
C# CopyCode image Copy Code
        PythonEngine engine = new PythonEngine();
        EngineModule em = engine.CreateModule("em", true);

        Object a = engine.Evaluate("1/2", em);
        Double b = engine.EvaluateAs<Double>("1/2", em);
        Console.WriteLine("Compatibility mode: {0}, {1}", a, b);

        em.TrueDivision = true;

        a = engine.Evaluate("1/2", em);
        b = engine.EvaluateAs<Double>("1/2", em);
        Console.WriteLine("Compatibility mode: {0}, {1}", a, b);

Output:
Compatibility mode: 0, 0
Compatibility mode: 0.5, 0.5

Expand image See Also

Reference

EngineModule Class
EngineModule Members


EngineOptions Class
See Also Members
CollapseAll image DropDown image

Provides PythonEngine execution options.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Class EngineOptions
Visual Basic (Usage)
Dim instance As EngineOptions
C#
public class EngineOptions
C++
public ref class EngineOptions
J#
public class EngineOptions
JScript
public class EngineOptions

Expand image Remarks

To set execution options for a new PythonEngine, set the properties of an instance of EngineOptions and then pass the instance to the appropriate constructor. The property values of the EngineOptions class determine the exception information displayed by the FormatException method. For code examples showing the use of this class, see the ClrDebuggingEnabled property and the ShowClrExceptions property.

Expand image Inheritance Hierarchy

System.Object
IronPython.Hosting.EngineOptions

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

EngineOptions Members


EngineOptions Members
See Also Constructors Methods Properties
CollapseAll image DropDown image

Provides PythonEngine execution options.

The following tables list the members exposed by the EngineOptions type.

Expand image Public Constructors

 | Name | Description
Public method | EngineOptions | Initializes a new instance of the EngineOptions class with default properties.
Top

Expand image Public Properties

 | Name | Description
Public property | ClrDebuggingEnabled | Gets or sets a value indicating whether common language runtime (CLR) debugging is enabled.
Public property | ExceptionDetail | Gets or sets a value indicating whether exception detail is to be displayed.
Public property | ShowClrExceptions | Gets or sets a value indicating whether common language runtime (CLR) exceptions are to be displayed.
Public property | SkipFirstLine | Gets or sets a value indicating whether the first line of the code is to be executed.
Top

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
 | ReferenceEquals | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

EngineOptions Class


EngineOptions Constructor
See Also
CollapseAll image DropDown image

Initializes a new instance of the EngineOptions class with default properties.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New EngineOptions
C#
public EngineOptions ()
C++
public:
EngineOptions ()
J#
public EngineOptions ()
JScript
public function EngineOptions ()

Expand image Remarks

By default, all properties of EngineOptions are set to false.

Expand image See Also

Reference

EngineOptions Class
EngineOptions Members


EngineOptions Methods
See Also
CollapseAll image DropDown image

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
 | ReferenceEquals | (Inherited from Object.)
Public method | ToString | (Inherited from Object.)
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

EngineOptions Class


EngineOptions Properties
See Also
CollapseAll image DropDown image

Expand image Public Properties

 | Name | Description
Public property | ClrDebuggingEnabled | Gets or sets a value indicating whether common language runtime (CLR) debugging is enabled.
Public property | ExceptionDetail | Gets or sets a value indicating whether exception detail is to be displayed.
Public property | ShowClrExceptions | Gets or sets a value indicating whether common language runtime (CLR) exceptions are to be displayed.
Public property | SkipFirstLine | Gets or sets a value indicating whether the first line of the code is to be executed.
Top

Expand image See Also

Reference

EngineOptions Class


EngineOptions.ClrDebuggingEnabled Property
See Also Example
CollapseAll image DropDown image

Gets or sets a value indicating whether common language runtime (CLR) debugging is enabled.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Property ClrDebuggingEnabled As Boolean
Visual Basic (Usage)
Dim instance As EngineOptions
Dim value As Boolean

value = instance.ClrDebuggingEnabled

instance.ClrDebuggingEnabled = value
C#
public bool ClrDebuggingEnabled { get; set; }
C++
public:
property bool ClrDebuggingEnabled {
    bool get ();
    void set (bool value);
}
J#
/** @property */
public boolean get_ClrDebuggingEnabled ()

/** @property */
public void set_ClrDebuggingEnabled (boolean value)
JScript
public function get ClrDebuggingEnabled () : boolean

public function set ClrDebuggingEnabled (value : boolean)

Property Value

true if common language runtime (CLR) debugging is enabled; otherwise, false.

Expand image Remarks

The ClrDebuggingEnabled property enables the debugging of script files with a CLR debugger.

  • CLR debugging is only effective when executing a script using the ExecuteFile or CompileFile methods.

  • CLR debugging is independent of the functionality provided by the TraceBack class.

  • CLR debugging should not be used for unlimited execution. Setting ClrDebuggingEnabledtrue causes increased memory use. IronPython uses the AssemblyBuilder class to support CLR debugging. This prevents the memory used by the generated code from being reclaimed until the AppDomain is unloaded. When ClrDebuggingEnabled is false IronPython compiles the Python script into a DynamicMethod object that does not support debugging. However, DynamicMethod objects are reclaimed by the garbage collector when they are no longer in use.

Expand image Example

The following code example creates an IronPython script raise.py that raises an exception. Instances of the PythonEngine are created using different EngineOptions objects to demonstrate the effect of the ClrDebuggingEnabled property. When the IronPython code is executed, it throws an exception that is displayed using the FormatException method.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.IO

Class Program
    Private Shared debuggableEngine As PythonEngine
    Private Shared debuggableEngineOptions As EngineOptions

    Shared Sub Main(ByVal args() As String)
        Dim raise() As String = {"x = 1", "class C(object):", "    def __init__(self):", "        self.attr = 1", "        raise ""Exception from py""", "c = C()", "# The following statement should not be executed.", "y = 1"}

        File.WriteAllLines("raise.py", raise)

        ' Execute the script using different property values.
        'RunScript(true, true, true)
        RunScript(True, True, False)
        'RunScript(true, false, true)
        RunScript(True, False, False)
        'RunScript(false, true, false)
        'RunScript(false, false, true)
        RunScript(False, True, False)
    End Sub 'Main

    Private Shared Sub RunScript(ByVal enabled As Boolean, ByVal show As Boolean, ByVal detail As Boolean)
        Try
            Console.WriteLine(vbLf + "ClrDebuggingEnabled = {0}, ShowClrExceptions = {1}, ExceptionDetail = {2}" + vbLf, enabled, show, detail)

            debuggableEngineOptions = New EngineOptions()
            debuggableEngineOptions.ClrDebuggingEnabled = enabled
            debuggableEngineOptions.ShowClrExceptions = show
            debuggableEngineOptions.ExceptionDetail = detail
            debuggableEngine = New PythonEngine(debuggableEngineOptions)
            debuggableEngine.ExecuteFile("raise.py")

        Catch e1 As IronPython.Runtime.Exceptions.StringException
            'Format the exception for display to the console.
            Console.Write(debuggableEngine.FormatException(e1))
        End Try

    End Sub 'RunScript
End Class 'Program

' This code example produces the following output:
'
'   ClrDebuggingEnabled = True, ShowClrExceptions = True, ExceptionDetail = False
'
'Traceback (most recent call last):
'  File C:\....\pythonEngine.engineOptions.cs, line 44, in RunScript
'  File raise.py, line 6, in Initialize
'  File raise.py, line 5, in __init__
'Exception from py
'CLR Exception:
'    StringException
':
'Exception from py
'
'ClrDebuggingEnabled = True, ShowClrExceptions = False, ExceptionDetail = False
'
'Traceback (most recent call last):
'  File C:\....\pythonEngine.engineOptions.cs, line 44, in RunScript
'  File debuggableSnippets2, line unknown, in Initialize
'  File debuggableSnippets2, line unknown, in __init__
'Exception from py
'
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.IO;

class Program
{
    private static PythonEngine debuggableEngine;
    private static EngineOptions debuggableEngineOptions;
    static void Main(string[] args)
    {
        String[] raise = new string[]
                {"x = 1", "class C(object):",
                "    def __init__(self):",
                "        self.attr = 1",
                "        raise \"Exception from py\"",
                "c = C()",

                "# The following statement should not be executed.",
                "y = 1"};
        File.WriteAllLines("raise.py", raise);

        // Execute the script using different property values.

        //RunScript(true, true, true);
        RunScript(true, true, false);
        //RunScript(true, false, true);
        RunScript(true, false, false);
        //RunScript(false, true, false);
        //RunScript(false, false, true);
        RunScript(false, true, false);

    }
    private static void RunScript(bool enabled, bool show, bool detail)
    {
        try
        {
            Console.WriteLine("\nClrDebuggingEnabled = {0}, ShowClrExceptions = {1}, ExceptionDetail = {2}\n", enabled, show, detail);

            debuggableEngineOptions = new EngineOptions();
            debuggableEngineOptions.ClrDebuggingEnabled = enabled;
            debuggableEngineOptions.ShowClrExceptions = show;
            debuggableEngineOptions.ExceptionDetail = detail;
            debuggableEngine = new PythonEngine(debuggableEngineOptions);
            debuggableEngine.ExecuteFile("raise.py");
        }

        catch (IronPython.Runtime.Exceptions.StringException e1)
        {
            //Format the exception for display to the console.
            Console.Write(debuggableEngine.FormatException(e1));

        }
    }

}
// This code example produces the following output:
/*
   ClrDebuggingEnabled = True, ShowClrExceptions = True, ExceptionDetail = False

Traceback (most recent call last):
  File C:\Projects\IronPython\pythonEngine.engineOptions\pythonEngine.engineOptions.cs, line 45, in RunScript
  File raise.py, line 6, in Initialize
  File raise.py, line 5, in __init__
Exception from py
CLR Exception:
    StringException
:
Exception from py

ClrDebuggingEnabled = True, ShowClrExceptions = False, ExceptionDetail = False

Traceback (most recent call last):
  File C:\Projects\IronPython\pythonEngine.engineOptions\pythonEngine.engineOptions.cs, line 45, in RunScript
  File debuggableSnippets2, line unknown, in Initialize
  File debuggableSnippets2, line unknown, in __init__
Exception from py

ClrDebuggingEnabled = False, ShowClrExceptions = True, ExceptionDetail = False

Traceback (most recent call last):
  File C:\Projects\IronPython\pythonEngine.engineOptions\pythonEngine.engineOptions.cs, line 45, in RunScript
  File , line 0, in raise.py##7
  File , line 0, in __init__
Exception from py
CLR Exception:
    StringException
:
Exception from py
*/

Expand image See Also

Reference

EngineOptions Class
EngineOptions Members


EngineOptions.ExceptionDetail Property
See Also
CollapseAll image DropDown image

Gets or sets a value indicating whether exception detail is to be displayed.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Property ExceptionDetail As Boolean
Visual Basic (Usage)
Dim instance As EngineOptions
Dim value As Boolean

value = instance.ExceptionDetail

instance.ExceptionDetail = value
C#
public bool ExceptionDetail { get; set; }
C++
public:
property bool ExceptionDetail {
    bool get ();
    void set (bool value);
}
J#
/** @property */
public boolean get_ExceptionDetail ()

/** @property */
public void set_ExceptionDetail (boolean value)
JScript
public function get ExceptionDetail () : boolean

public function set ExceptionDetail (value : boolean)

Property Value

true to display exception detail; otherwise, false.

Expand image Remarks

When ExceptionDetail is true, the common language runtime (CLR) call stack is displayed by the FormatException method with the exception.

Expand image See Also

Reference

EngineOptions Class
EngineOptions Members


EngineOptions.ShowClrExceptions Property
See Also
CollapseAll image DropDown image

Gets or sets a value indicating whether common language runtime (CLR) exceptions are to be displayed.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Property ShowClrExceptions As Boolean
Visual Basic (Usage)
Dim instance As EngineOptions
Dim value As Boolean

value = instance.ShowClrExceptions

instance.ShowClrExceptions = value
C#
public bool ShowClrExceptions { get; set; }
C++
public:
property bool ShowClrExceptions {
    bool get ();
    void set (bool value);
}
J#
/** @property */
public boolean get_ShowClrExceptions ()

/** @property */
public void set_ShowClrExceptions (boolean value)
JScript
public function get ShowClrExceptions () : boolean

public function set ShowClrExceptions (value : boolean)

Property Value

true if CLR exceptions are to be displayed by the FormatException method; otherwise, false.

Expand image Remarks

By default the FormatException method displays only the IronPython-specific information. To display the underlying CLR exceptions using the FormatException method set ShowClrExceptionstrue. The following sample output shows the difference in output for the true and false settings. For the full code example, see the ClrDebuggingEnabled method.

CopyCode image Copy Code
ClrDebuggingEnabled = True, ShowClrExceptions = True, ExceptionDetail = False

Traceback (most recent call last):
  File C:\Projects\IronPython\pythonEngine.engineOptions\pythonEngine.engineOptions.cs, line 45, in RunScript
  File raise.py, line 6, in Initialize
  File raise.py, line 5, in __init__
Exception from py
CLR Exception:
    StringException
:
Exception from py

ClrDebuggingEnabled = True, ShowClrExceptions = False, ExceptionDetail = False

Traceback (most recent call last):
  File C:\Projects\IronPython\pythonEngine.engineOptions\pythonEngine.engineOptions.cs, line 45, in RunScript
  File debuggableSnippets2, line unknown, in Initialize
  File debuggableSnippets2, line unknown, in __init__
Exception from py

Expand image See Also

Reference

EngineOptions Class
EngineOptions Members


EngineOptions.SkipFirstLine Property
See Also
CollapseAll image DropDown image

Gets or sets a value indicating whether the first line of the code is to be executed.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Property SkipFirstLine As Boolean
Visual Basic (Usage)
Dim instance As EngineOptions
Dim value As Boolean

value = instance.SkipFirstLine

instance.SkipFirstLine = value
C#
public bool SkipFirstLine { get; set; }
C++
public:
property bool SkipFirstLine {
    bool get ();
    void set (bool value);
}
J#
/** @property */
public boolean get_SkipFirstLine ()

/** @property */
public void set_SkipFirstLine (boolean value)
JScript
public function get SkipFirstLine () : boolean

public function set SkipFirstLine (value : boolean)

Property Value

true if the first line of code is to be skipped; otherwise, false.

Expand image Remarks

Skipping the first line of code is useful for executing UNIX scripts which contain the execute command in the first line.

The SkipFirstLine property applies only to script code executed by the PythonEngine, not to script code that is called as a result of the execution.

Expand image See Also

Reference

EngineOptions Class
EngineOptions Members


ModuleBinder Generic Delegate
See Also Example
CollapseAll image DropDown image

Returns a delegate of the specified type, bound to the specified IronPython module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Delegate Function ModuleBinder(Of T) ( _
    engineModule As EngineModule _
) As T
Visual Basic (Usage)
Dim instance As New ModuleBinder(Of T)(AddressOf HandlerMethod)
C#
public delegate T ModuleBinder<T> (
    EngineModule engineModule
)
C++
generic<typename T>
public delegate T ModuleBinder (
    EngineModule^ engineModule
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

T

The type of delegate that is returned.

Parameters

engineModule

The module the delegate of type T is bound to.

Return Value

A delegate of type T, bound to engineModule.

Expand image Remarks

The ModuleBinder generic delegate allows the host to create a delegate that represents a method body or a lambda expression that is not bound to any module, and then to bind that delegate to any module for execution or evaluation.

To create a ModuleBinder generic delegate for a lambda expression, use the CreateLambdaUnscoped method. To create a ModuleBinder generic delegate for a method body, use the CreateMethodUnscoped method.

When a ModuleBinder generic delegate is invoked with a reference to a module, it returns a delegate of type T that represents the original lambda expression or method body and that is bound to the specified module. The returned delegate is then used to evaluate the lambda expression or to execute the method body. This allows the same code to be used from multiple scopes without additional compilations.

Expand image Example

The following code example declares a delegate type named Example and uses the CreateLambdaUnscoped method to create an instance of Example that is not bound to any module. The Example delegate is wrapped in an instance of the ModuleBinder generic delegate, which can be used to bind Example to any module scope.

The instance of Example represents an expression that calculates compound interest. The expression contains three variables passed to the delegate, representing the initial investment, the number of times per year the interest is compounded, and the number of years.

The code example passes an array of parameter names to the CreateLambdaUnscoped method, and those names are used in the expression instead of the parameter names from the Example delegate type.

The current interest rate is specified by the variable currentRate, which must be set in the scope of the module where the expression is evaluated. The code example creates the module and sets the global variable before invoking the delegate and displaying the result. Two sets of arguments are supplied: The first set is for the ModuleBinder generic delegate, and specifies the module where evaluation is to occur. The second set is for the Example delegate returned by the ModuleBinder delegate.

Finally, the code example creates a second module with a different value for the global variable currentRate, and uses the ModuleBinder to bind the expression to the second module, producing a different result.

To compile this example, you need a reference to IronPython.dll.

Compare this code example to the code example for the CreateLambda(String,Generic IList,EngineModule) method overload, which creates a delegate that is bound to a specific module.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Integer, _
                                      ByVal p3 As Integer) As Double
Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The expression includes the alternate names specified in
        ' the paramNames array, and also a variable to be supplied
        ' by module scope: currentRate.
        Dim expression As String = _
            "investment * ((1 + currentRate/timesPerYear) ** (timesPerYear * years))"

        Dim paramNames As String() = _
            { "investment", "timesPerYear", "years" }

        Dim compoundInterestUnscoped As ModuleBinder(Of Example) = _
            engine.CreateLambdaUnscoped(Of Example)(expression, paramNames)

        Dim financeModule As EngineModule = _
            engine.CreateModule("FM", True)
        financeModule.Globals.Add("currentRate", 0.03)

        ' First an instance of Example is created, bound to
        ' financeModule. Then the bound delegate is invoked, to get
        ' the result. Finally, the result is displayed to the
        ' console.
        Dim boundDelegate As Example = _
            compoundInterestUnscoped(financeModule)
        Dim result As Double = boundDelegate(100000, 12, 100)
        Console.WriteLine( _
            "$100,000 compounded monthly for 100 years at the current rate: {0:C}", _
            result)

        ' Create a second module with a different value for the
        ' global variable currentRate.
        Dim financeModule2 As EngineModule = _
            engine.CreateModule("FM2", True)
        financeModule2.Globals.Add("currentRate", 0.02)

        ' This time, the bound delegate is created and used without
        ' being saved.
        Console.WriteLine( _
            "$100,000 compounded monthly for 100 years at the current rate: {0:C}", _
            compoundInterestUnscoped(financeModule2)(100000, 12, 100))

    End Sub
End Class

' This code example produces output similar to the following:
'
'$100,000 compounded monthly for 100 years at the current rate: $2,001,048.20
'$100,000 compounded monthly for 100 years at the current rate: $737,676.49
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, int p2, int p3);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The expression includes the alternate names specified in
        // the paramNames array, and also a variable to be supplied
        // by module scope: currentRate.
        string expression =
            "investment * ((1 + currentRate/timesPerYear) ** (timesPerYear * years))";

        string[] paramNames = { "investment", "timesPerYear", "years" };

        ModuleBinder<Example> compoundInterestUnscoped =
            engine.CreateLambdaUnscoped<Example>(expression, paramNames);

        EngineModule financeModule = engine.CreateModule("FM", true);
        financeModule.Globals.Add("currentRate", .03);

        // First an instance of Example is created, bound to
        // financeModule. Then the bound delegate is invoked, to get
        // the result. Finally, the result is displayed to the
        // console.
        Example boundDelegate = compoundInterestUnscoped(financeModule);
        double result = boundDelegate(100000, 12, 100);
        Console.WriteLine(
            "$100,000 compounded monthly for 100 years at the current rate: {0:C}",
            result);

        // Create a second module with a different value for the
        // global variable currentRate.
        EngineModule financeModule2 = engine.CreateModule("FM2", true);
        financeModule2.Globals.Add("currentRate", .02);

        // This time, the bound delegate is created and used without
        // being saved.
        Console.WriteLine(
            "$100,000 compounded monthly for 100 years at the current rate: {0:C}",
            compoundInterestUnscoped(financeModule2)(100000, 12, 100));
    }
}

/* This code example produces output similar to the following:

$100,000 compounded monthly for 100 years at the current rate: $2,001,048.20
$100,000 compounded monthly for 100 years at the current rate: $737,676.49
 */

Expand image See Also

Reference


OptimizedEngineModule Class
See Also Example Members
CollapseAll image DropDown image

Represents a module that has been optimized for access to global data.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Class OptimizedEngineModule
    Inherits EngineModule
Visual Basic (Usage)
Dim instance As OptimizedEngineModule
C#
public class OptimizedEngineModule : EngineModule
C++
public ref class OptimizedEngineModule : public EngineModule
J#
public class OptimizedEngineModule extends EngineModule
JScript
public class OptimizedEngineModule extends EngineModule

Expand image Remarks

Use an OptimizedEngineModule to hold code that makes many references to global data, and is critical to improving the performance of the application.

Note Important

Unlike other compiled code, the memory occupied by code in an OptimizedEngineModule is not reclaimed by garbage collection. The memory is not released until the application domain that contains the OptimizedEngineModule is unloaded.

When you create an OptimizedEngineModule, you provide the name of a file containing IronPython code. Call the Execute method once to execute the global code. The Microsoft intermediate language (MSIL) that is generated has optimized access to global variables. The standard PyStone benchmark executes significantly faster if you use an OptimizedEngineModule instead of an EngineModule.

You cannot specify a global dictionary to use with an OptimizedEngineModule. A global dictionary is created automatically, and can be accessed using the EngineModule.Globals property of the base class, EngineModule. Since the PythonEngine creates the global dictionary, it can create a dictionary that optimizes access to the global variables. It does this by storing the global variables as CLI static variables that the generated MSIL can directly access, while also exposing the CLI static variables through the Globals property.

You can add code to an OptimizedEngineModule after the call to the CreateOptimizedModule method, but that code will not have optimized references to global data.

To obtain an OptimizedEngineModule, use the CreateOptimizedModule method of the PythonEngine class.

Expand image Example

The following code example executes the same global code in two modules, an optimized module and an ordinary module, and compares their performance.

To run the code example, create a file named optiMod.py containing the following statements:

CopyCode image Copy Code
a = 1002
b = 1004
c = 1006
d = 1008
e = 1010
f = 1012
g = 1014
h = 1016
i = 1018
j = 1020

def test():
  return a + b + c + d + e + f + g + h + i + j

The function test makes a number of references to global variables, to exaggerate the effect of optimizing global references.

The optiMod.py file is loaded into the optimized module by the PythonEngine.CreateOptimizedModule method. The Execute method is then called to execute the global code. The IronPython.Hosting.PythonEngine.ExecuteFile method is used to load the same file is loaded into the ordinary module and execute its global code.

Note Note

Executing the global code compiles the test function.

In order to call the test function multiple times, the code example compiles a test script containing the code st = test(). Before each run, the script is "burned in" in the appropriate module, to reduce the likelihood of initialization overhead affecting the results.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Diagnostics

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' Load the file optiMod.py into an optimized module.
        Dim om As OptimizedEngineModule = _
            engine.CreateOptimizedModule("optiMod.py", "om", True)
        om.Execute()

        ' Load the same file into an ordinary module.
        Dim m As EngineModule = engine.CreateModule("m", True)
        engine.ExecuteFile("optiMod.py", m)

        ' The global code in both modules has been executed, so the
        ' test functions have been compiled. Now compile a script
        ' that calls the test function.
        Dim script As CompiledCode = engine.Compile("st = test()")

        ' Call the test script once before timing it, to ensure that
        ' any initialization code is run.
        script.Execute(om)

        Dim s As New Stopwatch()
        s.Start()

        For i As Integer = 0 To 9999
            script.Execute(om)
        Next i

        s.Stop()
        Dim optimized As Double = s.ElapsedTicks

        ' Call the test script once before timing it, to ensure that
        ' any initialization code is run.
        script.Execute(m)

        s.Reset()
        s.Start()

        For i As Integer = 0 To 9999
            script.Execute(m)
        Next i

        s.Stop()
        Dim nonOptimized As Double = s.ElapsedTicks

        Console.WriteLine( _
            "Non-optimized code took {0:F2} times as long to run.", _
            nonOptimized / optimized)

    End Sub
End Class

' This code example produces output similar to the following:
'
'Non-optimized code took 2.92 times as long to run.
'
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Diagnostics;

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // Load the file optiMod.py into an optimized module.
        OptimizedEngineModule om =
            engine.CreateOptimizedModule("optiMod.py", "om", true);
        om.Execute();

        // Load the same file into an ordinary module.
        EngineModule m = engine.CreateModule("m", true);
        engine.ExecuteFile("optiMod.py", m);

        // The global code in both modules has been executed, so the
        // test functions have been compiled. Now compile a script
        // that calls the test function.
        CompiledCode script = engine.Compile("st = test()");

        // Call the test script once before timing it, to ensure that
        // any initialization code is run.
        script.Execute(om);

        Stopwatch s = new Stopwatch();
        s.Start();

        for (int i = 0; i < 10000; i++)
        {
            script.Execute(om);
        }

        s.Stop();
        double optimized = s.ElapsedTicks;

        // Call the test script once before timing it, to ensure that
        // any initialization code is run.
        script.Execute(m);

        s.Reset();
        s.Start();

        for (int i = 0; i < 10000; i++)
        {
            script.Execute(m);
        }

        s.Stop();
        double nonOptimized = s.ElapsedTicks;

        Console.WriteLine(
            "Non-optimized code took {0:F2} times as long to run.",
            nonOptimized / optimized);
    }
}

/* This code example produces output similar to the following:

Non-optimized code took 2.92 times as long to run.
 */

Expand image Inheritance Hierarchy

System.Object
IronPython.Hosting.EngineModule
IronPython.Hosting.OptimizedEngineModule

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

OptimizedEngineModule Members


OptimizedEngineModule Members
See Also Methods Properties
CollapseAll image DropDown image

Represents a module that has been optimized for access to global data.

The following tables list the members exposed by the OptimizedEngineModule type.

Expand image Public Properties

 | Name | Description
Public property | Globals | Gets the dictionary of global variables for the module. (Inherited from EngineModule.)
Public property | Name | Gets the name of the module. (Inherited from EngineModule.)
Public property | TrueDivision | Gets or sets a value that specifies whether division in the current module is done in backward-compatibility mode. (Inherited from EngineModule.)
Top

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | Execute | Executes the global code in the module.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | Import | Imports a module into the global dictionary of the current module. (Inherited from EngineModule.)
 | ReferenceEquals | (Inherited from Object.)
Public method | ToString | Returns the type name and the name of the module. (Inherited from EngineModule.)
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

OptimizedEngineModule Class


OptimizedEngineModule Methods
See Also
CollapseAll image DropDown image

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | Execute | Executes the global code in the module.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | Import | Imports a module into the global dictionary of the current module. (Inherited from EngineModule.)
 | ReferenceEquals | (Inherited from Object.)
Public method | ToString | Returns the type name and the name of the module. (Inherited from EngineModule.)
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

OptimizedEngineModule Class


OptimizedEngineModule.Execute Method
See Also Example
collapseAll image DropDown image

Executes the global code in the module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Execute
Visual Basic (Usage)
Dim instance As OptimizedEngineModule

instance.Execute
C#
public void Execute ()
C++
public:
void Execute ()
J#
public void Execute ()
JScript
public function Execute ()

Expand image Exceptions

Exception type | Condition
InvalidOperationException | The Execute method has already been called once for this module.

Expand image Remarks

Call the Execute method after creating an instance of OptimizedEngineModule.

This method can be called only once for a module. If it is called again, it throws an InvalidOperationException.

You can add code to an optimized module after it has been created, but the references to global variables in that code will not be optimized.

Expand image Example

The following code example executes the same global code in two modules, an optimized module and an ordinary module, and compares their performance. Note the use of the Execute method to run the global code in the optimized module, and optimize global references.

To run the code example, create a file named optiMod.py containing the following statements:

CopyCode image Copy Code
a = 1002
b = 1004
c = 1006
d = 1008
e = 1010
f = 1012
g = 1014
h = 1016
i = 1018
j = 1020

def test():
  return a + b + c + d + e + f + g + h + i + j

The function test makes a number of references to global variables, to exaggerate the effect of optimizing global references.

The optiMod.py file is loaded into the optimized module by the PythonEngine.CreateOptimizedModule method. The Execute method is then called to execute the global code. The IronPython.Hosting.PythonEngine.ExecuteFile method is used to load the same file is loaded into the ordinary module and execute its global code.

Note Note

Executing the global code compiles the test function.

In order to call the test function multiple times, the code example compiles a test script containing the code st = test(). Before each run, the script is "burned in" in the appropriate module, to reduce the likelihood of initialization overhead affecting the results.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Diagnostics

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' Load the file optiMod.py into an optimized module.
        Dim om As OptimizedEngineModule = _
            engine.CreateOptimizedModule("optiMod.py", "om", True)
        om.Execute()

        ' Load the same file into an ordinary module.
        Dim m As EngineModule = engine.CreateModule("m", True)
        engine.ExecuteFile("optiMod.py", m)

        ' The global code in both modules has been executed, so the
        ' test functions have been compiled. Now compile a script
        ' that calls the test function.
        Dim script As CompiledCode = engine.Compile("st = test()")

        ' Call the test script once before timing it, to ensure that
        ' any initialization code is run.
        script.Execute(om)

        Dim s As New Stopwatch()
        s.Start()

        For i As Integer = 0 To 9999
            script.Execute(om)
        Next i

        s.Stop()
        Dim optimized As Double = s.ElapsedTicks

        ' Call the test script once before timing it, to ensure that
        ' any initialization code is run.
        script.Execute(m)

        s.Reset()
        s.Start()

        For i As Integer = 0 To 9999
            script.Execute(m)
        Next i

        s.Stop()
        Dim nonOptimized As Double = s.ElapsedTicks

        Console.WriteLine( _
            "Non-optimized code took {0:F2} times as long to run.", _
            nonOptimized / optimized)

    End Sub
End Class

' This code example produces output similar to the following:
'
'Non-optimized code took 2.92 times as long to run.
'
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Diagnostics;

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // Load the file optiMod.py into an optimized module.
        OptimizedEngineModule om =
            engine.CreateOptimizedModule("optiMod.py", "om", true);
        om.Execute();

        // Load the same file into an ordinary module.
        EngineModule m = engine.CreateModule("m", true);
        engine.ExecuteFile("optiMod.py", m);

        // The global code in both modules has been executed, so the
        // test functions have been compiled. Now compile a script
        // that calls the test function.
        CompiledCode script = engine.Compile("st = test()");

        // Call the test script once before timing it, to ensure that
        // any initialization code is run.
        script.Execute(om);

        Stopwatch s = new Stopwatch();
        s.Start();

        for (int i = 0; i < 10000; i++)
        {
            script.Execute(om);
        }

        s.Stop();
        double optimized = s.ElapsedTicks;

        // Call the test script once before timing it, to ensure that
        // any initialization code is run.
        script.Execute(m);

        s.Reset();
        s.Start();

        for (int i = 0; i < 10000; i++)
        {
            script.Execute(m);
        }

        s.Stop();
        double nonOptimized = s.ElapsedTicks;

        Console.WriteLine(
            "Non-optimized code took {0:F2} times as long to run.",
            nonOptimized / optimized);
    }
}

/* This code example produces output similar to the following:

Non-optimized code took 2.92 times as long to run.
 */

Expand image See Also

Reference

OptimizedEngineModule Class
OptimizedEngineModule Members


OptimizedEngineModule Properties
See Also
CollapseAll image DropDown image

Expand image Public Properties

 | Name | Description
Public property | Globals | Gets the dictionary of global variables for the module. (Inherited from EngineModule.)
Public property | Name | Gets the name of the module. (Inherited from EngineModule.)
Public property | TrueDivision | Gets or sets a value that specifies whether division in the current module is done in backward-compatibility mode. (Inherited from EngineModule.)
Top

Expand image See Also

Reference

OptimizedEngineModule Class


PythonEngine Class
See Also Example Members
CollapseAll image DropDown image

Represents a running instance of the IronPython execution engine, which can be controlled by host applications.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Class PythonEngine
    Implements IDisposable
Visual Basic (Usage)
Dim instance As PythonEngine
C#
public class PythonEngine : IDisposable
C++
public ref class PythonEngine : IDisposable
J#
public class PythonEngine implements IDisposable
JScript
public class PythonEngine implements IDisposable

Expand image Remarks

The PythonEngine class allows applications to host IronPython. The host application creates an instance of the PythonEngine in order to execute IronPython code, and to create and manage modules so that code can be executed in different scopes. IronPython code can be executed as part of the application or as a user scripting language. The host application can provide executing code with access to its object model.

A host can create multiple instances of PythonEngine in order to have multiple engine scopes that don't share any state. For example, each engine instance has its own sys module with its own set of loaded modules.

Modules

Each instance of PythonEngine has a default module, which the host application can access using the DefaultModule property. The host can import modules into the default module using the Import method, and manipulate the default module's global data using the Globals property.

Additional modules can be created using the CreateModule method, if the host needs to provide separate global data for some code. The host can execute code in any module. The global data of a module can be accessed through its EngineModule.Globals property. The host can also create optimized modules for static code that makes heavy use of global data, using the CreateOptimizedModule method.

Evaluating Expressions and Executing Code

The host application can evaluate an expression using the Evaluate method, which returns Object and therefore usually requires a cast, or the EvaluateAs generic method, which has a strongly typed return value. Both methods compile the expression every time they are called. If the host application needs to evaluate an expression repeatedly, the CreateLambda and CreateLambdaUnscoped generic methods can be used to create a delegate representing the compiled expression.

Similarly, the host can execute a series of IronPython statements using Execute and ExecuteFile methods, which compile the code every time the method is called, or use the Compile and CompileFile methods to compile a series of statements for later execution. Compiled code is executed using the IronPython.Hosting.CompiledCode.Execute method.

Note Note

Compilation and execution as discussed here only apply to the strings containing expressions or code statements that are passed to the methods of PythonEngine. Those strings can include calls to IronPython functions and class members, which are already compiled. IronPython def or class statements always generate compiled code. The memory used by compiled code is reclaimed by garbage collection when there are no more references to it, unless the code is in an OptimizedEngineModule. Compiled code in an OptimizedEngineModule is not released until the application domain is unloaded.

In addition, the host application can specify delegates as signatures for method bodies that consist of a series of IronPython statements. The compiled statements are executed when the delegate is invoked. Use the CreateMethod and CreateMethodUnscoped generic method to compile a method body and associate it with a delegate.

Other Features

The host application can add paths to sys.path, the set of paths that are searched when importing modules, by using the AddToPath method. The host can access the sys object using the Sys property.

Rudimentary console functionality can be supported using the ExecuteToConsole, FormatException, and ParseInteractiveInput methods. Console commands can be routed to a different thread, for example when IronPython code needs to interact with Windows forms, by supplying a delegate for the ConsoleCommandDispatcher property. Console input and output can be rerouted using the SetStandardError, SetStandardInput, and SetStandardOutput methods.

Code Examples

The following table lists members that have code examples demonstrating various host application tasks. (These are not necessarily the only topics whose code examples demonstrate the task.)

Task | Topic with code example
Make the host object model available to an IronPython module. | PythonEngine
Cache ClrModule for host use. | PythonEngine
Show the difference between compiling code every time and reusing compiled code. | Compile(String)
Wrap a compiled set of IronPython statements, optionally including a return statement, in a delegate. | Any overload of CreateMethod or CreateMethodUnscoped.
Wrap a compiled set of IronPython statements, optionally including a return statement, in a delegate. Supply alternate names for the parameters. | CreateMethod(String,Generic IList,EngineModule) or CreateMethodUnscoped(String,Generic IList).
Wrap an existing IronPython method call in a delegate bound to a module. | CreateLambda
Evaluate an IronPython expression and get back a strongly-typed result. | Any overload of EvaluateAs.
Evaluate an IronPython expression and get back an untyped result. | Any overload of Evaluate.
Wrap a compiled IronPython expression in a delegate. | Any overload of CreateLambda or CreateLambdaUnscoped.
Implement a rudimentary IronPython console. | ParseInteractiveInput

Expand image Example

The following code example shows one way to start a host application, initialize the IronPython execution engine, import and cache ClrModule, and provide the default module with access to the public API of the host application.

When the host application is started, the Initialize method creates an instance of PythonEngine using the parameterless constructor and uses the Import method to import ClrModule into the default module. The return value is cached, to that the host has a reference to ClrModule.

The Globals property is used to store a reference to the running instance of the application as a global variable in the default module, allowing IronPython code in the default module to access the public API of the host.

To demonstrate these capabilities, the Run method does the following:

  • Executes IronPython code that calls the host application's public Greeting method.

  • Uses the host's cached reference to ClrModule to add a reference to System.Windows.Forms.dll, then executes IronPython code that shows a message box and retrieves the return value.

  • Executes IronPython code that uses ClrModule.References to display the list of assemblies that are loaded and referenced.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports IronPython.Modules

Class MyApplication

    Private engine As PythonEngine
    Private clr As ClrModule

    Private Sub Initialize()

        engine = New PythonEngine()

        ' Import ClrModule, and make it available to the host
        ' application.
        clr = engine.Import("clr")

        ' Make the running instance of the application available
        ' to the default module.
        engine.Globals.Add("MyApplication", Me)

    End Sub

    Shared Sub Main()

        Dim instance As New MyApplication()
        instance.Initialize()
        instance.Run()

    End Sub

    Private Sub Run()

        Console.WriteLine("IronPython code accesses the host API:")
        Dim statements As String = _
            "x = 'Hello'" & vbLf & _
            "MyApplication.Greeting(x)"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "Host code accesses ClrModule:")
        clr.AddReferenceByPartialName("System.Windows.Forms")
        statements = _
            "from System.Windows.Forms import *" & vbLf & _
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)" & vbLf & _
            "print 'You clicked:', result"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "IronPython code accesses clr:")
        statements = _
            "for s in clr.References:" & vbLf & _
            "  print s"
        engine.Execute(statements)
    End Sub

    Public Sub Greeting(ByVal message As String)
        Console.WriteLine("{0} from the host!", message)
    End Sub
End Class

' This code produces output similar to the following:
'
'IronPython code accesses the host API:
'Hello from the host!
'
'Host code accesses ClrModule:
'You clicked: No
'
'IronPython code accesses clr:
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using IronPython.Modules;

class MyApplication
{
    private PythonEngine engine;
    private ClrModule clr;

    private void Initialize()
    {
        engine = new PythonEngine();

        // Import ClrModule, and make it available to the host
        // application.
        clr = (ClrModule) engine.Import("clr");

        // Make the running instance of the application available
        // to the default module.
        engine.Globals.Add("MyApplication", this);
    }

    public static void Main()
    {
        MyApplication instance = new MyApplication();
        instance.Initialize();
        instance.Run();
    }

    private void Run()
    {
        Console.WriteLine("IronPython code accesses the host API:");
        string statements =
            "x = 'Hello'\n" +
            "MyApplication.Greeting(x)";
        engine.Execute(statements);

        Console.WriteLine("\nHost code accesses ClrModule:");
        clr.AddReferenceByPartialName("System.Windows.Forms");
        statements =
            "from System.Windows.Forms import *\n" +
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)\n" +
            "print 'You clicked:', result";
        engine.Execute(statements);

        Console.WriteLine("\nIronPython code accesses clr:");
        statements =
            "for s in clr.References:\n" +
            "  print s";
        engine.Execute(statements);
    }

    public void Greeting(string message)
    {
        Console.WriteLine("{0} from the host!", message);
    }
}

/* This code produces output similar to the following:

IronPython code accesses the host API:
Hello from the host!

Host code accesses ClrModule:
You clicked: No

IronPython code accesses clr:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
 */

Expand image Inheritance Hierarchy

System.Object
IronPython.Hosting.PythonEngine

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

PythonEngine Members


PythonEngine Members
See Also Constructors Fields Methods Properties
CollapseAll image DropDown image

Represents a running instance of the IronPython execution engine, which can be controlled by host applications.

The following tables list the members exposed by the PythonEngine type.

Expand image Public Constructors

 | Name | Description
Public method | PythonEngine | Overloaded. Initializes a new instance of PythonEngine.
Top

Expand image Public Fields

Name | Description
Copyright | Contains the copyright string.
Top

Expand image Public Properties

 | Name | Description
 | ConsoleCommandDispatcher | Gets or sets a delegate that allows custom actions to be performed for the execution of each console statement. This can include executing the code on another thread for improved interactive scenarios, custom pre- and post-execution events, or other host-controlled changes to the way console code is executed.
Public property | DefaultModule | Gets the default module for this engine.
Public property | Globals | Gets the dictionary of global variables for the default module.
Public property | Sys | Gets the IronPython sys module.
 | Version | Gets a structure representing the assembly version of IronPython.dll.
 | VersionString | Gets a string that contains IronPython version information.
Top

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | AddToPath | Adds a path to sys.path, the list of paths to search when importing modules.
Public method | Compile | Overloaded. Compiles IronPython code for later execution.
Public method | CompileFile | Compiles the IronPython statements in the specified file.
Public method | CreateLambda | Overloaded. Creates a delegate representing a compiled expression, in which the parameters of the delegate can be used as variables.
Public method | CreateLambdaUnscoped | Overloaded. Creates a factory delegate that produces instances of a delegate representing a compiled expression, bound to any specified module.
Public method | CreateMethod | Overloaded. Creates a delegate representing a compiled method body, in which the parameters of the delegate can be used as variables.
Public method | CreateMethodUnscoped | Overloaded. Creates a factory delegate that produces instances of a delegate representing a compiled method body, bound to any specified module.
Public method | CreateModule | Overloaded. Creates a new module.
Public method | CreateOptimizedModule | Loads the specified file containing IronPython statements, using the specified module name and specifying whether the module is available for import into other modules, and create a module optimized for accessing global data. The memory used by the module is not freed until the application domain is unloaded.
Public method | Dispose | Releases the resources used by the current engine.
 | DumpDebugInfo | This method is not intended for use in application code.
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | Evaluate | Overloaded. Evaluates an IronPython expression.
Public method | EvaluateAs | Overloaded. Evaluates an IronPython expression and returns a strongly-typed result.
Public method | Execute | Overloaded. Executes a series of IronPython statements.
Public method | ExecuteFile | Overloaded. Executes the IronPython statements in a file.
Public method | ExecuteToConsole | Overloaded. Executes a statement in the IronPython console environment.
Public method | FormatException | Overloaded. Formats an exception for display by the IronPython console.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | Import | Imports a module into the global dictionary of the default module.
Public method | InitializeModules | Sets system state for a new PythonEngine.
Public method | LoadAssembly | Do not use. Use the AddReference method instead.
Public method | ParseInteractiveInput | Determines whether the specified string represents a valid statement. The specified Boolean value determines whether the statement is treated as incomplete or complete.
 | ReferenceEquals | (Inherited from Object.)
Public method | SetStandardError | Redirects console error messages to the specified stream.
Public method | SetStandardInput | Specifies a stream from which standard console input is to be obtained.
Public method | SetStandardOutput | Redirects standard console output to the specified stream.
Public method | Shutdown | Shuts down this instance of the engine.
Public method | ToString | (Inherited from Object.)
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | Overridden. Releases unmanaged resources and performs other cleanup operations before the PythonEngine is reclaimed by garbage collection.
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

PythonEngine Class


PythonEngine Fields
See Also
CollapseAll image DropDown image

Expand image Public Fields

Name | Description
Copyright | Contains the copyright string.
Top

Expand image See Also

Reference

PythonEngine Class


PythonEngine.Copyright Field
See Also
CollapseAll image DropDown image

Contains the copyright string.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Const Copyright As String
Visual Basic (Usage)
Dim value As String

value = PythonEngine.Copyright
C#
public const string Copyright
C++
public:
literal String^ Copyright
J#
public static final String Copyright
JScript
public const var Copyright : String

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine Constructor
See Also
CollapseAll image DropDown image

Initializes a new instance of PythonEngine.

Expand image Overload List

Name | Description
PythonEngine () | Initializes a new instance of PythonEngine with default engine options.
PythonEngine (EngineOptions) | Initializes a new instance of PythonEngine with the specified engine options.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine Constructor ()
See Also Example
CollapseAll image DropDown image

Initializes a new instance of PythonEngine with default engine options.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New PythonEngine
C#
public PythonEngine ()
C++
public:
PythonEngine ()
J#
public PythonEngine ()
JScript
public function PythonEngine ()

Expand image Remarks

By default, all engine options are set to false.

Expand image Example

The following code example shows one way to start a host application, initialize the IronPython execution engine, import and cache ClrModule, and provide the default module with access to the public API of the host application.

When the host application is started, the Initialize method creates an instance of PythonEngine using the parameterless constructor and uses the Import method to import ClrModule into the default module. The return value is cached, to that the host has a reference to ClrModule.

The Globals property is used to store a reference to the running instance of the application as a global variable in the default module, allowing IronPython code in the default module to access the public API of the host.

To demonstrate these capabilities, the Run method does the following:

  • Executes IronPython code that calls the host application's public Greeting method.

  • Uses the host's cached reference to ClrModule to add a reference to System.Windows.Forms.dll, then executes IronPython code that shows a message box and retrieves the return value.

  • Executes IronPython code that uses ClrModule.References to display the list of assemblies that are loaded and referenced.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports IronPython.Modules

Class MyApplication

    Private engine As PythonEngine
    Private clr As ClrModule

    Private Sub Initialize()

        engine = New PythonEngine()

        ' Import ClrModule, and make it available to the host
        ' application.
        clr = engine.Import("clr")

        ' Make the running instance of the application available
        ' to the default module.
        engine.Globals.Add("MyApplication", Me)

    End Sub

    Shared Sub Main()

        Dim instance As New MyApplication()
        instance.Initialize()
        instance.Run()

    End Sub

    Private Sub Run()

        Console.WriteLine("IronPython code accesses the host API:")
        Dim statements As String = _
            "x = 'Hello'" & vbLf & _
            "MyApplication.Greeting(x)"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "Host code accesses ClrModule:")
        clr.AddReferenceByPartialName("System.Windows.Forms")
        statements = _
            "from System.Windows.Forms import *" & vbLf & _
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)" & vbLf & _
            "print 'You clicked:', result"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "IronPython code accesses clr:")
        statements = _
            "for s in clr.References:" & vbLf & _
            "  print s"
        engine.Execute(statements)
    End Sub

    Public Sub Greeting(ByVal message As String)
        Console.WriteLine("{0} from the host!", message)
    End Sub
End Class

' This code produces output similar to the following:
'
'IronPython code accesses the host API:
'Hello from the host!
'
'Host code accesses ClrModule:
'You clicked: No
'
'IronPython code accesses clr:
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using IronPython.Modules;

class MyApplication
{
    private PythonEngine engine;
    private ClrModule clr;

    private void Initialize()
    {
        engine = new PythonEngine();

        // Import ClrModule, and make it available to the host
        // application.
        clr = (ClrModule) engine.Import("clr");

        // Make the running instance of the application available
        // to the default module.
        engine.Globals.Add("MyApplication", this);
    }

    public static void Main()
    {
        MyApplication instance = new MyApplication();
        instance.Initialize();
        instance.Run();
    }

    private void Run()
    {
        Console.WriteLine("IronPython code accesses the host API:");
        string statements =
            "x = 'Hello'\n" +
            "MyApplication.Greeting(x)";
        engine.Execute(statements);

        Console.WriteLine("\nHost code accesses ClrModule:");
        clr.AddReferenceByPartialName("System.Windows.Forms");
        statements =
            "from System.Windows.Forms import *\n" +
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)\n" +
            "print 'You clicked:', result";
        engine.Execute(statements);

        Console.WriteLine("\nIronPython code accesses clr:");
        statements =
            "for s in clr.References:\n" +
            "  print s";
        engine.Execute(statements);
    }

    public void Greeting(string message)
    {
        Console.WriteLine("{0} from the host!", message);
    }
}

/* This code produces output similar to the following:

IronPython code accesses the host API:
Hello from the host!

Host code accesses ClrModule:
You clicked: No

IronPython code accesses clr:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine Constructor (EngineOptions)
See Also Example
CollapseAll image DropDown image

Initializes a new instance of PythonEngine with the specified engine options.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub New ( _
    engineOptions As EngineOptions _
)
Visual Basic (Usage)
Dim engineOptions As EngineOptions

Dim instance As New PythonEngine(engineOptions)
C#
public PythonEngine (
    EngineOptions engineOptions
)
C++
public:
PythonEngine (
    EngineOptions^ engineOptions
)
J#
public PythonEngine (
    EngineOptions engineOptions
)
JScript
public function PythonEngine (
    engineOptions : EngineOptions
)

Parameters

engineOptions

An EngineOptions object whose properties have been set to select the desired options.

Expand image Exceptions

Exception type | Condition
ArgumentNullException | engineOptions is a null reference (Nothing in Visual Basic).

Expand image Example

The following code example enables common language runtime (CLR) debugging for a new instance of PythonEngine. For more detailed examples showing the use of EngineOptions, see the EngineOptions.ClrDebuggingEnabled property and the EngineOptions.ShowClrExceptions property.

C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

class Program
{
    static void Main()
    {
        EngineOptions engineOptions = new EngineOptions();
        // Enable common language runtime (CLR) debugging so that scripts
        // can be debugged using a CLR debugger such as Visual Studio.
        engineOptions.ClrDebuggingEnabled = true;

        PythonEngine debuggableEngine =
            new PythonEngine(engineOptions);
    }
}
Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Module Program

    Sub Main()

        Dim engineOptions As New EngineOptions()
        ' Enable common language runtime (CLR) debugging so that scripts
        ' can be debugged using a CLR debugger such as Visual Studio.
        engineOptions.ClrDebuggingEnabled = True

        Dim debuggableEngine As New PythonEngine(engineOptions)

    End Sub
End Module

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine Methods
See Also
CollapseAll image DropDown image

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | AddToPath | Adds a path to sys.path, the list of paths to search when importing modules.
Public method | Compile | Overloaded. Compiles IronPython code for later execution.
Public method | CompileFile | Compiles the IronPython statements in the specified file.
Public method | CreateLambda | Overloaded. Creates a delegate representing a compiled expression, in which the parameters of the delegate can be used as variables.
Public method | CreateLambdaUnscoped | Overloaded. Creates a factory delegate that produces instances of a delegate representing a compiled expression, bound to any specified module.
Public method | CreateMethod | Overloaded. Creates a delegate representing a compiled method body, in which the parameters of the delegate can be used as variables.
Public method | CreateMethodUnscoped | Overloaded. Creates a factory delegate that produces instances of a delegate representing a compiled method body, bound to any specified module.
Public method | CreateModule | Overloaded. Creates a new module.
Public method | CreateOptimizedModule | Loads the specified file containing IronPython statements, using the specified module name and specifying whether the module is available for import into other modules, and create a module optimized for accessing global data. The memory used by the module is not freed until the application domain is unloaded.
Public method | Dispose | Releases the resources used by the current engine.
 | DumpDebugInfo | This method is not intended for use in application code.
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | Evaluate | Overloaded. Evaluates an IronPython expression.
Public method | EvaluateAs | Overloaded. Evaluates an IronPython expression and returns a strongly-typed result.
Public method | Execute | Overloaded. Executes a series of IronPython statements.
Public method | ExecuteFile | Overloaded. Executes the IronPython statements in a file.
Public method | ExecuteToConsole | Overloaded. Executes a statement in the IronPython console environment.
Public method | FormatException | Overloaded. Formats an exception for display by the IronPython console.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
Public method | Import | Imports a module into the global dictionary of the default module.
Public method | InitializeModules | Sets system state for a new PythonEngine.
Public method | LoadAssembly | Do not use. Use the AddReference method instead.
Public method | ParseInteractiveInput | Determines whether the specified string represents a valid statement. The specified Boolean value determines whether the statement is treated as incomplete or complete.
 | ReferenceEquals | (Inherited from Object.)
Public method | SetStandardError | Redirects console error messages to the specified stream.
Public method | SetStandardInput | Specifies a stream from which standard console input is to be obtained.
Public method | SetStandardOutput | Redirects standard console output to the specified stream.
Public method | Shutdown | Shuts down this instance of the engine.
Public method | ToString | (Inherited from Object.)
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | Overridden. Releases unmanaged resources and performs other cleanup operations before the PythonEngine is reclaimed by garbage collection.
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

PythonEngine Class


PythonEngine.AddToPath Method
See Also
collapseAll image DropDown image

Adds a path to sys.path, the list of paths to search when importing modules.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub AddToPath ( _
    dirName As String _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim dirName As String

instance.AddToPath(dirName)
C#
public void AddToPath (
    string dirName
)
C++
public:
void AddToPath (
    String^ dirName
)
J#
public void AddToPath (
    String dirName
)
JScript
public function AddToPath (
    dirName : String
)

Parameters

dirName

The path to be added.

Expand image Remarks

The Import method and the IronPython import statement use sys.path when searching for modules.

You can also use the sys.path.append function in IronPython code to add paths.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Compile Method
See Also
CollapseAll image DropDown image

Compiles IronPython code for later execution.

Expand image Overload List

Name | Description
PythonEngine.Compile (String) | Compiles the specified IronPython code for later execution.
PythonEngine.Compile (String, String) | Compiles the specified IronPython code for later execution. Optionally generates debug and traceback information using a specified file containing the IronPython code embedded in its original context, for example in an ASP.NET page.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Compile Method (String)
See Also Example
collapseAll image DropDown image

Compiles the specified IronPython code for later execution.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Compile ( _
    scriptCode As String _
) As CompiledCode
Visual Basic (Usage)
Dim instance As PythonEngine
Dim scriptCode As String
Dim returnValue As CompiledCode

returnValue = instance.Compile(scriptCode)
C#
public CompiledCode Compile (
    string scriptCode
)
C++
public:
CompiledCode^ Compile (
    String^ scriptCode
)
J#
public CompiledCode Compile (
    String scriptCode
)
JScript
public function Compile (
    scriptCode : String
) : CompiledCode

Parameters

scriptCode

A string containing the code to be compiled. Statements are separated by line feed characters.

Return Value

A CompiledCode object representing the compiled code.

Expand image Exceptions

Exception type | Condition
PythonSyntaxErrorException | scriptCode contains a syntax error.
ArgumentNullException | scriptCode is a null reference (Nothing in Visual Basic).

Expand image Remarks

If code is to be executed more than once, it is more efficient to compile it once and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method. When all references to the compiled code have been released, the memory it occupied is reclaimed by garbage collection.

Compiled code is not bound to any module. The IronPython.Hosting.CompiledCode.Execute method includes overloads that specify the module in which the code is to be executed.

Note Note

The CreateMethodUnscoped generic method allows you to compile a method body with a strongly-typed signature specified using a delegate type. The CreateMethod generic method does the same thing, but binds the compiled method body to a specified namespace.

Expand image Example

The following code example compiles a series of IronPython statements and executes them in the default module.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        Dim statements As String = _
            "def sum(a, b):" + vbLf + _
            "  return a + b" + vbLf + _
            "first = 10" + vbLf + _
            "second = 32" + vbLf + _
            "print sum(first, second)" + vbLf + _
            "print sum(first, 90)"

        Dim test As CompiledCode = engine.Compile(statements)

        test.Execute()

    End Sub
End Class

' This code example produces the following output:
'
'42
'100
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        string statements = "def sum(a, b):\n" +
                            "  return a + b\n" +
                            "first = 10\n" +
                            "second = 32\n" +
                            "print sum(first, second)\n" +
                            "print sum(first, 90)";

        CompiledCode test = engine.Compile(statements);

        test.Execute();
    }
}

/* This code example produces the following output:

42
100
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Compile Method (String, String)
See Also
collapseAll image DropDown image

Compiles the specified IronPython code for later execution. Optionally generates debug and traceback information using a specified file containing the IronPython code embedded in its original context, for example in an ASP.NET page.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Compile ( _
    scriptCode As String, _
    sourceFileName As String _
) As CompiledCode
Visual Basic (Usage)
Dim instance As PythonEngine
Dim scriptCode As String
Dim sourceFileName As String
Dim returnValue As CompiledCode

returnValue = instance.Compile(scriptCode, sourceFileName)
C#
public CompiledCode Compile (
    string scriptCode,
    string sourceFileName
)
C++
public:
CompiledCode^ Compile (
    String^ scriptCode,
    String^ sourceFileName
)
J#
public CompiledCode Compile (
    String scriptCode,
    String sourceFileName
)
JScript
public function Compile (
    scriptCode : String,
    sourceFileName : String
) : CompiledCode

Parameters

scriptCode

A string containing the code to be compiled. Statements are separated by line feeds.

sourceFileName

The relative or absolute path to a file that contains the code in scriptCode, embedded in its original context. For example, in an ASP.NET page. Specify a null reference (Nothing in Visual Basic) if no debug information is desired.

Return Value

A CompiledCode object containing the compiled code.

Expand image Exceptions

Exception type | Condition
PythonSyntaxErrorException | scriptCode contains a syntax error.
ArgumentNullException | scriptCode is a null reference (Nothing in Visual Basic).

Expand image Remarks

The host creates scriptCode by replacing the lines of sourceFileName that do not contain IronPython code with blank lines.

Debug information is only generated if common language runtime debugging is enabled. That is, if EngineOptions.ClrDebuggingEnabled is set to true when the PythonEngine is created.

If sourceFileName is not found, no exception is thrown.

If code is to be executed more than once, it is more efficient to compile it once and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method. When all references to the compiled code have been released, the memory it occupied is reclaimed by garbage collection.

Compiled code is not bound to any module. The IronPython.Hosting.CompiledCode.Execute method includes overloads that specify the module in which the code is to be executed.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CompileFile Method
See Also
collapseAll image DropDown image

Compiles the IronPython statements in the specified file.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CompileFile ( _
    fileName As String _
) As CompiledCode
Visual Basic (Usage)
Dim instance As PythonEngine
Dim fileName As String
Dim returnValue As CompiledCode

returnValue = instance.CompileFile(fileName)
C#
public CompiledCode CompileFile (
    string fileName
)
C++
public:
CompiledCode^ CompileFile (
    String^ fileName
)
J#
public CompiledCode CompileFile (
    String fileName
)
JScript
public function CompileFile (
    fileName : String
) : CompiledCode

Parameters

fileName

The file name and path of a file containing IronPython statements.

Return Value

A CompiledCode object containing the compiled code.

Expand image Exceptions

Exception type | Condition
PythonSyntaxErrorException | The file contains a syntax error.
ArgumentNullException | fileName is a null reference (Nothing in Visual Basic).

Expand image Remarks

If code is to be executed more than once, it is more efficient to compile it once and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method. When all references to the compiled code have been released, the memory it occupied is reclaimed by garbage collection.

Compiled code is not bound to any module. The IronPython.Hosting.CompiledCode.Execute method includes overloads that specify the module in which the code is to be executed.

Note Note

The CreateMethodUnscoped generic method allows you to compile a method body with a strongly-typed signature specified using a delegate type. The CreateMethod generic method does the same thing, but binds the compiled method body to a specified namespace. These methods do not read files directly.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateLambda Generic Method
See Also
CollapseAll image DropDown image

Creates a delegate representing a compiled expression, in which the parameters of the delegate can be used as variables.

Expand image Overload List

Name | Description
PythonEngine.CreateLambda (String) | Creates a delegate of the specified type, which can be used to return the result of the specified IronPython expression. The expression is evaluated within the scope of the default module.
PythonEngine.CreateLambda (String, EngineModule) | Creates a delegate of the specified type, which can be used to return the result of the specified IronPython expression. The expression is evaluated within the scope of the specified module.
PythonEngine.CreateLambda (String, Generic IList) | Creates a delegate of the specified type, which can be used to return the result of the specified IronPython expression. The expression is evaluated within the scope of the default module. A set of alternate parameter names can be specified, for use in the expression.
PythonEngine.CreateLambda (String, Generic IList, EngineModule) | Creates a delegate of the specified type, which can be used to return the result of the specified IronPython expression. The expression is evaluated within the scope of the specified module. A set of alternate parameter names can be specified, for use in the expression.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateLambda Generic Method (String)
See Also Example
collapseAll image DropDown image

Creates a delegate of the specified type, which can be used to return the result of the specified IronPython expression. The expression is evaluated within the scope of the default module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateLambda(Of TDelegate) ( _
    expression As String _
) As TDelegate
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim returnValue As TDelegate

returnValue = instance.CreateLambda(expression)
C#
public TDelegate CreateLambda<TDelegate> (
    string expression
)
C++
public:
generic<typename TDelegate>
TDelegate CreateLambda (
    String^ expression
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The delegate type that is used to represent expression.

Parameters

expression

An IronPython expression that can use the names of the parameters of TDelegate as variables. This must be an expression, not a statement.

Return Value

A delegate of type TDelegate, which can be used to evaluate the compiled expression in the scope of the default module.

Expand image Exceptions

Exception type | Condition
ArgumentException | TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | expression is a statement. -or- expression is an empty string. -or- expression contains a syntax error.

Expand image Remarks

The delegate that is returned can be invoked many times, but expression is compiled only once. When all references to the delegate have been released, the memory used by the compiled code is reclaimed by garbage collection.

The CreateLambda generic method parses expression, treating the parameter names of TDelegate as variables. In addition to the parameter names of TDelegate, expression can use any name that can be resolved in the scope of the default module.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in expression as instances of IronPython.Modules.ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. An IronPython expression cannot change the value of its variables, so ref or out parameters cannot be set in a lambda expression. The code example for this topic demonstrates this.

When the delegate returned by this method is invoked, IronPython throws a PythonNameErrorException exception if expression contains symbols that cannot be resolved in the scope of the default module.

To create a delegate instance for a lambda expression, such that the delegate is not bound to a specific module, use the CreateLambdaUnscoped method.

To create a delegate bound to a specified module, use the CreateLambda(String,EngineModule) or CreateLambda(String,Generic IList,EngineModule) method overloads.

Expand image Example

The following code example declares a delegate named Example and creates an instance of that delegate to evaluate a simple expression with four variables, in the scope of the default module. Three of the variables are names of parameters in the delegate type, and the fourth is a variable that must be resolved in the scope of the default module.

The third parameter of the Example delegate is a ref parameter (ByRef in Visual Basic), so in the IronPython code for the expression this parameter must be treated as an instance of Reference<int> (Reference(Of Integer) in Visual Basic). The Value property of ClrModule.Reference is used to obtain the value.

Note Note

The code example does not show an out parameter because an undefined value cannot be used in the expression, and expressions cannot set the values of their parameters.

The code example sets the global variable in the default module, then creates the lambda expression. The delegate is invoked, and the value it returns is displayed at the console.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Long, _
                                     ByRef p3 As Integer) As Double
Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The expression uses the parameter names of the delegate
        ' type, Example. Note that p3 is a ByRef parameter, so it
        ' contains an instance of ClrModule.Reference and its
        ' value is obtained using the Reference.Value property.
        Dim expression As String = "p1 * (p2 + p3.Value) - globalValue"

        Dim calculation As Example = _
            engine.CreateLambda(Of Example)(expression)

        engine.Globals.Add("globalValue", 1)

        Dim x As Integer = 88
        Console.WriteLine("The result of the calculation is: {0}", _
            calculation(1.4, 12, x))

    End Sub
End Class

' This code example produces the following output:
'
'The result of the calculation is: 139
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, long p2, ref int p3);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The expression uses the parameter names of the delegate
        // type, Example. Note that p3 is a ref parameter, so it

        // contains an instance of ClrModule.Reference and its
        // value is obtained using the Reference.Value property.
        string expression = "p1 * (p2 + p3.Value) - globalValue";

        Example calculation = engine.CreateLambda<Example>(
            expression
        );

        engine.Globals.Add("globalValue", 1);

        int x = 88;
        Console.WriteLine("The result of the calculation is: {0}",
            calculation(1.4, 12, ref x));
    }
}

/* This code example produces the following output:

The result of the calculation is: 139
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateLambda Generic Method (String, EngineModule)
See Also Example
collapseAll image DropDown image

Creates a delegate of the specified type, which can be used to return the result of the specified IronPython expression. The expression is evaluated within the scope of the specified module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateLambda(Of TDelegate) ( _
    expression As String, _
    engineModule As EngineModule _
) As TDelegate
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim engineModule As EngineModule
Dim returnValue As TDelegate

returnValue = instance.CreateLambda(expression, engineModule)
C#
public TDelegate CreateLambda<TDelegate> (
    string expression,
    EngineModule engineModule
)
C++
public:
generic<typename TDelegate>
TDelegate CreateLambda (
    String^ expression,
    EngineModule^ engineModule
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The delegate type that is used to represent expression.

Parameters

expression

An IronPython expression that can use the names of the parameters of TDelegate as variables. This must be an expression, not a statement.

engineModule

The module in which the expression is evaluated.

Return Value

A delegate of type TDelegate, which can be used to evaluate the compiled expression in the scope of the engineModule module.

Expand image Exceptions

Exception type | Condition
ArgumentNullException | engineModule is a null reference (Nothing in Visual Basic).
ArgumentException | TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | expression is a statement. -or- expression is an empty string. -or- expression contains a syntax error.

Expand image Remarks

The delegate that is returned can be invoked many times, but expression is compiled only once. When all references to the delegate have been released, the memory used by the compiled code is reclaimed by garbage collection.

The CreateLambda generic method parses expression, treating the parameter names of TDelegate as variables.

In addition to the parameter names of TDelegate, expression can use any name that can be resolved in the scope of engineModule.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in expression as instances of IronPython.Modules.ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. An IronPython expression cannot change the value of its variables, so ref or out parameters cannot be set in a lambda expression. See the code example for the CreateLambda(String) method overload.

When the delegate returned by this method is invoked, IronPython throws a PythonNameErrorException exception if expression contains symbols that cannot be resolved in the scope of engineModule.

To create a delegate instance for a lambda expression, such that the delegate is not bound to a specific module, use the CreateLambdaUnscoped method.

To create a delegate bound to the default module, specify PythonEngine.DefaultModule for engineModule, or use the CreateLambda(String) method overload.

Expand image Example

The following code example shows how to use the CreateLambda method to wrap an IronPython function with a delegate that can be called from the host application.

The code example defines a delegate type named Example that takes one argument of type int (Integer in Visual Basic) and returns a Double. The code example then initializes a PythonEngine and creates a module. In that module the code example defines a method that calculates the sum from 1 to n of n factorial (n!).

The code example creates a delegate wrapper for the IronPython function by calling the CreateLambda(String,EngineModule) method overload with an expression that consists of a function call to the IronPython method, using the name of the parameter of the Example delegate as the argument. Finally, the code example invokes the delegate, passing the value 10.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Delegate Function Example(ByVal p1 As Integer) As Double

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' Create a module, and in that module define a function.
        Dim calcModule As EngineModule = engine.CreateModule("cm", True)
        Dim statements As String = _
            "def sumNFactorial(n):" & vbLf & _
            "  total = 1" & vbLf & _
            "  if n > 0:" & vbLf & _
            "    element = 1" & vbLf & _
            "    for i in range(2, n + 1):" & vbLf & _
            "      element *= i" & vbLf & _
            "      total += element" & vbLf & _
            "  return total"
        engine.Execute(statements, calcModule)

        ' Create a lambda expression that wraps the IronPython
        ' function.
        Dim SumNFactorial As Example = _
            engine.CreateLambda(Of Example)("sumNFactorial(p1)", calcModule)

        Console.WriteLine("Sum n=1 to 10 of n! = {0}", SumNFactorial(10))

    End Sub
End Class

' This code example produces the following output:
'
'Sum n=1 to 10 of n! = 4037913
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(int p1);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // Create a module, and in that module define a function.
        EngineModule calcModule = engine.CreateModule("cm", true);
        string statements = "def sumNFactorial(n):\n" +
                            "  total = 1\n" +
                            "  if n > 0:\n" +
                            "    element = 1\n" +
                            "    for i in range(2, n + 1):\n" +
                            "      element *= i\n" +
                            "      total += element\n" +
                            "  return total";
        engine.Execute(statements, calcModule);

        // Create a lambda expression that wraps the IronPython
        // function.
        Example SumNFactorial =
            engine.CreateLambda<Example>("sumNFactorial(p1)", calcModule);

        Console.WriteLine("Sum n=1 to 10 of n! = {0}", SumNFactorial(10));
    }
}

/* This code example produces the following output:

Sum n=1 to 10 of n! = 4037913
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateLambda Generic Method (String, Generic IList)
See Also Example
collapseAll image DropDown image

Creates a delegate of the specified type, which can be used to return the result of the specified IronPython expression. The expression is evaluated within the scope of the default module. A set of alternate parameter names can be specified, for use in the expression.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateLambda(Of TDelegate) ( _
    expression As String, _
    parameters As IList(Of String) _
) As TDelegate
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim parameters As IList(Of String)
Dim returnValue As TDelegate

returnValue = instance.CreateLambda(expression, parameters)
C#
public TDelegate CreateLambda<TDelegate> (
    string expression,
    IList<string> parameters
)
C++
public:
generic<typename TDelegate>
TDelegate CreateLambda (
    String^ expression,
    IList<String^>^ parameters
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The delegate type that is used to represent expression.

Parameters

expression

An IronPython expression that can use the names supplied in parameters, or the names of the parameters of TDelegate if parameters is a null reference (Nothing in Visual Basic). This must be an expression, not a statement.

parameters

An array of parameter names to be used in expression, instead of the parameter names of the delegate type.

Return Value

A delegate of type TDelegate, which can be used to evaluate the compiled expression in the scope of the default module.

Expand image Exceptions

Exception type | Condition
ArgumentException | The number of parameter names in parameters is different from the number of parameters in TDelegate. -or- TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | expression is a statement. -or- expression is an empty string. -or- expression contains a syntax error.

Expand image Remarks

The delegate that is returned can be invoked many times, but expression is compiled only once. When all references to the delegate have been released, the memory used by the compiled code is reclaimed by garbage collection.

The CreateLambda generic method parses expression and binds the names specified in parameters to the corresponding parameters of TDelegate. The correspondence is positional. If parameters is a null reference (Nothing in Visual Basic), the parameter names of the delegate type are used.

In addition to names contained in parameters, expression can use any name that can be resolved in the scope of the default module.

The names in parameters completely replace the parameter names of the delegate. You cannot use a mixture of names in expression.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in expression as instances of IronPython.Modules.ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. An IronPython expression cannot change the value of its variables, so ref or out parameters cannot be set in a lambda expression. See the code example for the CreateLambda(String) method overload.

When the delegate returned by this method is invoked, IronPython throws a PythonNameErrorException exception if expression contains symbols that cannot be resolved in the scope of the default module.

To create a delegate instance for a lambda expression, such that the delegate is not bound to a specific module, use the CreateLambdaUnscoped method.

To create a delegate bound to a specified module, use the CreateLambda(String,Generic IList,EngineModule) method overload.

Expand image Example

The following code example declares a delegate named Example and creates an instance of that delegate to evaluate a simple expression with four variables, in the scope of the default module. Three of the variables are substitutes for the parameter names of the delegate type, and the fourth is a variable that must be resolved in the scope of the default module.

The parameter names used in expression are specified in the parameterNames array. They are bound to the parameter names of Example by position.

The third parameter of the Example delegate is a ref parameter (ByRef in Visual Basic), so in the IronPython code for the expression it must be treated as an instance of Reference<int> (Reference(Of Integer) in Visual Basic). The Value property of ClrModule.Reference is used to obtain the value.

Note Note

The code example does not show an out parameter because an undefined value cannot be used in the expression, and expressions cannot set the values of their parameters.

The code example sets the global variable in the default module, then creates the lambda expression. The delegate is invoked, and the value it returns is displayed at the console.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Long, _
                                    ByRef p3 As Integer) As Double
Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The expression uses the parameter names supplied in
        ' parameterNames. Note that 'three' is a ByRef parameter,
        ' so it contains an instance of ClrModule.Reference and its
        ' value is obtained using the Reference.Value property.
        Dim expression As String = _
            "one * (two + three.Value) - globalValue"

        Dim parameterNames As String() = { "one", "two", "three" }

        engine.Globals.Add("globalValue", 1)

        Dim calculation As Example = _
            engine.CreateLambda(Of Example)(expression, parameterNames)

        Dim x As Integer = 88
        Console.WriteLine("The result of the calculation is: {0}", _
            calculation(1.4, 12, x))

    End Sub
End Class

' This code example produces the following output:
'
'The result of the calculation is: 139
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, long p2, ref int p3);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The expression uses the parameter names supplied in
        // parameterNames. Note that 'three' is a ref parameter, so
        // it contains an instance of ClrModule.Reference and its
        // value is obtained using the Reference.Value property.
        string expression =
            "one * (two + three.Value) - globalValue";

        string[] parameterNames = { "one", "two", "three" };

        engine.Globals.Add("globalValue", 1);

        Example calculation = engine.CreateLambda<Example>(
            expression, parameterNames
        );

        int x = 88;
        Console.WriteLine("The result of the calculation is: {0}",
            calculation(1.4, 12, ref x));
    }
}

/* This code example produces the following output:

The result of the calculation is: 139
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateLambda Generic Method (String, Generic IList, EngineModule)
See Also Example
collapseAll image DropDown image

Creates a delegate of the specified type, which can be used to return the result of the specified IronPython expression. The expression is evaluated within the scope of the specified module. A set of alternate parameter names can be specified, for use in the expression.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateLambda(Of TDelegate) ( _
    expression As String, _
    parameters As IList(Of String), _
    engineModule As EngineModule _
) As TDelegate
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim parameters As IList(Of String)
Dim engineModule As EngineModule
Dim returnValue As TDelegate

returnValue = instance.CreateLambda(expression, parameters, engineModule)
C#
public TDelegate CreateLambda<TDelegate> (
    string expression,
    IList<string> parameters,
    EngineModule engineModule
)
C++
public:
generic<typename TDelegate>
TDelegate CreateLambda (
    String^ expression,
    IList<String^>^ parameters,
    EngineModule^ engineModule
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The delegate type that is used to represent expression.

Parameters

expression

An IronPython expression that can use the names supplied in parameters, or the names of the parameters of TDelegate if parameters is a null reference (Nothing in Visual Basic). This must be an expression, not a statement.

parameters

An array of parameter names to be used in expression, instead of the parameter names of the delegate type.

engineModule

The module in which the expression is evaluated.

Return Value

A delegate of type TDelegate, which can be used to evaluate the compiled expression in the scope of the engineModule module.

Expand image Exceptions

Exception type | Condition
ArgumentNullException | engineModule is a null reference (Nothing in Visual Basic).
ArgumentException | The number of parameter names in parameters is different from the number of parameters in TDelegate. -or- TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | expression is a statement. -or- expression is an empty string. -or- expression contains a syntax error.

Expand image Remarks

The delegate that is returned can be invoked many times, but expression is compiled only once. When all references to the delegate have been released, the memory used by the compiled code is reclaimed by garbage collection.

The CreateLambda generic method parses expression and binds the names specified in parameters to the corresponding parameters of TDelegate. The correspondence is positional. If parameters is a null reference (Nothing in Visual Basic), the parameter names of the delegate type are used.

In addition to names contained in parameters, expression can use any name that can be resolved in the scope of engineModule.

The names in parameters completely replace the parameter names of the delegate. You cannot use a mixture of names in expression.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in expression as instances of IronPython.Modules.ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. An IronPython expression cannot change the value of its variables, so ref or out parameters cannot be set in a lambda expression. See the code example for the CreateLambda(String) method overload.

When the delegate returned by this method is invoked, IronPython throws a PythonNameErrorException exception if expression contains symbols that cannot be resolved in the scope of engineModule.

To create a delegate instance for a lambda expression, such that the delegate is not bound to a specific module, use the CreateLambdaUnscoped method.

To create a delegate bound to the default module, specify PythonEngine.DefaultModule for engineModule, or use the CreateLambda(String,Generic IList) method overload.

Expand image Example

The following code example declares a delegate type and creates an instance of that delegate type to calculate compound interest. The expression contains three variables passed to the delegate, representing the initial investment, the number of times per year the interest is compounded, and the number of years.

The code example passes an array of parameter names to the CreateLambda method, and those names are used in the expression instead of the parameter names from the delegate type.

The current interest rate is specified by the variable currentRate, which must be set in the scope of the module where the expression is evaluated. The code example creates the module and sets the global variable before invoking the delegate and displaying the result.

To compile this example, you need a reference to IronPython.dll.

Compare this code example to the code example for the CreateLambdaUnscoped(String,Generic IList) method overload, which creates a delegate that is not bound to a particular module.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Integer, _
                                      ByVal p3 As Integer) As Double
Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The expression includes the alternate names specified in
        ' the paramNames array, and also a variable to be supplied
        ' by module scope: currentRate.
        Dim expression As String = _
            "investment * ((1 + currentRate/timesPerYear) ** (timesPerYear * years))"

        Dim paramNames As String() = _
            { "investment", "timesPerYear", "years" }

        Dim financeModule As EngineModule = _
            engine.CreateModule("FM", True)
        financeModule.Globals.Add("currentRate", 0.03)

        Dim compoundInterest As Example = _
            engine.CreateLambda(Of Example)(expression, paramNames, financeModule)

        Console.WriteLine( _
            "$100,000 compounded monthly for 100 years at the current rate: {0:C}", _
            compoundInterest(100000, 12, 100))

    End Sub
End Class

' This code example produces the following output:
'
'$100,000 compounded monthly for 100 years at the current rate: $2,001,048.20
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, int p2, int p3);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The expression includes the alternate names specified in
        // the paramNames array, and also a variable to be supplied
        // by module scope: currentRate.
        string expression = "investment * ((1 + currentRate/timesPerYear) ** (timesPerYear * years))";

        string[] paramNames = { "investment", "timesPerYear", "years" };

        EngineModule financeModule = engine.CreateModule("FM", true);
        financeModule.Globals.Add("currentRate", .03);

        Example compoundInterest = engine.CreateLambda<Example>(
            expression, paramNames, financeModule
        );

        Console.WriteLine("$100,000 compounded monthly for 100 years at the current rate: {0:C}",
            compoundInterest(100000, 12, 100));
    }
}

/* This code example produces the following output:

$100,000 compounded monthly for 100 years at the current rate: $2,001,048.20
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateLambdaUnscoped Generic Method
See Also
CollapseAll image DropDown image

Creates a factory delegate that produces instances of a delegate representing a compiled expression, bound to any specified module.

Expand image Overload List

Name | Description
PythonEngine.CreateLambdaUnscoped (String) | Returns a ModuleBinder generic delegate that can be used to bind the specified IronPython expression to a module scope, using an inner delegate of the specified type.
PythonEngine.CreateLambdaUnscoped (String, Generic IList) | Returns a ModuleBinder generic delegate that can be used to bind the specified IronPython expression to a module scope, using an inner delegate of the specified type. A set of alternate parameter names can be specified, for use in the expression.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateLambdaUnscoped Generic Method (String)
See Also Example
collapseAll image DropDown image

Returns a ModuleBinder generic delegate that can be used to bind the specified IronPython expression to a module scope, using an inner delegate of the specified type.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateLambdaUnscoped(Of TDelegate) ( _
    expression As String _
) As ModuleBinder(Of TDelegate)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim returnValue As ModuleBinder(Of TDelegate)

returnValue = instance.CreateLambdaUnscoped(expression)
C#
public ModuleBinder<TDelegate> CreateLambdaUnscoped<TDelegate> (
    string expression
)
C++
public:
generic<typename TDelegate>
ModuleBinder<TDelegate>^ CreateLambdaUnscoped (
    String^ expression
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The delegate type that is used to represent expression.

Parameters

expression

An IronPython expression that can use the names of the parameters of TDelegate as variables. This must be an expression, not a statement.

Return Value

A ModuleBinder generic delegate that wraps a delegate of type TDelegate, and that can bind the TDelegate to any module. This allows the compiled expression to be evaluated in the scope of any module.

Expand image Exceptions

Exception type | Condition
ArgumentException | TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | expression is a statement. -or- expression is an empty string. -or- expression contains a syntax error.

Expand image Remarks

Use the CreateLambdaUnscoped generic method when you have an expression you want to evaluate in the scopes of arbitrary modules.

This method creates a delegate of type TDelegate that represents expression and that is not bound to the scope of any module. Instead of returning the unscoped delegate directly, the CreateLambdaUnscoped generic method returns a ModuleBinder generic delegate that wraps the TDelegate delegate. When you want to evaluate the specified expression in the scope of a module, use the ModuleBinder generic delegate to produce a TDelegate delegate that is bound to the desired module, and then invoke the TDelegate delegate. That is, the ModuleBinder generic delegate functions as a factory method for producing bound delegates.

The expression is compiled only once.

When the delegate representing the compiled expression is invoked, IronPython throws a PythonNameErrorException exception if expression contains symbols that cannot be resolved in the scope of the module the delegate is bound to.

Note Note

If you only need to evaluate expression in the scope of one module, you can use the CreateLambda(String,EngineModule) generic method to produce a delegate that is bound to that module.

This method parses expression, treating the parameter names of TDelegate as variables. In addition to the parameter names of TDelegate, expression can use other names. Those names are resolved in the scope of the eventual target module.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in expression as instances of IronPython.Modules.ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. An IronPython expression cannot change the value of its variables, so ref or out parameters cannot be set in a lambda expression. See the code example.

Expand image Example

The following code example declares a delegate type named Example and uses the CreateLambdaUnscoped generic method to create an instance of Example that is not bound to any module. The Example delegate is wrapped in an instance of the ModuleBinder generic delegate, which can be used to bind Example to any module scope.

In this code example, the Example delegate represents a simple expression that uses two parameters passed by value, a ref parameter (ByRef in Visual Basic), and a global variable. The names of the delegate parameters are used as variables in the expression. Because parameter p3 is a ref parameter, it is passed as an instance of ClrModule.Reference, and its value must be obtained using the ClrModule.Reference.Value property.

Note Note

The code example does not show an out parameter because an undefined value cannot be used in the expression, and expressions cannot set the values of their parameters.

The ModuleBinder created by the CreateLambdaUnscoped method is stored in a variable named unscopedCalculation.

The global variable globalValue must be set in the scope of the module where the expression is evaluated. The code example sets this global value in the default module.

The ModuleBinder delegate in unscopedCalculation is invoked to create an instance of Example bound to the default module. The bound delegate boundDelegate is then invoked to obtain the result. Finally, the result is displayed to the console.

To show binding to different modules, the code example creates a second module, module2, and sets its globalValue variable to a different value. This time, the bound delegate is obtained and invoked in one step, and the delegate instance is not saved. Two sets of arguments are supplied: The first set is for the ModuleBinder generic delegate, and specifies the module where evaluation is to occur. The second set is for the Example delegate returned by the ModuleBinder delegate.

To compile this example, you need a reference to IronPython.dll.

Compare this code example to the code example for the CreateLambda(String,EngineModule) method overload, which creates a delegate that is bound to a specific module.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Long, _
                                   ByRef p3 As Integer) As Double
Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The expression uses the parameter names of the delegate
        ' type, Example. Note that p3 is a ref parameter, so it
        ' contains an instance of ClrModule.Reference and its
        ' value is obtained using the Reference.Value property.
        Dim expression As String = _
            "p1 * (p2 + p3.Value) + globalValue"

        Dim unscopedCalculation As ModuleBinder(Of Example) = _
            engine.CreateLambdaUnscoped(Of Example)(expression)

        ' In the default module, set the value of the global
        ' variable required by the calculation. Also, set a host
        ' variable that will be passed by reference.
        engine.Globals.Add("globalValue", 1000)
        Dim x As Integer = 88

        ' First an instance of Example is created, bound to the
        ' default module. Then the bound delegate is invoked, to get
        ' the result. Finally, the result is displayed to the
        ' console.
        Dim boundDelegate As Example = _
            unscopedCalculation(engine.DefaultModule)
        Dim result As Double = boundDelegate(1.4, 12, x)
        Console.WriteLine( _
            "The value of the calculation in '{0}': {1:F2}", _
            engine.DefaultModule.Name, result)

        ' Create another module with a different value for the
        ' global variable globalValue.
        Dim module2 As EngineModule = _
            engine.CreateModule("mod2", True)
        module2.Globals.Add("globalValue", 2000)

        ' This time, the bound delegate is created and used without
        ' being saved.
        Console.WriteLine( _
            "The value of the calculation in '{0}': {1:F2}", _
            module2.Name, _
            unscopedCalculation(module2)(1.4, 12, x))

    End Sub
End Class

' This code example produces the following output:
'
'The value of the calculation in 'defaultModule': 1140.00
'The value of the calculation in 'mod2': 2140.00
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, long p2, ref int p3);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The expression uses the parameter names of the delegate
        // type, Example. Note that p3 is a ref parameter, so it
        // contains an instance of ClrModule.Reference and its
        // value is obtained using the Reference.Value property.
        string expression = "p1 * (p2 + p3.Value) + globalValue";

        ModuleBinder<Example> unscopedCalculation =
            engine.CreateLambdaUnscoped<Example>(expression);

        // In the default module, set the value of the global
        // variable required by the calculation. Also, set a host
        // variable that will be passed by reference.
        engine.Globals.Add("globalValue", 1000);
        int x = 88;

        // First an instance of Example is created, bound to the
        // default module. Then the bound delegate is invoked, to get
        // the result. Finally, the result is displayed to the
        // console.
        Example boundDelegate =
            unscopedCalculation(engine.DefaultModule);
        double result = boundDelegate(1.4, 12, ref x);
        Console.WriteLine(
            "The value of the calculation in '{0}': {1:F2}",
            engine.DefaultModule.Name,
            result);

        // Create another module with a different value for the
        // global variable globalValue.
        EngineModule module2 = engine.CreateModule("mod2", true);
        module2.Globals.Add("globalValue", 2000);

        // This time, the bound delegate is created and used without
        // being saved.
        Console.WriteLine(
            "The value of the calculation in '{0}': {1:F2}",
            module2.Name,
            unscopedCalculation(module2)(1.4, 12, ref x));
    }
}

/* This code example produces the following output:

The value of the calculation in 'defaultModule': 1140.00
The value of the calculation in 'mod2': 2140.00
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateLambdaUnscoped Generic Method (String, Generic IList)
See Also Example
collapseAll image DropDown image

Returns a ModuleBinder generic delegate that can be used to bind the specified IronPython expression to a module scope, using an inner delegate of the specified type. A set of alternate parameter names can be specified, for use in the expression.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateLambdaUnscoped(Of TDelegate) ( _
    expression As String, _
    parameters As IList(Of String) _
) As ModuleBinder(Of TDelegate)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim parameters As IList(Of String)
Dim returnValue As ModuleBinder(Of TDelegate)

returnValue = instance.CreateLambdaUnscoped(expression, parameters)
C#
public ModuleBinder<TDelegate> CreateLambdaUnscoped<TDelegate> (
    string expression,
    IList<string> parameters
)
C++
public:
generic<typename TDelegate>
ModuleBinder<TDelegate>^ CreateLambdaUnscoped (
    String^ expression,
    IList<String^>^ parameters
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The delegate type that is used to represent expression.

Parameters

expression

An IronPython expression that can use the names supplied in parameters, or the names of the parameters of TDelegate if parameters is a null reference (Nothing in Visual Basic). This must be an expression, not a statement.

parameters

An array of parameter names to be used in expression, instead of the parameter names of TDelegate.

Return Value

A ModuleBinder generic delegate that wraps a delegate of type TDelegate, and that can bind the TDelegate to any module. This allows the compiled expression to be evaluated in the scope of any module.

Expand image Exceptions

Exception type | Condition
ArgumentException | The number of parameter names in parameters is different from the number of parameters in TDelegate. -or- TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | expression is a statement. -or- expression is an empty string. -or- expression contains a syntax error.

Expand image Remarks

Use the CreateLambdaUnscoped generic method when you have an expression you want to evaluate in the scopes of arbitrary modules.

This method creates a delegate of type TDelegate that represents expression and is not bound to the scope of any module. Instead of returning the unscoped delegate directly, the CreateLambdaUnscoped generic method returns a ModuleBinder generic delegate that wraps the TDelegate delegate. When you want to evaluate the specified expression in the scope of a module, use the ModuleBinder generic delegate to produce a TDelegate delegate that is bound to the desired module, and then invoke the TDelegate delegate. That is, the ModuleBinder generic delegate functions as a factory method for producing bound delegates.

The expression is compiled only once.

When the delegate representing the compiled expression is invoked, IronPython throws a PythonNameErrorException exception if expression contains symbols that cannot be resolved in the scope of the module the delegate is bound to.

Note Note

If you only need to evaluate expression in the scope of one module, you can use the CreateLambda(String,Generic IList,EngineModule) generic method to produce a delegate that is bound to that module.

This method parses expression and binds the names specified in parameters to the corresponding parameters of TDelegate. The correspondence is positional. If parameters is a null reference (Nothing in Visual Basic), the parameter names of TDelegate are used.

In addition to names contained in parameters, expression can use other names. Those names are resolved in the scope of the eventual target module.

The names in parameters completely replace the parameter names of TDelegate. You cannot use a mixture of names in expression.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in expression as instances of IronPython.Modules.ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. An IronPython expression cannot change the value of its variables, so ref or out parameters cannot be set in a lambda expression. See the code example for the CreateLambdaUnscoped(String) method overload.

Expand image Example

The following code example declares a delegate type named Example and uses the CreateLambdaUnscoped method to create an instance of Example that is not bound to any module. The Example delegate is wrapped in an instance of the ModuleBinder generic delegate, which can be used to bind Example to any module scope.

In this code example, the Example delegate represents an expression that calculates compound interest. The expression contains three variables passed to the delegate, representing the initial investment, the number of times per year the interest is compounded, and the number of years.

The code example passes an array of parameter names to the CreateLambdaUnscoped method, and those names are used in parsing the expression, instead of the parameter names from the Example delegate type.

The ModuleBinder created by the CreateLambdaUnscoped method is stored in a variable named compoundInterestUnscoped.

The current interest rate is specified by the variable currentRate, which must be set in the scope of the module where the expression is evaluated. The code example creates a module and puts a reference to it into a variable named financeModule, then sets the global variable.

The ModuleBinder delegate in compoundInterestUnscoped is invoked to create an instance of Example bound to financeModule. The bound delegate boundDelegate is then invoked to obtain the result. Finally, the result is displayed to the console.

To show binding to different modules, the code example creates a second module, financeModule2 and sets its global currentRate variable to a different value. This time, the bound delegate is obtained and invoked in one step, and the delegate instance is not saved. Two sets of arguments are supplied: The first set is for the ModuleBinder generic delegate, and specifies the module where evaluation is to occur. The second set is for the Example delegate returned by the ModuleBinder delegate.

To compile this example, you need a reference to IronPython.dll.

Compare this code example to the code example for the CreateLambda(String,Generic IList,EngineModule) method overload, which creates a delegate that is bound to a specific module.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Integer, _
                                      ByVal p3 As Integer) As Double
Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The expression includes the alternate names specified in
        ' the paramNames array, and also a variable to be supplied
        ' by module scope: currentRate.
        Dim expression As String = _
            "investment * ((1 + currentRate/timesPerYear) ** (timesPerYear * years))"

        Dim paramNames As String() = _
            { "investment", "timesPerYear", "years" }

        Dim compoundInterestUnscoped As ModuleBinder(Of Example) = _
            engine.CreateLambdaUnscoped(Of Example)(expression, paramNames)

        Dim financeModule As EngineModule = _
            engine.CreateModule("FM", True)
        financeModule.Globals.Add("currentRate", 0.03)

        ' First an instance of Example is created, bound to
        ' financeModule. Then the bound delegate is invoked, to get
        ' the result. Finally, the result is displayed to the
        ' console.
        Dim boundDelegate As Example = _
            compoundInterestUnscoped(financeModule)
        Dim result As Double = boundDelegate(100000, 12, 100)
        Console.WriteLine( _
            "$100,000 compounded monthly for 100 years at the current rate: {0:C}", _
            result)

        ' Create a second module with a different value for the
        ' global variable currentRate.
        Dim financeModule2 As EngineModule = _
            engine.CreateModule("FM2", True)
        financeModule2.Globals.Add("currentRate", 0.02)

        ' This time, the bound delegate is created and used without
        ' being saved.
        Console.WriteLine( _
            "$100,000 compounded monthly for 100 years at the current rate: {0:C}", _
            compoundInterestUnscoped(financeModule2)(100000, 12, 100))

    End Sub
End Class

' This code example produces output similar to the following:
'
'$100,000 compounded monthly for 100 years at the current rate: $2,001,048.20
'$100,000 compounded monthly for 100 years at the current rate: $737,676.49
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, int p2, int p3);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The expression includes the alternate names specified in
        // the paramNames array, and also a variable to be supplied
        // by module scope: currentRate.
        string expression =
            "investment * ((1 + currentRate/timesPerYear) ** (timesPerYear * years))";

        string[] paramNames = { "investment", "timesPerYear", "years" };

        ModuleBinder<Example> compoundInterestUnscoped =
            engine.CreateLambdaUnscoped<Example>(expression, paramNames);

        EngineModule financeModule = engine.CreateModule("FM", true);
        financeModule.Globals.Add("currentRate", .03);

        // First an instance of Example is created, bound to
        // financeModule. Then the bound delegate is invoked, to get
        // the result. Finally, the result is displayed to the
        // console.
        Example boundDelegate = compoundInterestUnscoped(financeModule);
        double result = boundDelegate(100000, 12, 100);
        Console.WriteLine(
            "$100,000 compounded monthly for 100 years at the current rate: {0:C}",
            result);

        // Create a second module with a different value for the
        // global variable currentRate.
        EngineModule financeModule2 = engine.CreateModule("FM2", true);
        financeModule2.Globals.Add("currentRate", .02);

        // This time, the bound delegate is created and used without
        // being saved.
        Console.WriteLine(
            "$100,000 compounded monthly for 100 years at the current rate: {0:C}",
            compoundInterestUnscoped(financeModule2)(100000, 12, 100));
    }
}

/* This code example produces output similar to the following:

$100,000 compounded monthly for 100 years at the current rate: $2,001,048.20
$100,000 compounded monthly for 100 years at the current rate: $737,676.49
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateMethod Generic Method
See Also
CollapseAll image DropDown image

Creates a delegate representing a compiled method body, in which the parameters of the delegate can be used as variables.

Expand image Overload List

Name | Description
PythonEngine.CreateMethod (String) | Creates a delegate of the specified type, which can be used to execute the specified IronPython method body and optionally return a result. The method is executed within the scope of the default module.
PythonEngine.CreateMethod (String, EngineModule) | Creates a delegate of the specified type, which can be used to execute the specified IronPython method body and optionally return a result. The method is executed within the scope of the specified module.
PythonEngine.CreateMethod (String, Generic IList) | Creates a delegate of the specified type, which can be used to execute the specified IronPython method body and optionally return a result. The method is executed within the scope of the default module. A set of alternate parameter names can be specified, for use in the method body.
PythonEngine.CreateMethod (String, Generic IList, EngineModule) | Creates a delegate of the specified type, which can be used to execute the specified IronPython method body and optionally return a result. The method is executed within the scope of the specified module. A set of alternate parameter names can be specified, for use in the method body.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateMethod Generic Method (String)
See Also Example
collapseAll image DropDown image

Creates a delegate of the specified type, which can be used to execute the specified IronPython method body and optionally return a result. The method is executed within the scope of the default module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateMethod(Of TDelegate) ( _
    statements As String _
) As TDelegate
Visual Basic (Usage)
Dim instance As PythonEngine
Dim statements As String
Dim returnValue As TDelegate

returnValue = instance.CreateMethod(statements)
C#
public TDelegate CreateMethod<TDelegate> (
    string statements
)
C++
public:
generic<typename TDelegate>
TDelegate CreateMethod (
    String^ statements
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The type of delegate that is used to represent the method body.

Parameters

statements

A method body consisting of a series of IronPython statements that can use the parameter names supplied in parameters, or the names of the parameters of TDelegate if parameters is a null reference (Nothing in Visual Basic). The statements are separated by line feed characters.

Return Value

A delegate of type TDelegate, which can be used to execute the compiled method body in the scope of the default module.

Expand image Exceptions

Exception type | Condition
ArgumentException | TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | statements contains a syntax error.

Expand image Remarks

The delegate that is returned can be invoked many times, but statements are compiled only once. When all references to the delegate have been released, the memory used by the compiled code is reclaimed by garbage collection.

The CreateMethod generic method parses the method body specified in statements using the names of the parameters of TDelegate as variable names. In addition, statements can use any name that can be resolved in the scope of the default module.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in statements as instances of IronPython.Modules.ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, or to set the value of a ref or out parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. See the code example.

When the delegate returned by this method is invoked, IronPython throws a PythonNameErrorException exception if there are symbols in statements that cannot be resolved in the scope of the default module.

If TDelegate returns a value type, and there is no return statement in statements, the delegate throws ArgumentTypeException when invoked. This is because methods in Python that do not explicitly return a value return None.

To create a delegate instance that is not bound to a specific module, use the CreateMethodUnscoped method.

To create a delegate bound to the default module, specify PythonEngine.DefaultModule for engineModule, or use the CreateMethod(String) method overload.

Expand image Example

The following code example declares a delegate named Example and creates an instance of that delegate to execute a simple method body in the scope of the default module. The method body uses four variables that are names of parameters of the delegate type, one variable created within the scope of the method body, and one that must be resolved in the scope of the default module.

The third and fourth parameters of the Example delegate are a ref parameter and an out parameter (ByRef and <OutAttribute> parameters in Visual Basic), so in the IronPython code for the method body they must be treated as instances of Reference<int> and Reference<string> (Reference(Of Integer) and Reference(Of String) in Visual Basic). The Value property of ClrModule.Reference is used to obtain the value of the ref parameter, and to set the values of both parameters.

The code example sets the global variable in the default module, then creates the delegate that represents the method. When the delegate is invoked, the method body prints a result, increments the ref parameter, sets the value of the out parameter, and returns the result. The host displays the returned result and the altered values of the ref and out parameters.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Runtime.InteropServices

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Long, _
    ByRef p3 As Integer, <OutAttribute> ByRef p4 As String) As Double

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The method body uses the parameter names of the delegate
        ' type, Example. Note that p3 is a ByRef parameter and p4 is
        ' an <OutAttribute> parameter, so they contain instances of
        ' ClrModule.Reference. The Reference.Value property is used
        ' to obtain the value of the ByRef parameter, and to set the
        ' values of the two parameters.
        Dim statements As String = _
            "x = p1 * (p2 + p3.Value) - globalValue" & vbLf & _
            "print 'Iron Python prints the result:', x" & vbLf & _
            "p3.Value += 1" & vbLf & _
            "p4.Value = 'Hello from IronPython!'" & vbLf & _
            "return x"

        engine.Globals.Add("globalValue", 1)

        Dim pythonMethod As Example = _
            engine.CreateMethod(Of Example)(statements)

        Dim outValue As String = Nothing
        Dim refValue As Integer = 88
        Dim result As Double = _
            pythonMethod(1.4, 12, refValue, outValue)
        Console.WriteLine("The host prints the result: {0}", result)
        Console.WriteLine("refValue = {0}, outValue = '{1}'", _
            refValue, outValue)

    End Sub
End Class

' This code example produces the following output:
'
'Iron Python prints the result: 139.0
'The host prints the result: 139
'refValue = 89, outValue = 'Hello from IronPython!'
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, long p2, ref int p3, out string p4);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The method body uses the parameter names of the delegate
        // type, Example. Note that p3 is a ref parameter and p4 is
        // an out parameter, so they contain instances of
        // ClrModule.Reference. The Reference.Value property is used
        // to obtain the value of the ref parameter, and to set the
        // values of the two parameters.
        string statements =
            "x = p1 * (p2 + p3.Value) - globalValue\n" +
            "print 'Iron Python prints the result:', x\n" +
            "p3.Value += 1\n" +
            "p4.Value = 'Hello from IronPython!'\n" +
            "return x";

        engine.Globals.Add("globalValue", 1);

        Example pythonMethod = engine.CreateMethod<Example>(
            statements
        );

        string outValue = null;
        int refValue = 88;
        double result = pythonMethod(1.4, 12, ref refValue, out outValue);
        Console.WriteLine("The host prints the result: {0}",
            result);
        Console.WriteLine("refValue = {0}, outValue = '{1}'",
            refValue, outValue);
    }
}

/* This code example produces the following output:

Iron Python prints the result: 139.0
The host prints the result: 139
refValue = 89, outValue = 'Hello from IronPython!'
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateMethod Generic Method (String, EngineModule)
See Also Example
collapseAll image DropDown image

Creates a delegate of the specified type, which can be used to execute the specified IronPython method body and optionally return a result. The method is executed within the scope of the specified module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateMethod(Of TDelegate) ( _
    statements As String, _
    engineModule As EngineModule _
) As TDelegate
Visual Basic (Usage)
Dim instance As PythonEngine
Dim statements As String
Dim engineModule As EngineModule
Dim returnValue As TDelegate

returnValue = instance.CreateMethod(statements, engineModule)
C#
public TDelegate CreateMethod<TDelegate> (
    string statements,
    EngineModule engineModule
)
C++
public:
generic<typename TDelegate>
TDelegate CreateMethod (
    String^ statements,
    EngineModule^ engineModule
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The type of delegate that is used to represent the method body.

Parameters

statements

A method body consisting of a series of IronPython statements that can use the parameter names supplied in parameters, or the names of the parameters of TDelegate if parameters is a null reference (Nothing in Visual Basic). The statements are separated by line feed characters.

engineModule

The module in which the method is executed.

Return Value

A delegate of type TDelegate, which can be used to execute the compiled method body in the scope of engineModule.

Expand image Exceptions

Exception type | Condition
ArgumentNullException | engineModule is a null reference (Nothing in Visual Basic).
ArgumentException | TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | statements contains a syntax error.

Expand image Remarks

The delegate that is returned can be invoked many times, but statements are compiled only once. When all references to the delegate have been released, the memory used by the compiled code is reclaimed by garbage collection.

The CreateMethod generic method parses the method body specified in statements using the names of the parameters of TDelegate as variables.

In addition, statements can use any name that can be resolved in the scope of engineModule.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in statements as instances of ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, or to set the value of a ref or out parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. See the code example for the CreateMethod(String,Generic IList) method overload.

When the delegate returned by this method is invoked, IronPython throws a PythonNameErrorException exception if statements contains symbols that cannot be resolved in the scope of engineModule.

If TDelegate returns a value type, and there is no return statement in statements, the delegate throws ArgumentTypeException when invoked. This is because methods in Python that do not explicitly return a value return None.

To create a delegate instance that is not bound to a specific module, use the CreateMethodUnscoped method.

To create a delegate bound to the default module, specify PythonEngine.DefaultModule for engineModule, or use the CreateMethod(String) method overload.

Expand image Example

The following code example declares a delegate named Example and creates an instance of that delegate to execute a simple method body in the scope of a specified module. The method body uses four variables that are names of parameters of the delegate type, one variable created within the scope of the method body, and one that must be resolved in the scope of the specified module.

The third and fourth parameters of the Example delegate are a ref parameter and an out parameter (ByRef and <OutAttribute> parameters in Visual Basic), so in the IronPython code for the method body they must be treated as instances of Reference<int> and Reference<string> (Reference(Of Integer) and Reference(Of String) in Visual Basic). The Value property of ClrModule.Reference is used to obtain the value of the ref parameter, and to set the values of both parameters.

The code example creates the module and sets the global variable, then creates the delegate that represents the method. When the delegate is invoked, the method body prints and returns a result, increments the ref parameter, and sets the value of the out parameter. The host displays the returned result, and the altered values of the ref and out parameters.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Runtime.InteropServices

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Long, _
    ByRef p3 As Integer, <OutAttribute> ByRef p4 As String) As Double

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The method body uses the parameter names of the delegate
        ' type, Example. Note that p3 is a ByRef parameter and p4 is
        ' an <OutAttribute> parameter, so they contain instances of
        ' ClrModule.Reference. The Reference.Value property is used
        ' to obtain the value of the ByRef parameter, and to set the
        ' values of the two parameters.
        Dim statements As String = _
            "x = p1 * (p2 + p3.Value) - globalValue" & vbLf & _
            "print 'Iron Python prints the result:', x" & vbLf & _
            "p3.Value += 1" & vbLf & _
            "p4.Value = 'Hello from IronPython!'" & vbLf & _
            "return x"

        Dim testModule As EngineModule = _
            engine.CreateModule("TM", True)
        testModule.Globals.Add("globalValue", 1)

        Dim pythonMethod As Example = _
            engine.CreateMethod(Of Example)(statements, testModule)

        Dim outValue As String = Nothing
        Dim refValue As Integer = 88
        Dim result As Double = _
            pythonMethod(1.4, 12, refValue, outValue)
        Console.WriteLine("The host prints the result: {0}", result)
        Console.WriteLine("refValue = {0}, outValue = '{1}'", _
            refValue, outValue)

    End Sub
End Class

' This code example produces the following output:
'
'Iron Python prints the result: 139.0
'The host prints the result: 139
'refValue = 89, outValue = 'Hello from IronPython!'
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, long p2, ref int p3, out string p4);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The method body uses the parameter names of the delegate
        // type, Example. Note that p3 is a ref parameter and p4 is
        // an out parameter, so they contain instances of

        // ClrModule.Reference. The Reference.Value property is used
        // to obtain the value of the ref parameter, and to set the
        // values of the two parameters.
        string statements =
            "x = p1 * (p2 + p3.Value) - globalValue\n" +
            "print 'Iron Python prints the result:', x\n" +
            "p3.Value += 1\n" +
            "p4.Value = 'Hello from IronPython!'\n" +
            "return x";

        EngineModule testModule = engine.CreateModule("TM", true);
        testModule.Globals.Add("globalValue", 1);

        Example pythonMethod = engine.CreateMethod<Example>(
            statements, testModule
        );

        string outValue = null;
        int refValue = 88;
        double result = pythonMethod(1.4, 12, ref refValue, out outValue);
        Console.WriteLine("The host prints the result: {0}",
            result);
        Console.WriteLine("refValue = {0}, outValue = '{1}'",
            refValue, outValue);
    }
}

/* This code example produces the following output:

Iron Python prints the result: 139.0
The host prints the result: 139
refValue = 89, outValue = 'Hello from IronPython!'
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateMethod Generic Method (String, Generic IList)
See Also Example
collapseAll image DropDown image

Creates a delegate of the specified type, which can be used to execute the specified IronPython method body and optionally return a result. The method is executed within the scope of the default module. A set of alternate parameter names can be specified, for use in the method body.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateMethod(Of TDelegate) ( _
    statements As String, _
    parameters As IList(Of String) _
) As TDelegate
Visual Basic (Usage)
Dim instance As PythonEngine
Dim statements As String
Dim parameters As IList(Of String)
Dim returnValue As TDelegate

returnValue = instance.CreateMethod(statements, parameters)
C#
public TDelegate CreateMethod<TDelegate> (
    string statements,
    IList<string> parameters
)
C++
public:
generic<typename TDelegate>
TDelegate CreateMethod (
    String^ statements,
    IList<String^>^ parameters
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The type of delegate that is used to represent the method body.

Parameters

statements

A method body consisting of a series of IronPython statements that can use the parameter names supplied in parameters, or the names of the parameters of TDelegate if parameters is a null reference (Nothing in Visual Basic). The statements are separated by line feed characters.

parameters

An array of parameter names to be used in the method body, instead of the parameter names of the delegate type.

Return Value

A delegate of type TDelegate, which can be used to execute the compiled method body in the scope of engineModule.

Expand image Exceptions

Exception type | Condition
ArgumentException | The number of parameter names in parameters is different from the number of parameters in TDelegate. -or- TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | statements contains a syntax error.

Expand image Remarks

The delegate that is returned can be invoked many times, but statements are compiled only once. When all references to the delegate have been released, the memory used by the compiled code is reclaimed by garbage collection.

The CreateMethod generic method parses the method body specified in statements and binds the names specified in parameters to the corresponding parameters of TDelegate. The correspondence is positional. If parameters is a null reference (Nothing in Visual Basic), the parameter names of the delegate type are used.

In addition to names contained in parameters, statements can use any name that can be resolved in the scope of the default module.

The names in parameters completely replace the parameter names of the delegate. You cannot use a mixture of names in statements.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in statements as instances of ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, or to set the value of a ref or out parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. See the code example.

When the delegate returned by this method is invoked, IronPython throws a PythonNameErrorException exception if statements contains symbols that cannot be resolved in the scope of the default module.

If TDelegate returns a value type, and there is no return statement in statements, the delegate throws ArgumentTypeException when invoked. This is because methods in Python that do not explicitly return a value return None.

To create a delegate instance that is not bound to a specific module, use the CreateMethodUnscoped method.

To create a delegate bound to a module other than the default module, use the CreateMethod(String,Generic IList,EngineModule) method overload.

Expand image Example

The following code example declares a delegate named Example and creates an instance of that delegate to execute a simple method body in the scope of a the default module.

The method body uses four variable names provided in the parameterNames array, one variable created within the scope of the method body, and one that must be resolved in the scope of the default module. The names in the parameterNames array are bound by position to the names and types of the parameters of the Example delegate.

The third and fourth parameters of the Example delegate are a ref parameter and an out parameter (ByRef and <OutAttribute> parameters in Visual Basic), so in the IronPython code for the method body they must be treated as instances of Reference<int> and Reference<string> (Reference(Of Integer) and Reference(Of String) in Visual Basic). The Value property of ClrModule.Reference is used to obtain the value of the ref parameter, and to set the values of both parameters.

The code example sets the global variable in the default module, then creates the delegate that represents the method. When the delegate is invoked, the method body prints a result, increments the ref parameter, sets the value of the out parameter, and returns the result. The host displays the returned result and the altered values of the ref and out parameters.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Runtime.InteropServices

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Long, _
    ByRef p3 As Integer, <OutAttribute> ByRef p4 As String) As Double

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The method body uses the parameter names of the delegate
        ' type, Example. Note that 'three' is a ByRef parameter and
        ' 'four' is an <Out> parameter, so they contain instances of
        ' ClrModule.Reference. The Reference.Value property is used
        ' to obtain the value of the ByRef parameter, and to set the
        ' values of the two parameters.
        Dim statements As String = _
            "x = one * (two + three.Value) - globalValue" & vbLf & _
            "print 'Iron Python prints the result:', x" & vbLf & _
            "three.Value += 1" & vbLf & _
            "four.Value = 'Hello from IronPython!'" & vbLf & _
            "return x"

        Dim parameterNames As String() = _
            { "one", "two", "three", "four" }

        engine.Globals.Add("globalValue", 1)

        Dim pythonMethod As Example = _
            engine.CreateMethod(Of Example)(statements, parameterNames)

        Dim outValue As String = Nothing
        Dim refValue As Integer = 88
        Dim result As Double = _
            pythonMethod(1.4, 12, refValue, outValue)
        Console.WriteLine("The host prints the result: {0}", result)
        Console.WriteLine("refValue = {0}, outValue = '{1}'", _
            refValue, outValue)

    End Sub
End Class

' This code example produces the following output:
'
'Iron Python prints the result: 139.0
'The host prints the result: 139
'refValue = 89, outValue = 'Hello from IronPython!'
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, long p2, ref int p3, out string p4);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The method body uses the parameter names of the delegate
        // type, Example. Note that 'three' is a ref parameter and
        // 'four' is an out parameter, so they contain instances of
        // ClrModule.Reference. The Reference.Value property is used
        // to obtain the value of the ref parameter, and to set the
        // values of the two parameters.
        string statements =
            "x = one * (two + three.Value) - globalValue\n" +
            "print 'Iron Python prints the result:', x\n" +
            "three.Value += 1\n" +
            "four.Value = 'Hello from IronPython!'\n" +
            "return x";

        string[] parameterNames = { "one", "two", "three", "four" };

        engine.Globals.Add("globalValue", 1);

        Example pythonMethod = engine.CreateMethod<Example>(
            statements, parameterNames
        );

        string outValue = null;
        int refValue = 88;
        double result = pythonMethod(1.4, 12, ref refValue, out outValue);
        Console.WriteLine("The host prints the result: {0}",
            result);
        Console.WriteLine("refValue = {0}, outValue = '{1}'",
            refValue, outValue);
    }
}

/* This code example produces the following output:

Iron Python prints the result: 139.0
The host prints the result: 139
refValue = 89, outValue = 'Hello from IronPython!'
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateMethod Generic Method (String, Generic IList, EngineModule)
See Also Example
collapseAll image DropDown image

Creates a delegate of the specified type, which can be used to execute the specified IronPython method body and optionally return a result. The method is executed within the scope of the specified module. A set of alternate parameter names can be specified, for use in the method body.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateMethod(Of TDelegate) ( _
    statements As String, _
    parameters As IList(Of String), _
    engineModule As EngineModule _
) As TDelegate
Visual Basic (Usage)
Dim instance As PythonEngine
Dim statements As String
Dim parameters As IList(Of String)
Dim engineModule As EngineModule
Dim returnValue As TDelegate

returnValue = instance.CreateMethod(statements, parameters, engineModule)
C#
public TDelegate CreateMethod<TDelegate> (
    string statements,
    IList<string> parameters,
    EngineModule engineModule
)
C++
public:
generic<typename TDelegate>
TDelegate CreateMethod (
    String^ statements,
    IList<String^>^ parameters,
    EngineModule^ engineModule
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The type of delegate that is used to represent the method body.

Parameters

statements

A method body consisting of a series of IronPython statements that can use the parameter names supplied in parameters, or the names of the parameters of TDelegate if parameters is a null reference (Nothing in Visual Basic). The statements are separated by line feed characters.

parameters

An array of parameter names to be used in the method body, instead of the parameter names of the delegate type.

engineModule

The module in which the method is executed.

Return Value

A delegate of type TDelegate, which can be used to execute the compiled method body in the scope of engineModule.

Expand image Exceptions

Exception type | Condition
ArgumentNullException | engineModule is a null reference (Nothing in Visual Basic).
ArgumentException | The number of parameter names in parameters is different from the number of parameters in TDelegate. -or- TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | statements contains a syntax error.

Expand image Remarks

The delegate that is returned can be invoked many times, but statements are compiled only once. When all references to the delegate have been released, the memory used by the compiled code is reclaimed by garbage collection.

The CreateMethod generic method parses the method body specified in statements and binds the names specified in parameters to the corresponding parameters of TDelegate. The correspondence is positional. If parameters is a null reference (Nothing in Visual Basic), the parameter names of the delegate type are used.

In addition to names contained in parameters, statements can use any name that can be resolved in the scope of engineModule.

The names in parameters completely replace the parameter names of the delegate. You cannot use a mixture of names in statements.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in statements as instances of ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, or to set the value of a ref or out parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. See the code example for the CreateMethod(String,Generic IList) method overload.

When the delegate returned by this method is invoked, IronPython throws a PythonNameErrorException exception if statements contains symbols that cannot be resolved in the scope of engineModule.

If TDelegate returns a value type, and there is no return statement in statements, the delegate throws ArgumentTypeException when invoked. This is because methods in Python that do not explicitly return a value return None.

To create a delegate instance that is not bound to a specific module, use the CreateMethodUnscoped method.

To create a delegate bound to the default module, specify PythonEngine.DefaultModule for engineModule, or use the CreateMethod(String) or CreateMethod(String,Generic IList) method overload.

Expand image Example

The following code example declares a delegate type, and creates an instance of that delegate type to calculate the sum of n factorial (n!), given starting and ending values of n. The result is calculated by a method body that uses nStart and nEnd to represent the starting and ending values.

The code example creates an array containing the parameter names nStart and nEnd, so that those names can be used in the method body instead of the parameter names from the delegate type.

The code example creates a module in which the method is executed, and calls the CreateMethod with the string containing the method body statements, the array of alternate parameter names, and the module. The resulting delegate is used to execute the method body.

Note Note

This example does not use any global variables from the module. If it did, the example code would have to use the EngineModule.Globals property to set the necessary variables for the module.

To compile this example, you need a reference to IronPython.dll.

Compare this code example to the code example for the CreateMethodUnscoped(String,Generic IList) method overload, which creates a delegate that is not bound to a particular module.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Delegate Function Example(ByVal p1 As Integer, _
                          ByVal p2 As Integer) As Double

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The method body. Notice that the variables used are nStart
        ' and nEnd, which are not the parameter names from the delegate
        ' type.
        Dim statements As String = _
            "total = 0" & vbLf & _
            "if nStart > 0 and nEnd > nStart:" & vbLf & _
            "  element = 1" & vbLf & _
            "  for i in range(2, nStart):" & vbLf & _
            "    element *= i" & vbLf & _
            "  for i in range(nStart, nEnd + 1):" & vbLf & _
            "    element *= i" & vbLf & _
            "    total += element" & vbLf & _
            "return total"

        ' Specify the variable names that are actually used in the
        ' method body.
        Dim paramNames As String() = { "nStart", "nEnd" }

        Dim testModule As EngineModule = engine.CreateModule("TM", True)

        Dim sumNFactorial As Example = _
            engine.CreateMethod(Of Example)(statements, paramNames, testModule)

        Console.WriteLine("Sum of n! for n = 3 to 6: {0}", _
            sumNFactorial(3, 6))
        Console.WriteLine("Sum of n! for n = 5 to 10: {0}", _
            sumNFactorial(5, 10))

    End Sub
End Class

' This code example produces the following output:
'
'Sum of n! for n = 3 to 6: 870
'Sum of n! for n = 5 to 10: 4037880
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(int p1, int p2);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The method body. Notice that the variables used are nStart
        // and nEnd, which are not the parameter names from the delegate
        // type.
        string statements = "total = 0\n" +
                            "if nStart > 0 and nEnd > nStart:\n" +
                            "  element = 1\n" +
                            "  for i in range(2, nStart):\n" +
                            "    element *= i\n" +
                            "  for i in range(nStart, nEnd + 1):\n" +
                            "    element *= i\n" +
                            "    total += element\n" +
                            "return total";

        // Specify the variable names that are actually used in the
        // method body.
        string[] paramNames = { "nStart", "nEnd" };

        EngineModule testModule = engine.CreateModule("TM", true);

        Example sumNFactorial =
            engine.CreateMethod<Example>(statements, paramNames, testModule);

        Console.WriteLine("Sum of n! for n = 3 to 6: {0}",
            sumNFactorial(3, 6));
        Console.WriteLine("Sum of n! for n = 5 to 10: {0}",
            sumNFactorial(5, 10));
    }
}

/* This code example produces the following output:

Sum of n! for n = 3 to 6: 870
Sum of n! for n = 5 to 10: 4037880
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateMethodUnscoped Generic Method
See Also
CollapseAll image DropDown image

Creates a factory delegate that produces instances of a delegate representing a compiled method body, bound to any specified module.

Expand image Overload List

Name | Description
PythonEngine.CreateMethodUnscoped (String) | Returns a ModuleBinder generic delegate that can be used to bind the specified IronPython method body to a module scope, using an inner delegate of the specified type.
PythonEngine.CreateMethodUnscoped (String, Generic IList) | Returns a ModuleBinder generic delegate that can be used to bind the specified IronPython method body to a module scope, using an inner delegate of the specified type. A set of alternate parameter names can be specified, for use in the method body.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateMethodUnscoped Generic Method (String)
See Also Example
collapseAll image DropDown image

Returns a ModuleBinder generic delegate that can be used to bind the specified IronPython method body to a module scope, using an inner delegate of the specified type.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateMethodUnscoped(Of TDelegate) ( _
    statements As String _
) As ModuleBinder(Of TDelegate)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim statements As String
Dim returnValue As ModuleBinder(Of TDelegate)

returnValue = instance.CreateMethodUnscoped(statements)
C#
public ModuleBinder<TDelegate> CreateMethodUnscoped<TDelegate> (
    string statements
)
C++
public:
generic<typename TDelegate>
ModuleBinder<TDelegate>^ CreateMethodUnscoped (
    String^ statements
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The delegate type that is used to represent the method body.

Parameters

statements

The delegate type that is used to represent the method body.

Return Value

A ModuleBinder generic delegate that wraps a delegate of type TDelegate, and can bind that delegate to any module. This allows the compiled method body specified in statements to be executed in the scope of any module.

Expand image Exceptions

Exception type | Condition
ArgumentException | TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | statements contains a syntax error.

Expand image Remarks

Use the CreateMethodUnscoped generic method when you have a method body you want to execute in the scopes of arbitrary modules. This is useful when the host application allows the user to provide custom implementations of some application features.

This method creates a delegate of type TDelegate that represents the method body specified in statements and that is not bound to the scope of any module. Instead of returning the unscoped delegate directly, the CreateMethodUnscoped generic method returns a ModuleBinder generic delegate that wraps the TDelegate delegate. When you want to execute statements in the scope of a module, use the ModuleBinder generic delegate to produce a TDelegate delegate that is bound to the desired module, and then invoke the TDelegate delegate. That is, the ModuleBinder generic delegate functions as a factory method for producing bound delegates.

The statements are compiled only once.

When the delegate representing the compiled method body is invoked, IronPython throws a PythonNameErrorException exception if expression contains symbols that cannot be resolved in the scope of the module the delegate is bound to.

Note Note

If you only need to execute statements in the scope of one module, you can use the CreateMethod(String,Generic IList,EngineModule) generic method to produce a delegate that is bound to that module.

If TDelegate returns a value type, and there is no return statement in statements, the delegate throws ArgumentTypeException when invoked. This is because methods in Python that do not explicitly return a value return None.

This method parses statements and uses the names of parameters of TDelegate as variable names. In addition to the parameter names, statements can use other names. Those names are resolved in the scope of the eventual target module.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in statements as instances of ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, or to set the value of a ref or out parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. See the code example.

Expand image Example

The following code example declares a delegate named Example and uses the CreateMethodUnscoped generic method to create an instance of Example that is not bound to any module. The Example delegate is wrapped in an instance of the ModuleBinder generic delegate, which can be used to bind Example to any module scope.

In this code example, the Example delegate represents a method body that uses two parameters passed by value, a ref parameter (ByRef in Visual Basic), an out parameter (<OutAttribute> in Visual Basic), and a global variable. The names of the delegate parameters are used as variables in the method body.

Because parameters p3 and p4 are ref and out parameters, respectively, they are passed as instances of ClrModule.Reference. In the IronPython code for the method body they must be treated as instances of Reference<int> and Reference<string> (Reference(Of Integer) and Reference(Of String) in Visual Basic). The ClrModule.Reference.Value property is used to obtain the value of the ref parameter, and to set the values of both parameters.

The ModuleBinder created by the CreateMethodUnscoped method is stored in a variable named methodFactory.

The code example declares two variables, outValue and refValue, to use with the out and ref parameters.

The ModuleBinder delegate in methodFactory is invoked to create an instance of Example bound to the default module. The bound delegate pythonMethod is then invoked to obtain the result. Finally, the result is displayed to the console.

To show binding to different modules, the code example creates a second module, module2, and sets its globalValue variable to a different value. A bound delegate is created and invoked, and the results are displayed.

To compile this example, you need a reference to IronPython.dll.

Compare this code example to the code example for the CreateMethod method overload, which creates a delegate that is bound to a specific module.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Runtime.InteropServices

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Long, _
    ByRef p3 As Integer, <OutAttribute> ByRef p4 As String) As Double

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The method body uses the parameter names of the delegate
        ' type, Example. Note that p3 is a ByRef parameter and p4 is
        ' an <OutAttribute> parameter, so they contain instances of
        ' ClrModule.Reference. The Reference.Value property is used
        ' to obtain the value of the ByRef parameter, and to set the
        ' values of the two parameters.
        Dim statements As String = _
            "x = p1 * (p2 + p3.Value) - globalValue" & vbLf & _
            "print 'Iron Python prints the result:', x" & vbLf & _
            "p3.Value += 1" & vbLf & _
            "p4.Value = 'Hello from IronPython!'" & vbLf & _
            "return x"

        engine.Globals.Add("globalValue", 1)

        Dim methodFactory As ModuleBinder(Of Example) = _
            engine.CreateMethodUnscoped(Of Example)(statements)

        ' Create the variables that are passed <Out> and ByRef.
        Dim outValue As String = Nothing
        Dim refValue As Integer = 88

        Console.WriteLine("Default module:")
        Dim pythonMethod As Example = _
            methodFactory(engine.DefaultModule)
        Dim result As Double = _
            pythonMethod(1.4, 12, refValue, outValue)
        Console.WriteLine("The host prints the result: {0}", _
            result)
        Console.WriteLine("refValue = {0}, outValue = '{1}'", _
            refValue, outValue)

        Dim mod2 As EngineModule = engine.CreateModule("mod2", True)
        mod2.Globals.Add("globalValue", 10000)

        Console.WriteLine(vbLf + "Another module:")
        pythonMethod = methodFactory(mod2)
        result = pythonMethod(1.4, 12, refValue, outValue)
        Console.WriteLine("The host prints the result: {0}", _
            result)
        Console.WriteLine("refValue = {0}, outValue = '{1}'", _
            refValue, outValue)

    End Sub 'Main
End Class 'CodeSample

' This code example produces the following output:
'
'Default module:
'Iron Python prints the result:  139.0
'The host prints the result: 139
'refValue = 89, outValue = 'Hello from IronPython!'
'
'Another module:
'Iron Python prints the result:  -9858.6
'The host prints the result: -9858.6
'refValue = 90, outValue = 'Hello from IronPython!'
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, long p2, ref int p3, out string p4);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The method body uses the parameter names of the delegate
        // type, Example. Note that p3 is a ref parameter and p4 is
        // a out parameter, so they contain instances of
        // ClrModule.Reference. The Reference.Value property is used
        // to obtain the value of the ref parameter, and to set the
        // values of the two parameters.
        string statements =
            "x = p1 * (p2 + p3.Value) - globalValue\n" +
            "print 'Iron Python prints the result: ', x\n" +
            "p3.Value += 1\n" +
            "p4.Value = 'Hello from IronPython!'\n" +
            "return x\n";

        engine.Globals.Add("globalValue", 1);

        ModuleBinder<Example> methodFactory =
            engine.CreateMethodUnscoped<Example>(statements);

        // Create the variables that are passed out and ref.
        string outValue = null;
        int refValue = 88;

        Console.WriteLine("Default module:");
        Example pythonMethod = methodFactory(engine.DefaultModule);
        double result = pythonMethod(1.4, 12, ref refValue, out outValue);
        Console.WriteLine("The host prints the result: {0}",
            result);
        Console.WriteLine("refValue = {0}, outValue = '{1}'",
            refValue, outValue);

        EngineModule mod2 = engine.CreateModule("mod2", true);
        mod2.Globals.Add("globalValue", 10000);

        Console.WriteLine("\nAnother module:");
        pythonMethod = methodFactory(mod2);
        result = pythonMethod(1.4, 12, ref refValue, out outValue);
        Console.WriteLine("The host prints the result: {0}",
            result);
        Console.WriteLine("refValue = {0}, outValue = '{1}'",
            refValue, outValue);
    }
}

/* This code example produces the following output:

Default module:
Iron Python prints the result:  139.0
The host prints the result: 139
refValue = 89, outValue = 'Hello from IronPython!'

Another module:
Iron Python prints the result:  -9858.6
The host prints the result: -9858.6
refValue = 90, outValue = 'Hello from IronPython!'
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateMethodUnscoped Generic Method (String, Generic IList)
See Also Example
collapseAll image DropDown image

Returns a ModuleBinder generic delegate that can be used to bind the specified IronPython method body to a module scope, using an inner delegate of the specified type. A set of alternate parameter names can be specified, for use in the method body.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateMethodUnscoped(Of TDelegate) ( _
    statements As String, _
    parameters As IList(Of String) _
) As ModuleBinder(Of TDelegate)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim statements As String
Dim parameters As IList(Of String)
Dim returnValue As ModuleBinder(Of TDelegate)

returnValue = instance.CreateMethodUnscoped(statements, parameters)
C#
public ModuleBinder<TDelegate> CreateMethodUnscoped<TDelegate> (
    string statements,
    IList<string> parameters
)
C++
public:
generic<typename TDelegate>
ModuleBinder<TDelegate>^ CreateMethodUnscoped (
    String^ statements,
    IList<String^>^ parameters
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

TDelegate

The delegate type that is used to represent the method body.

Parameters

statements

A method body consisting of a series of IronPython statements that can use the parameter names supplied in parameters, or the names of the parameters of TDelegate if parameters is a null reference (Nothing in Visual Basic). Statements are separated by line feed characters.

parameters

An array of parameter names to be used in the method body, instead of the parameter names of the delegate type.

Return Value

A ModuleBinder generic delegate that wraps a delegate of type TDelegate, and can bind the TDelegate to any module. This allows the compiled method body specified in statements to be executed in the scope of any module.

Expand image Exceptions

Exception type | Condition
ArgumentException | TDelegate is not a subclass of Delegate. -or- TDelegate is either of the specific types Delegate or MulticastDelegate.
PythonSyntaxErrorException | statements contains a syntax error.

Expand image Remarks

Use the CreateMethodUnscoped generic method when you have a method body you want to execute in the scopes of arbitrary modules. This is useful when the host application allows the user to provide custom implementations of some application features.

This method creates a delegate of type TDelegate that represents the method body specified in statements and that is not bound to the scope of any module. Instead of returning the unscoped delegate directly, the CreateMethodUnscoped generic method returns a ModuleBinder generic delegate that wraps the TDelegate delegate. When you want to execute statements in the scope of a module, use the ModuleBinder generic delegate to produce a TDelegate delegate that is bound to the desired module, and then invoke the TDelegate delegate. That is, the ModuleBinder generic delegate functions as a factory method for producing bound delegates.

The statements are compiled only once.

When the delegate representing the compiled method body is invoked, IronPython throws a PythonNameErrorException exception if statements contains symbols that cannot be resolved in the scope of the module the delegate is bound to.

Note Note

If you only need to execute statements in the scope of one module, you can use the CreateMethod(String,Generic IList,EngineModule) generic method to produce a delegate that is bound to that module.

If TDelegate returns a value type, and there is no return statement in statements, the delegate throws ArgumentTypeException when invoked. This is because methods in Python that do not explicitly return a value return None.

This method parses statements and binds the names specified in parameters to the corresponding parameters of TDelegate. The correspondence is positional. If parameters is a null reference (Nothing in Visual Basic), the parameter names of TDelegate are used.

In addition to names contained in parameters, statements can use other names. Those names are resolved in the scope of the eventual target module.

The names in parameters completely replace the parameter names of TDelegate. You cannot use a mixture of names in statements.

If TDelegate has ref or out parameters (ByRef or <OutAttribute> parameters in Visual Basic), they are available to the IronPython code in statements as instances of IronPython.Modules.ClrModule.Reference, where the generic type argument of the ClrModule.Reference instance is the type of the corresponding parameter. To obtain the value of a ref parameter, or to set the value of a ref or out parameter, the IronPython code must use the ClrModule.Reference.Value property. The value of an out parameter is undefined. See the code example for the CreateMethodUnscoped(String) method overload.

Expand image Example

The following code example declares a delegate type named Example and uses the CreateMethodUnscoped generic method to create an instance of Example that is not bound to any module. The Example delegate is wrapped in an instance of the ModuleBinder generic delegate, which can be used to bind Example to any module scope.

The instance of Example represents a method body that calculates the sum of n factorial (n!), given starting and ending values of n. The method body uses nStart and nEnd to represent the starting and ending values.

The code example creates an array containing the parameter names nStart and nEnd, so that those names can be used in the method body instead of the parameter names from the delegate type.

The code example creates a module and then executes the method body in the default module and in the newly created module. Two sets of arguments are supplied: The first set is for the ModuleBinder generic delegate, and specifies the module where execution is to occur. The second set is for the Example delegate returned by the ModuleBinder delegate.

Note Note

This example does not use any global variables from the module. If it did, the example code would have to use the EngineModule.Globals property to set the necessary variables.

To compile this example, you need a reference to IronPython.dll.

Compare this code example to the code example for the CreateMethod(String,Generic IList,EngineModule) method overload, which creates a delegate that is bound to a specific module.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Delegate Function Example(ByVal p1 As Integer, _
                          ByVal p2 As Integer) As Double
Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The method body. Notice that the variables used are nStart
        ' and nEnd, which are not the parameter names from the delegate
        ' type.
        Dim statements As String = _
            "total = 0" & vbLf & _
            "if nStart > 0 and nEnd > nStart:" & vbLf & _
            "  element = 1" & vbLf & _
            "  for i in range(2, nStart):" & vbLf & _
            "    element *= i" & vbLf & _
            "  for i in range(nStart, nEnd + 1):" & vbLf & _
            "    element *= i" & vbLf & _
            "    total += element" & vbLf & _
            "return total"

        ' Specify the variable names that are actually used in the
        ' method body.
        Dim paramNames As String() = { "nStart", "nEnd" }

        Dim sumNFactorial As ModuleBinder(Of Example) = _
            engine.CreateMethodUnscoped(Of Example)(statements, paramNames)

        ' Create a delegate bound to the default module.
        Dim boundSumNFactorial As Example = _
            sumNFactorial(engine.DefaultModule)

        ' Invoke the bound delegate, and display the result.
        Dim result As Double = boundSumNFactorial(3, 6)

        Console.WriteLine("Sum of n! for n = 3 to 6: {0}", _
            result)

        ' Repeat the process with another module. This time, the
        ' Example delegate is not saved.
        '
        Dim testModule As EngineModule = _
            engine.CreateModule("TM", True)
        Console.WriteLine("Sum of n! for n = 5 to 10: {0}", _
            sumNFactorial(testModule)(5, 10))

    End Sub
End Class

' This code example produces the following output:
'
'Sum of n! for n = 3 to 6: 870
'Sum of n! for n = 5 to 10: 4037880
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(int p1, int p2);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The method body. Notice that the variables used are nStart
        // and nEnd, which are not the parameter names from the delegate
        // type.
        string statements = "total = 0\n" +
                            "if nStart > 0 and nEnd > nStart:\n" +
                            "  element = 1\n" +
                            "  for i in range(2, nStart):\n" +
                            "    element *= i\n" +
                            "  for i in range(nStart, nEnd + 1):\n" +
                            "    element *= i\n" +
                            "    total += element\n" +
                            "return total";

        // Specify the variable names that are actually used in the
        // method body.
        string[] paramNames = { "nStart", "nEnd" };

        ModuleBinder<Example> sumNFactorial =
            engine.CreateMethodUnscoped<Example>(statements, paramNames);

        EngineModule testModule = engine.CreateModule("TM", true);

        // Create a delegate bound to the default module.
        Example boundSumNFactorial =
            sumNFactorial(engine.DefaultModule);

        // Invoke the bound delegate, and display the result.
        double result = boundSumNFactorial(3, 6);

        Console.WriteLine("Sum of n! for n = 3 to 6: {0}",
            result);

        // Repeat the process with another module. This time, the
        // Example delegate is not saved.
        //
        Console.WriteLine("Sum of n! for n = 5 to 10: {0}",
            sumNFactorial(testModule)(5, 10));
    }
}

/* This code example produces the following output:

Sum of n! for n = 3 to 6: 870
Sum of n! for n = 5 to 10: 4037880
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateModule Method
See Also
CollapseAll image DropDown image

Creates a new module.

Expand image Overload List

Name | Description
PythonEngine.CreateModule () | Creates a new module with no preset global variables. The contents of this module are not published.
PythonEngine.CreateModule (String, Boolean) | Creates a new module with the specified name and with no preset global variables, and specifies whether the module is to be published.
PythonEngine.CreateModule (String, Generic IDictionary, Boolean) | Creates a new module with the specified name and the specified global variables, and specifies whether the module is to be published.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateModule Method ()
See Also Example
collapseAll image DropDown image

Creates a new module with no preset global variables. The contents of this module are not published.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateModule As EngineModule
Visual Basic (Usage)
Dim instance As PythonEngine
Dim returnValue As EngineModule

returnValue = instance.CreateModule
C#
public EngineModule CreateModule ()
C++
public:
EngineModule^ CreateModule ()
J#
public EngineModule CreateModule ()
JScript
public function CreateModule () : EngineModule

Return Value

An EngineModule object representing the new module.

Expand image Remarks

Modules are required in order to execute code. Every PythonEngine instance has a default module, which can be obtained using the DefaultModule property. You can create additional modules in order to provide different scopes for executing code.

A module that is not published does not appear in sys.modules, and its symbols cannot be imported into other modules.

Expand image Example

The following code example creates an unpublished module, imports the sys module, and executes IronPython code to list the contents of sys.modules. The unpublished module does not appear in the list.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        Dim em As EngineModule = engine.CreateModule()

        Dim statements As String = _
            "import sys" & vbLf & _
            "for s in sys.modules:" & vbLf & _
            "  print s"
        engine.Execute(statements, em)

    End Sub
End Class

' This code example produces the following output:
'
'sys
'__builtin__
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        EngineModule em = engine.CreateModule();

        string statements =
                   "import sys\n" +
                   "for s in sys.modules:\n" +
                   "  print s";
        engine.Execute(statements, em);
    }
}

/* This code example produces the following output:

sys
__builtin__
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateModule Method (String, Boolean)
See Also Example
collapseAll image DropDown image

Creates a new module with the specified name and with no preset global variables, and specifies whether the module is to be published.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateModule ( _
    moduleName As String, _
    publishModule As Boolean _
) As EngineModule
Visual Basic (Usage)
Dim instance As PythonEngine
Dim moduleName As String
Dim publishModule As Boolean
Dim returnValue As EngineModule

returnValue = instance.CreateModule(moduleName, publishModule)
C#
public EngineModule CreateModule (
    string moduleName,
    bool publishModule
)
C++
public:
EngineModule^ CreateModule (
    String^ moduleName,
    bool publishModule
)
J#
public EngineModule CreateModule (
    String moduleName,
    boolean publishModule
)
JScript
public function CreateModule (
    moduleName : String,
    publishModule : boolean
) : EngineModule

Parameters

moduleName

The name used to identify the module in sys.modules and in import statements.

publishModule

true to publish the module in sys.modules, making it available for import into other modules; otherwise, false.

Return Value

An EngineModule object representing the new module.

Expand image Exceptions

Exception type | Condition
ArgumentException | moduleName is a null reference (Nothing in Visual Basic).

Expand image Remarks

Modules are required in order to execute code. Every PythonEngine instance has a default module, which can be obtained using the DefaultModule property. You can create additional modules in order to provide different scopes for executing code.

If the module is published, you can use moduleName with the IronPython import statement to add the module to the global dictionaries of other modules. In IronPython code, the module can be found in the sys.modules list, using moduleName as the key.

Host applications can cache the return value of this method, in order to evaluate expressions, set global variables, and execute code in the scope of this module.

Caution note Caution

No exception is thrown if moduleName is the same as the name of an existing module. If publishModule is true, the new module replaces the existing module in sys.modules. Modules that have already imported moduleName continue to use the global state of the old module, but modules that import moduleName from that moment on get the global state of the new module.

Expand image Example

The following code example creates a published module named exampleModule and adds a global variable, then executes IronPython code that displays the list of published modules.

In the default module, the example executes IronPython code that imports exampleModule into the default module, imports its global data, and uses the global variable defined earlier. The del statement is used to remove exampleModule from the list of published modules, and the list is displayed. Finally, the IronPython code uses the global data again to show that it is still imported.

In exampleModule, the code example executes IronPython code to show that the module still exists.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        Dim em As EngineModule = _
            engine.CreateModule("exampleModule", True)
        em.Globals.Add("data", 21)

        Dim statements As String = _
            "import sys" & vbLf & _
            "for s in sys.modules:" & vbLf & _
            "  print s"
        engine.Execute(statements, em)

        statements = _
            "import exampleModule" & vbLf & _
            "from exampleModule import *" & vbLf & _
            "print '\nUse imported value:', 2 * data" & vbLf & _
            "import sys" & vbLf & _
            "del sys.modules['exampleModule']" & vbLf & _
            "print '\nAfter unpublishing exampleModule:'" & vbLf & _
            "for s in sys.modules:" & vbLf & _
            "  print s" & vbLf & _
            "print '\nexampleModule is still imported:', 2 * data"
        engine.Execute(statements)

        engine.Execute("print '\nHello from exampleModule'", em)

    End Sub
End Class

' This code example produces the following output:
'
'sys
'__builtin__
'exampleModule
'
'Use imported value: 42
'
'After unpublishing exampleModule:
'sys
'__builtin__
'
'exampleModule is still imported: 42
'
'Hello from exampleModule
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        EngineModule em = engine.CreateModule("exampleModule", true);
        em.Globals.Add("data", 21);

        string statements =
                   "import sys\n" +
                   "for s in sys.modules:\n" +
                   "  print s";
        engine.Execute(statements, em);

        statements =
                   "import exampleModule\n" +
                   "from exampleModule import *\n" +
                   "print '\\nUse imported value:', 2 * data\n" +
                   "import sys\n" +
                   "del sys.modules['exampleModule']\n" +
                   "print '\\nAfter unpublishing exampleModule:'\n" +
                   "for s in sys.modules:\n" +
                   "  print s\n" +
                   "print '\\nexampleModule is still imported:', 2 * data";
        engine.Execute(statements);

        engine.Execute("print '\\nHello from exampleModule'", em);
    }
}

/* This code example produces the following output:

sys
__builtin__
exampleModule

Use imported value: 42

After unpublishing exampleModule:
sys
__builtin__

exampleModule is still imported: 42

Hello from exampleModule
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateModule Method (String, Generic IDictionary, Boolean)
See Also Example
collapseAll image DropDown image

Creates a new module with the specified name and the specified global variables, and specifies whether the module is to be published.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateModule ( _
    moduleName As String, _
    globals As IDictionary(Of String, Object), _
    publishModule As Boolean _
) As EngineModule
Visual Basic (Usage)
Dim instance As PythonEngine
Dim moduleName As String
Dim globals As IDictionary(Of String, Object)
Dim publishModule As Boolean
Dim returnValue As EngineModule

returnValue = instance.CreateModule(moduleName, globals, publishModule)
C#
public EngineModule CreateModule (
    string moduleName,
    IDictionary<string,Object> globals,
    bool publishModule
)
C++
public:
EngineModule^ CreateModule (
    String^ moduleName,
    IDictionary<String^, Object^>^ globals,
    bool publishModule
)
J#
public EngineModule CreateModule (
    String moduleName,
    IDictionary<String,Object> globals,
    boolean publishModule
)
JScript
public function CreateModule (
    moduleName : String,
    globals : IDictionary<String,Object>,
    publishModule : boolean
) : EngineModule

Parameters

moduleName

The name used to identify the module in sys.modules and in import statements.

globals

A collection that implements IDictionary for objects with string keys, which represent global variables and their values.

publishModule

true to publish the module in sys.modules, making it available for import into other modules; otherwise, false.

Return Value

An EngineModule object representing the new module.

Expand image Exceptions

Exception type | Condition
ArgumentException | moduleName is a null reference (Nothing in Visual Basic). -or- globals is a null reference (Nothing in Visual Basic).

Expand image Remarks

Modules are required in order to execute code. Every PythonEngine instance has a default module, which can be obtained using the DefaultModule property. You can create additional modules in order to provide different scopes for executing code.

If the module is published, you can use moduleName with the IronPython import statement to add the module to the global dictionaries of other modules. In IronPython code, the module can be found in the sys.modules list, using moduleName as the key.

Host applications can cache the return value of this method, in order to evaluate expressions, set global variables, and execute code in the scope of this module.

Caution note Caution

No exception is thrown if moduleName is the same as the name of an existing module. If publishModule is true, the new module replaces the existing module in sys.modules. Modules that have already imported moduleName continue to use the global state of the old module, but modules that import moduleName from that moment on get the global state of the new module.

Expand image Example

The following code example creates a dictionary of objects with string keys, populates it with two key/value pairs, and uses it to initialize the global dictionary of a new module.

The module is imported into the default module, and the imported global variables are used in a calculation.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Collections.Generic
Imports IronPython.Hosting

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        Dim globals As New Dictionary(Of String, Object)
        globals.Add("one", 1)
        globals.Add("two", 2)

        Dim em As EngineModule = _
            engine.CreateModule("exampleModule", globals, True)

        Dim statements As String = _
            "import exampleModule" & vbLf & _
            "from exampleModule import *" & vbLf & _
            "print '\nUse imported values:', one + two"
        engine.Execute(statements)

    End Sub
End Class

' This code example produces the following output:
'
'Use imported values: 3
C# CopyCode image Copy Code
using System;
using System.Collections.Generic;
using IronPython.Hosting;

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        Dictionary<string,object> globals =
            new Dictionary<string,object>();
        globals.Add("one", 1);
        globals.Add("two", 2);

        EngineModule em =
            engine.CreateModule("exampleModule", globals, true);

        string statements =
                   "import exampleModule\n" +
                   "from exampleModule import *\n" +
                   "print '\\nUse imported values:', one + two";
        engine.Execute(statements);
    }
}

/* This code example produces the following output:

Use imported values: 3
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CreateOptimizedModule Method
See Also Example
collapseAll image DropDown image

Loads the specified file containing IronPython statements, using the specified module name and specifying whether the module is available for import into other modules, and create a module optimized for accessing global data. The memory used by the module is not freed until the application domain is unloaded.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function CreateOptimizedModule ( _
    fileName As String, _
    moduleName As String, _
    publishModule As Boolean _
) As OptimizedEngineModule
Visual Basic (Usage)
Dim instance As PythonEngine
Dim fileName As String
Dim moduleName As String
Dim publishModule As Boolean
Dim returnValue As OptimizedEngineModule

returnValue = instance.CreateOptimizedModule(fileName, moduleName, publishModule)
C#
public OptimizedEngineModule CreateOptimizedModule (
    string fileName,
    string moduleName,
    bool publishModule
)
C++
public:
OptimizedEngineModule^ CreateOptimizedModule (
    String^ fileName,
    String^ moduleName,
    bool publishModule
)
J#
public OptimizedEngineModule CreateOptimizedModule (
    String fileName,
    String moduleName,
    boolean publishModule
)
JScript
public function CreateOptimizedModule (
    fileName : String,
    moduleName : String,
    publishModule : boolean
) : OptimizedEngineModule

Parameters

fileName

The absolute or relative path of a file containing IronPython statements.

moduleName

The name to use in IronPython import statements, and as the module key in sys.modules.

publishModule

true to publish the module in sys.modules, so that it can be imported into other modules; otherwise false.

Return Value

An EngineModule whose global code has optimized references to global variables.

Expand image Remarks

Use an OptimizedEngineModule to hold code that does not change and that makes many references to global data.

Note Important

Unlike other compiled code, the memory occupied by code in an OptimizedEngineModule is not reclaimed by garbage collection. The memory is not released until the application domain that contains the OptimizedEngineModule is unloaded.

After creating the optimized module, call the OptimizedEngineModule.Execute method on the new OptimizedEngineModule, to execute the global code in the module and optimize references to global variables.

You cannot specify a global dictionary to use with an OptimizedEngineModule. A global dictionary is created automatically, and can be accessed using the EngineModule.Globals property of the base class, EngineModule.

You can add code to an OptimizedEngineModule, but that code will not have optimized references to global data.

Expand image Example

The following code example executes the same global code in two modules, an optimized module and an ordinary module, and compares their performance. The CreateOptimizedModule method is used to create the optimized module.

To run the code example, create a file named optiMod.py containing the following statements:

CopyCode image Copy Code
a = 1002
b = 1004
c = 1006
d = 1008
e = 1010
f = 1012
g = 1014
h = 1016
i = 1018
j = 1020

def test():
  return a + b + c + d + e + f + g + h + i + j

The function test makes a number of references to global variables, to exaggerate the effect of optimizing global references.

The optiMod.py file is loaded into the optimized module by the PythonEngine.CreateOptimizedModule method. The Execute method is then called to execute the global code. The IronPython.Hosting.PythonEngine.ExecuteFile method is used to load the same file is loaded into the ordinary module and to execute its global code.

Note Note

Executing the global code compiles the test function.

In order to call the test function multiple times, the code example compiles a test script containing the code st = test(). Before each run, the script is "burned in" in the appropriate module, to reduce the likelihood of initialization overhead affecting the results.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Diagnostics

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' Load the file optiMod.py into an optimized module.
        Dim om As OptimizedEngineModule = _
            engine.CreateOptimizedModule("optiMod.py", "om", True)
        om.Execute()

        ' Load the same file into an ordinary module.
        Dim m As EngineModule = engine.CreateModule("m", True)
        engine.ExecuteFile("optiMod.py", m)

        ' The global code in both modules has been executed, so the
        ' test functions have been compiled. Now compile a script
        ' that calls the test function.
        Dim script As CompiledCode = engine.Compile("st = test()")

        ' Call the test script once before timing it, to ensure that
        ' any initialization code is run.
        script.Execute(om)

        Dim s As New Stopwatch()
        s.Start()

        For i As Integer = 0 To 9999
            script.Execute(om)
        Next i

        s.Stop()
        Dim optimized As Double = s.ElapsedTicks

        ' Call the test script once before timing it, to ensure that
        ' any initialization code is run.
        script.Execute(m)

        s.Reset()
        s.Start()

        For i As Integer = 0 To 9999
            script.Execute(m)
        Next i

        s.Stop()
        Dim nonOptimized As Double = s.ElapsedTicks

        Console.WriteLine( _
            "Non-optimized code took {0:F2} times as long to run.", _
            nonOptimized / optimized)

    End Sub
End Class

' This code example produces output similar to the following:
'
'Non-optimized code took 2.92 times as long to run.
'
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Diagnostics;

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // Load the file optiMod.py into an optimized module.
        OptimizedEngineModule om =
            engine.CreateOptimizedModule("optiMod.py", "om", true);
        om.Execute();

        // Load the same file into an ordinary module.
        EngineModule m = engine.CreateModule("m", true);
        engine.ExecuteFile("optiMod.py", m);

        // The global code in both modules has been executed, so the
        // test functions have been compiled. Now compile a script
        // that calls the test function.
        CompiledCode script = engine.Compile("st = test()");

        // Call the test script once before timing it, to ensure that
        // any initialization code is run.
        script.Execute(om);

        Stopwatch s = new Stopwatch();
        s.Start();

        for (int i = 0; i < 10000; i++)
        {
            script.Execute(om);
        }

        s.Stop();
        double optimized = s.ElapsedTicks;

        // Call the test script once before timing it, to ensure that
        // any initialization code is run.
        script.Execute(m);

        s.Reset();
        s.Start();

        for (int i = 0; i < 10000; i++)
        {
            script.Execute(m);
        }

        s.Stop();
        double nonOptimized = s.ElapsedTicks;

        Console.WriteLine(
            "Non-optimized code took {0:F2} times as long to run.",
            nonOptimized / optimized);
    }
}

/* This code example produces output similar to the following:

Non-optimized code took 2.92 times as long to run.
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Dispose Method
See Also
collapseAll image DropDown image

Releases the resources used by the current engine.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Dispose
Visual Basic (Usage)
Dim instance As PythonEngine

instance.Dispose
C#
public void Dispose ()
C++
public:
virtual void Dispose () sealed
J#
public final void Dispose ()
JScript
public final function Dispose ()

Expand image Remarks

Calling the Dispose method closes the input, output, and error files that were set using SetStandardError, SetStandardInput, and SetStandardOutput, but does not reset the target streams. A subsequent print statement therefore raises an exception for an operation on a closed stream.

Calling the Dispose method does not disable the PythonEngine, but might release other resources. Further use of a disposed PythonEngine is not recommended.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.DumpDebugInfo Method
See Also
collapseAll image DropDown image

This method is not intended for use in application code.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Shared Sub DumpDebugInfo
Visual Basic (Usage)
PythonEngine.DumpDebugInfo
C#
public static void DumpDebugInfo ()
C++
public:
static void DumpDebugInfo ()
J#
public static void DumpDebugInfo ()
JScript
public static function DumpDebugInfo ()

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Evaluate Method
See Also
CollapseAll image DropDown image

Evaluates an IronPython expression.

Expand image Overload List

Name | Description
PythonEngine.Evaluate (String) | Evaluates an IronPython expression in the scope of the default module.
PythonEngine.Evaluate (String, EngineModule) | Evaluates an IronPython expression in the scope of the specified module.
PythonEngine.Evaluate (String, EngineModule, Generic IDictionary) | Evaluates an IronPython expression in the scope of the default module.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Evaluate Method (String)
See Also Example
collapseAll image DropDown image

Evaluates an IronPython expression in the scope of the default module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Evaluate ( _
    expression As String _
) As Object
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim returnValue As Object

returnValue = instance.Evaluate(expression)
C#
public Object Evaluate (
    string expression
)
C++
public:
Object^ Evaluate (
    String^ expression
)
J#
public Object Evaluate (
    String expression
)
JScript
public function Evaluate (
    expression : String
) : Object

Parameters

expression

The IronPython expression to evaluate.

Return Value

The result of evaluating the expression.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | expression contains an error such as a bad operand type.
PythonSyntaxErrorException | expression contains a statement. -or- expression contains a syntax error.
PythonNameErrorException | expression contains an unrecognized symbol.

Expand image Remarks

The Evaluate method allows a host application to evaluate IronPython expressions without having to wrap the expression in an IronPython eval function. The result is the same as calling eval. The global dictionary used to evaluate the expression is supplied by the module.

To specify a local dictionary to use when evaluating an expression, use the Evaluate(String,EngineModule,Generic IDictionary) method overload.

This method can throw any exception that can occur during the evaluation of an IronPython expression.

Note Note

If you intend to use an expression frequently, you can compile the expression using the CreateLambda generic method. To use the compiled expression in multiple modules, use the CreateLambdaUnscoped generic method.

Expand image Example

The following code example demonstrates the overloads of the Evaluate method. The expression "x + 24" is evaluated three times:

  • The variable x is set to 42 in the global dictionary of the default module, and the Evaluate(String) method overload is used to evaluate the expression in the scope of the default module.

  • A module named "tm" is created, and the variable x is set to 3033 in the global dictionary of the new module. The Evaluate(String,EngineModule) method overload is used to evaluate the expression in the scope of the new module.

  • A local dictionary is created, with variable x set to 17, and the Evaluate(String,EngineModule,Generic IDictionary) method overload is used to evaluate the expression in the scope of module "tm" including the local dictionary.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Collections.Generic

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine()

        engine.Globals.Add("x", 42)
        Dim result As Object = engine.Evaluate("24 + x")
        Console.WriteLine(result)

        Dim tm As EngineModule = engine.CreateModule("tm", true)
        tm.Globals.Add("x", 3033)
        result = engine.Evaluate("24 + x", tm)
        Console.WriteLine(result)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("x", 17)
        result = engine.Evaluate("24 + x", tm, locals)
        Console.WriteLine(result)

    End Sub
End Class

' This code example produces the following output:
'
'66
'3057
'41
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Collections.Generic;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        engine.Globals.Add("x", 42);
        object result = engine.Evaluate("24 + x");
        Console.WriteLine(result);

        EngineModule tm = engine.CreateModule("tm", true);
        tm.Globals.Add("x", 3033);
        result = engine.Evaluate("24 + x", tm);
        Console.WriteLine(result);

        Dictionary<string, object> locals =
            new Dictionary<string, object>();
        locals.Add("x", 17);
        result = engine.Evaluate("24 + x", tm, locals);
        Console.WriteLine(result);
    }
}

/* This code example produces the following output:

66
3057
41
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Evaluate Method (String, EngineModule)
See Also Example
collapseAll image DropDown image

Evaluates an IronPython expression in the scope of the specified module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Evaluate ( _
    expression As String, _
    engineModule As EngineModule _
) As Object
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim engineModule As EngineModule
Dim returnValue As Object

returnValue = instance.Evaluate(expression, engineModule)
C#
public Object Evaluate (
    string expression,
    EngineModule engineModule
)
C++
public:
Object^ Evaluate (
    String^ expression,
    EngineModule^ engineModule
)
J#
public Object Evaluate (
    String expression,
    EngineModule engineModule
)
JScript
public function Evaluate (
    expression : String,
    engineModule : EngineModule
) : Object

Parameters

expression

The IronPython expression to evaluate.

engineModule

The module in whose scope the expression is evaluated.

Return Value

The result of evaluating the expression.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | expression contains an error such as a bad operand type.
PythonSyntaxErrorException | expression contains a statement. -or- expression contains a syntax error.
PythonNameErrorException | expression contains an unrecognized symbol.

Expand image Remarks

The Evaluate method allows a host application to evaluate IronPython expressions in a specified module, without having to wrap the expression in an IronPython eval function. The result is the same as calling eval. The global dictionary used to evaluate the expression is supplied by the module.

To specify a local dictionary to use when evaluating an expression, use the Evaluate(String,EngineModule,Generic IDictionary) method overload.

This method can throw any exception that can occur during the evaluation of an IronPython expression.

Note Note

If you intend to use an expression frequently, you can compile the expression using the CreateLambda generic method. To use the compiled expression in multiple modules, use the CreateLambdaUnscoped generic method.

Expand image Example

The following code example demonstrates the overloads of the Evaluate method. The expression "x + 24" is evaluated three times:

  • The variable x is set to 42 in the global dictionary of the default module, and the Evaluate(String) method overload is used to evaluate the expression in the scope of the default module.

  • A module named "tm" is created, and the variable x is set to 3033 in the global dictionary of the new module. The Evaluate(String,EngineModule) method overload is used to evaluate the expression in the scope of the new module.

  • A local dictionary is created, with variable x set to 17, and the Evaluate(String,EngineModule,Generic IDictionary) method overload is used to evaluate the expression in the scope of module "tm" including the local dictionary.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Collections.Generic

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine()

        engine.Globals.Add("x", 42)
        Dim result As Object = engine.Evaluate("24 + x")
        Console.WriteLine(result)

        Dim tm As EngineModule = engine.CreateModule("tm", true)
        tm.Globals.Add("x", 3033)
        result = engine.Evaluate("24 + x", tm)
        Console.WriteLine(result)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("x", 17)
        result = engine.Evaluate("24 + x", tm, locals)
        Console.WriteLine(result)

    End Sub
End Class

' This code example produces the following output:
'
'66
'3057
'41
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Collections.Generic;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        engine.Globals.Add("x", 42);
        object result = engine.Evaluate("24 + x");
        Console.WriteLine(result);

        EngineModule tm = engine.CreateModule("tm", true);
        tm.Globals.Add("x", 3033);
        result = engine.Evaluate("24 + x", tm);
        Console.WriteLine(result);

        Dictionary<string, object> locals =
            new Dictionary<string, object>();
        locals.Add("x", 17);
        result = engine.Evaluate("24 + x", tm, locals);
        Console.WriteLine(result);
    }
}

/* This code example produces the following output:

66
3057
41
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Evaluate Method (String, EngineModule, Generic IDictionary)
See Also Example
collapseAll image DropDown image

Evaluates an IronPython expression in the scope of the default module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Evaluate ( _
    expression As String, _
    engineModule As EngineModule, _
    locals As IDictionary(Of String, Object) _
) As Object
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim engineModule As EngineModule
Dim locals As IDictionary(Of String, Object)
Dim returnValue As Object

returnValue = instance.Evaluate(expression, engineModule, locals)
C#
public Object Evaluate (
    string expression,
    EngineModule engineModule,
    IDictionary<string,Object> locals
)
C++
public:
Object^ Evaluate (
    String^ expression,
    EngineModule^ engineModule,
    IDictionary<String^, Object^>^ locals
)
J#
public Object Evaluate (
    String expression,
    EngineModule engineModule,
    IDictionary<String,Object> locals
)
JScript
public function Evaluate (
    expression : String,
    engineModule : EngineModule,
    locals : IDictionary<String,Object>
) : Object

Parameters

expression

The IronPython expression to evaluate.

engineModule

The module in whose scope the expression is evaluated.

locals

A collection that implements IDictionary for objects with string keys, which represent global variables and their values.

Return Value

The result of evaluating the expression.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | expression contains an error such as a bad operand type.
PythonSyntaxErrorException | expression contains a statement. -or- expression contains a syntax error.
PythonNameErrorException | expression contains an unrecognized symbol.

Expand image Remarks

The Evaluate method allows a host application to evaluate IronPython expressions without having to wrap the expression in an IronPython eval function. The result is the same as calling eval. The global dictionary used to evaluate the expression is supplied by the module, and the local dictionary (if any) is specified by locals.

To use this method overload with the default module for this PythonEngine, use the DefaultModule property.

This method can throw any exception that can occur during the evaluation of an IronPython expression.

Note Note

If you intend to use an expression frequently, you can compile the expression using the CreateLambda generic method. To use the compiled expression in multiple modules, use the CreateLambdaUnscoped generic method. Local dictionaries cannot be used with these methods.

Expand image Example

The following code example demonstrates the overloads of the Evaluate method. The expression "x + 24" is evaluated three times:

  • The variable x is set to 42 in the global dictionary of the default module, and the Evaluate(String) method overload is used to evaluate the expression in the scope of the default module.

  • A module named "tm" is created, and the variable x is set to 3033 in the global dictionary of the new module. The Evaluate(String,EngineModule) method overload is used to evaluate the expression in the scope of the new module.

  • A local dictionary is created, with variable x set to 17, and the Evaluate(String,EngineModule,Generic IDictionary) method overload is used to evaluate the expression in the scope of module "tm" including the local dictionary.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Collections.Generic

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine()

        engine.Globals.Add("x", 42)
        Dim result As Object = engine.Evaluate("24 + x")
        Console.WriteLine(result)

        Dim tm As EngineModule = engine.CreateModule("tm", true)
        tm.Globals.Add("x", 3033)
        result = engine.Evaluate("24 + x", tm)
        Console.WriteLine(result)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("x", 17)
        result = engine.Evaluate("24 + x", tm, locals)
        Console.WriteLine(result)

    End Sub
End Class

' This code example produces the following output:
'
'66
'3057
'41
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Collections.Generic;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        engine.Globals.Add("x", 42);
        object result = engine.Evaluate("24 + x");
        Console.WriteLine(result);

        EngineModule tm = engine.CreateModule("tm", true);
        tm.Globals.Add("x", 3033);
        result = engine.Evaluate("24 + x", tm);
        Console.WriteLine(result);

        Dictionary<string, object> locals =
            new Dictionary<string, object>();
        locals.Add("x", 17);
        result = engine.Evaluate("24 + x", tm, locals);
        Console.WriteLine(result);
    }
}

/* This code example produces the following output:

66
3057
41
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.EvaluateAs Generic Method
See Also
CollapseAll image DropDown image

Evaluates an IronPython expression and returns a strongly-typed result.

Expand image Overload List

Name | Description
PythonEngine.EvaluateAs (String) | Evaluates the specified IronPython expression in the scope of the default module, and returns the strongly-typed result.
PythonEngine.EvaluateAs (String, EngineModule) | Evaluates the specified IronPython expression in the scope of the specified module, and returns the strongly-typed result.
PythonEngine.EvaluateAs (String, EngineModule, Generic IDictionary) | Evaluates the specified IronPython expression in the scope of the default module, and returns the strongly-typed result. Optionally specifies a dictionary of local names.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.EvaluateAs Generic Method (String)
See Also Example
collapseAll image DropDown image

Evaluates the specified IronPython expression in the scope of the default module, and returns the strongly-typed result.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function EvaluateAs(Of T) ( _
    expression As String _
) As T
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim returnValue As T

returnValue = instance.EvaluateAs(expression)
C#
public T EvaluateAs<T> (
    string expression
)
C++
public:
generic<typename T>
T EvaluateAs (
    String^ expression
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

T

The type to which the return value is cast.

Parameters

expression

The expression to evaluate.

Return Value

The result of evaluating the expression, cast to type T.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | The result cannot be cast to type T. -or- expression contains an error such as a bad operand type.
PythonSyntaxErrorException | expression contains a statement. -or- expression contains a syntax error.
PythonNameErrorException | expression contains an unrecognized symbol.

Expand image Remarks

The EvaluateAs generic method allows a host application to evaluate IronPython expressions without having to wrap the expression in an IronPython eval function. The result is the same as calling eval. The global dictionary used to evaluate the expression is supplied by the module.

To specify a local dictionary to use when evaluating an expression, use the EvaluateAs(String,EngineModule,Generic IDictionary) method overload.

This method can throw any exception that can occur during the evaluation of an IronPython expression.

Note Note

If you intend to use an expression frequently, you can compile the expression using the CreateLambda generic method. To use the compiled expression in multiple modules, use the CreateLambdaUnscoped generic method.

Expand image Example

The following code example demonstrates the overloads of the EvaluateAs method. The expression "x + 24" is evaluated three times:

  • The variable x is set to 42 in the global dictionary of the default module, and the EvaluateAs(String) method overload is used to evaluate the expression in the scope of the default module.

  • A module named "tm" is created, and the variable x is set to 3033 in the global dictionary of the new module. The EvaluateAs(String,EngineModule) method overload is used to evaluate the expression in the scope of the new module.

  • A local dictionary is created, with variable x set to 17, and the EvaluateAs(String,EngineModule,Generic IDictionary) method overload is used to evaluate the expression in the scope of module "tm" including the local dictionary.

Finally, the code example demonstrates the exception that is thrown when the type of the result cannot be cast to type T. The expression "abc + xyz" is evaluated, and Integer is specified for T.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Collections.Generic

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine()

        engine.Globals.Add("x", 42)
        Dim result As Integer = engine.EvaluateAs(Of Integer)("24 + x")
        Console.WriteLine(result)

        Dim tm As EngineModule = engine.CreateModule("tm", true)
        tm.Globals.Add("x", 3033)
        result = engine.EvaluateAs(Of Integer)("24 + x", tm)
        Console.WriteLine(result)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("x", 17)
        result = engine.EvaluateAs(Of Integer)("24 + x", tm, locals)
        Console.WriteLine(result)

        Try
            Dim x As Integer = _
                engine.EvaluateAs(Of Integer)("'abc' + 'xyz'")
        Catch ex As Exception
            Console.WriteLine("Caught: " & ex.GetType().ToString() _
                & vbCrLf & vbTab & ex.Message)
        End Try
    End Sub
End Class

' This code example produces the following output:
'
'66
'3057
'41
'Caught: IronPython.Runtime.Exceptions.ArgumentTypeException
'        Cannot convert str(abcxyz) to Int32
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Collections.Generic;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        engine.Globals.Add("x", 42);
        int result = engine.EvaluateAs<int>("24 + x");
        Console.WriteLine(result);

        EngineModule tm = engine.CreateModule("tm", true);
        tm.Globals.Add("x", 3033);
        result = engine.EvaluateAs<int>("24 + x", tm);
        Console.WriteLine(result);

        Dictionary<string, object> locals =
            new Dictionary<string, object>();
        locals.Add("x", 17);

        result = engine.EvaluateAs<int>("24 + x", tm, locals);
        Console.WriteLine(result);

        try
        {
            int x = engine.EvaluateAs<int>("'abc' + 'xyz'");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught: {0}\n\t{1}",
                ex.GetType(), ex.Message);
        }
    }
}

/* This code example produces the following output:

66
3057
41
Caught: IronPython.Runtime.Exceptions.ArgumentTypeException
        Cannot convert str(abcxyz) to Int32
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.EvaluateAs Generic Method (String, EngineModule)
See Also Example
collapseAll image DropDown image

Evaluates the specified IronPython expression in the scope of the specified module, and returns the strongly-typed result.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function EvaluateAs(Of T) ( _
    expression As String, _
    engineModule As EngineModule _
) As T
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim engineModule As EngineModule
Dim returnValue As T

returnValue = instance.EvaluateAs(expression, engineModule)
C#
public T EvaluateAs<T> (
    string expression,
    EngineModule engineModule
)
C++
public:
generic<typename T>
T EvaluateAs (
    String^ expression,
    EngineModule^ engineModule
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

T

The type to which the return value is cast.

Parameters

expression

The IronPython expression to evaluate.

engineModule

The module in whose scope the expression is evaluated.

Return Value

The result of evaluating the expression, cast to type T.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | The result cannot be cast to type T. -or- expression contains an error such as a bad operand type.
PythonSyntaxErrorException | expression contains a statement. -or- expression contains a syntax error.
PythonNameErrorException | expression contains an unrecognized symbol.

Expand image Remarks

The EvaluateAs generic method allows a host application to evaluate IronPython expressions without having to wrap the expression in an IronPython eval function. The result is the same as calling eval. The global dictionary used to evaluate the expression is supplied by the module.

To specify a local dictionary to use when evaluating an expression, use the EvaluateAs(String,EngineModule,Generic IDictionary) method overload.

This method can throw any exception that can occur during the evaluation of an IronPython expression.

Note Note

If you intend to use an expression frequently, you can compile the expression using the CreateLambda generic method. To use the compiled expression in multiple modules, use the CreateLambdaUnscoped generic method.

Expand image Example

The following code example demonstrates the overloads of the EvaluateAs method. The expression "x + 24" is evaluated three times:

  • The variable x is set to 42 in the global dictionary of the default module, and the EvaluateAs(String) method overload is used to evaluate the expression in the scope of the default module.

  • A module named "tm" is created, and the variable x is set to 3033 in the global dictionary of the new module. The EvaluateAs(String,EngineModule) method overload is used to evaluate the expression in the scope of the new module.

  • A local dictionary is created, with variable x set to 17, and the EvaluateAs(String,EngineModule,Generic IDictionary) method overload is used to evaluate the expression in the scope of module "tm" including the local dictionary.

Finally, the code example demonstrates the exception that is thrown when the type of the result cannot be cast to type T. The expression "abc + xyz" is evaluated, and Integer is specified for T.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Collections.Generic

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine()

        engine.Globals.Add("x", 42)
        Dim result As Integer = engine.EvaluateAs(Of Integer)("24 + x")
        Console.WriteLine(result)

        Dim tm As EngineModule = engine.CreateModule("tm", true)
        tm.Globals.Add("x", 3033)
        result = engine.EvaluateAs(Of Integer)("24 + x", tm)
        Console.WriteLine(result)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("x", 17)
        result = engine.EvaluateAs(Of Integer)("24 + x", tm, locals)
        Console.WriteLine(result)

        Try
            Dim x As Integer = _
                engine.EvaluateAs(Of Integer)("'abc' + 'xyz'")
        Catch ex As Exception
            Console.WriteLine("Caught: " & ex.GetType().ToString() _
                & vbCrLf & vbTab & ex.Message)
        End Try
    End Sub
End Class

' This code example produces the following output:
'
'66
'3057
'41
'Caught: IronPython.Runtime.Exceptions.ArgumentTypeException
'        Cannot convert str(abcxyz) to Int32
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Collections.Generic;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        engine.Globals.Add("x", 42);
        int result = engine.EvaluateAs<int>("24 + x");
        Console.WriteLine(result);

        EngineModule tm = engine.CreateModule("tm", true);
        tm.Globals.Add("x", 3033);
        result = engine.EvaluateAs<int>("24 + x", tm);
        Console.WriteLine(result);

        Dictionary<string, object> locals =
            new Dictionary<string, object>();
        locals.Add("x", 17);

        result = engine.EvaluateAs<int>("24 + x", tm, locals);
        Console.WriteLine(result);

        try
        {
            int x = engine.EvaluateAs<int>("'abc' + 'xyz'");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught: {0}\n\t{1}",
                ex.GetType(), ex.Message);
        }
    }
}

/* This code example produces the following output:

66
3057
41
Caught: IronPython.Runtime.Exceptions.ArgumentTypeException
        Cannot convert str(abcxyz) to Int32
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.EvaluateAs Generic Method (String, EngineModule, Generic IDictionary)
See Also Example
collapseAll image DropDown image

Evaluates the specified IronPython expression in the scope of the default module, and returns the strongly-typed result. Optionally specifies a dictionary of local names.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function EvaluateAs(Of T) ( _
    expression As String, _
    engineModule As EngineModule, _
    locals As IDictionary(Of String, Object) _
) As T
Visual Basic (Usage)
Dim instance As PythonEngine
Dim expression As String
Dim engineModule As EngineModule
Dim locals As IDictionary(Of String, Object)
Dim returnValue As T

returnValue = instance.EvaluateAs(expression, engineModule, locals)
C#
public T EvaluateAs<T> (
    string expression,
    EngineModule engineModule,
    IDictionary<string,Object> locals
)
C++
public:
generic<typename T>
T EvaluateAs (
    String^ expression,
    EngineModule^ engineModule,
    IDictionary<String^, Object^>^ locals
)
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

T

The type to which the return value is cast.

Parameters

expression

The IronPython expression to evaluate.

engineModule

The module in whose scope the expression is evaluated.

locals

A collection that implements IDictionary for objects with string keys, which represent global variables and their values.

Return Value

The result of evaluating the expression, cast to type T.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | The result cannot be cast to type T. -or- expression contains an error such as a bad operand type.
PythonSyntaxErrorException | expression contains a statement. -or- expression contains a syntax error.
PythonNameErrorException | expression contains an unrecognized symbol.

Expand image Remarks

The EvaluateAs generic method allows a host application to evaluate IronPython expressions without having to wrap the expression in an IronPython eval function. The result is the same as calling eval. The global dictionary used to evaluate the expression is supplied by the module, and the local dictionary (if any) is specified by locals.

To use this method overload with the default module for this PythonEngine, use the DefaultModule property.

This method can throw any exception that can occur during the evaluation of an IronPython expression.

Note Note

If you intend to use an expression frequently, you can compile the expression using the CreateLambda generic method. To use the compiled expression in multiple modules, use the CreateLambdaUnscoped generic method. Local dictionaries cannot be used with these methods.

Expand image Example

The following code example demonstrates the overloads of the EvaluateAs method. The expression "x + 24" is evaluated three times:

  • The variable x is set to 42 in the global dictionary of the default module, and the EvaluateAs(String) method overload is used to evaluate the expression in the scope of the default module.

  • A module named "tm" is created, and the variable x is set to 3033 in the global dictionary of the new module. The EvaluateAs(String,EngineModule) method overload is used to evaluate the expression in the scope of the new module.

  • A local dictionary is created, with variable x set to 17, and the EvaluateAs(String,EngineModule,Generic IDictionary) method overload is used to evaluate the expression in the scope of module "tm" including the local dictionary.

Finally, the code example demonstrates the exception that is thrown when the type of the result cannot be cast to type T. The expression "abc + xyz" is evaluated, and Integer is specified for T.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Collections.Generic

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine()

        engine.Globals.Add("x", 42)
        Dim result As Integer = engine.EvaluateAs(Of Integer)("24 + x")
        Console.WriteLine(result)

        Dim tm As EngineModule = engine.CreateModule("tm", true)
        tm.Globals.Add("x", 3033)
        result = engine.EvaluateAs(Of Integer)("24 + x", tm)
        Console.WriteLine(result)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("x", 17)
        result = engine.EvaluateAs(Of Integer)("24 + x", tm, locals)
        Console.WriteLine(result)

        Try
            Dim x As Integer = _
                engine.EvaluateAs(Of Integer)("'abc' + 'xyz'")
        Catch ex As Exception
            Console.WriteLine("Caught: " & ex.GetType().ToString() _
                & vbCrLf & vbTab & ex.Message)
        End Try
    End Sub
End Class

' This code example produces the following output:
'
'66
'3057
'41
'Caught: IronPython.Runtime.Exceptions.ArgumentTypeException
'        Cannot convert str(abcxyz) to Int32
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Collections.Generic;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        engine.Globals.Add("x", 42);
        int result = engine.EvaluateAs<int>("24 + x");
        Console.WriteLine(result);

        EngineModule tm = engine.CreateModule("tm", true);
        tm.Globals.Add("x", 3033);
        result = engine.EvaluateAs<int>("24 + x", tm);
        Console.WriteLine(result);

        Dictionary<string, object> locals =
            new Dictionary<string, object>();
        locals.Add("x", 17);

        result = engine.EvaluateAs<int>("24 + x", tm, locals);
        Console.WriteLine(result);

        try
        {
            int x = engine.EvaluateAs<int>("'abc' + 'xyz'");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Caught: {0}\n\t{1}",
                ex.GetType(), ex.Message);
        }
    }
}

/* This code example produces the following output:

66
3057
41
Caught: IronPython.Runtime.Exceptions.ArgumentTypeException
        Cannot convert str(abcxyz) to Int32
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Execute Method
See Also
CollapseAll image DropDown image

Executes a series of IronPython statements.

Expand image Overload List

Name | Description
PythonEngine.Execute (String) | Executes the specified IronPython code in the scope of the default module.
PythonEngine.Execute (String, EngineModule) | Executes the specified IronPython code in the scope of the specified module.
PythonEngine.Execute (String, EngineModule, Generic IDictionary) | Executes the specified IronPython code in the scope of the specified module, with the specified local dictionary.
PythonEngine.Execute (String, String, EngineModule, Generic IDictionary) | Executes the specified IronPython code in the scope of the specified module, using the specified local dictionary. Optionally generates debug and traceback information using a specified file containing the IronPython code embedded in its original context, for example in an ASP.NET page.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Execute Method (String)
See Also Example
collapseAll image DropDown image

Executes the specified IronPython code in the scope of the default module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Execute ( _
    scriptCode As String _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim scriptCode As String

instance.Execute(scriptCode)
C#
public void Execute (
    string scriptCode
)
C++
public:
void Execute (
    String^ scriptCode
)
J#
public void Execute (
    String scriptCode
)
JScript
public function Execute (
    scriptCode : String
)

Parameters

scriptCode

The statements to execute.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | scriptCode contains an error such as a bad operand type.
PythonSyntaxErrorException | scriptCode contains a syntax error.
PythonNameErrorException | scriptCode contains an unrecognized symbol.
ArgumentNullException | scriptCode is a null reference (Nothing in Visual Basic).
PythonSystemExitException | scriptCode calls sys.exit.

Expand image Remarks

Separate the lines of IronPython code in statements with line feeds (\n in C#, vbLf in Visual Basic).

This method throws any exceptions raised by the code in scriptCode.

The statements in scriptCode are compiled, and the compiled code is executed in the scope of the default module. Any variables that are set by global code and any functions or classes that are defined in the global code in scriptCode affect the global state of the default module, even if the global keyword is not specified, because this method overload does not specify a local dictionary. To specify a local dictionary, use the Execute(String,EngineModule,Generic IDictionary) method overload.

Note Note

If code is to be executed more than once, it is more efficient to compile it once using the Compile method and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method.

Expand image Example

The following code example demonstrates the overloads of the Execute method. The following IronPython statements are executed three times:

CopyCode image Copy Code
y = 24 + x
print 'y =', y"

  • The variable x is set to 42 in the global dictionary of the default module, and the Evaluate(String) method overload is used to execute the statements in the scope of the default module.

  • A module named "tm" is created, and the variable x is set to 3033 in the global dictionary of the new module. The Evaluate(String,EngineModule) method overload is used to execute the statements in the scope of the new module.

  • A local dictionary is created, with variable x set to 17, and the Evaluate(String,EngineModule,Generic IDictionary) method overload is used to execute the statements in the scope of module "tm" including the local dictionary.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Collections.Generic

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine()

        Dim statements As String = _
            "y = 24 + x" & vbLf & _
            "print 'y =', y"

        engine.Globals.Add("x", 42)
        engine.Execute(statements)

        Dim tm As EngineModule = engine.CreateModule("tm", true)
        tm.Globals.Add("x", 3033)
        engine.Execute(statements, tm)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("x", 17)
        engine.Execute(statements, tm, locals)

    End Sub
End Class

' This code example produces the following output:
'
'y = 66
'y = 3057
'y = 41
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Collections.Generic;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        string statements = "y = 24 + x\n" +
                            "print 'y =', y";

        engine.Globals.Add("x", 42);
        engine.Execute(statements);

        EngineModule tm = engine.CreateModule("tm", true);
        tm.Globals.Add("x", 3033);
        engine.Execute(statements, tm);

        Dictionary<string, object> locals =
            new Dictionary<string, object>();
        locals.Add("x", 17);
        engine.Execute(statements, tm, locals);
    }
}

/* This code example produces the following output:

y = 66
y = 3057
y = 41
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Execute Method (String, EngineModule)
See Also Example
collapseAll image DropDown image

Executes the specified IronPython code in the scope of the specified module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Execute ( _
    scriptCode As String, _
    engineModule As EngineModule _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim scriptCode As String
Dim engineModule As EngineModule

instance.Execute(scriptCode, engineModule)
C#
public void Execute (
    string scriptCode,
    EngineModule engineModule
)
C++
public:
void Execute (
    String^ scriptCode,
    EngineModule^ engineModule
)
J#
public void Execute (
    String scriptCode,
    EngineModule engineModule
)
JScript
public function Execute (
    scriptCode : String,
    engineModule : EngineModule
)

Parameters

scriptCode

The statements to execute.

engineModule

The module whose scope is used to execute scriptCode.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | scriptCode contains an error such as a bad operand type.
PythonSyntaxErrorException | scriptCode contains a syntax error.
PythonNameErrorException | scriptCode contains an unrecognized symbol.
ArgumentNullException | scriptCode is a null reference (Nothing in Visual Basic).
PythonSystemExitException | scriptCode calls sys.exit.

Expand image Remarks

Separate the lines of IronPython code in statements with line feeds (\n in C#, vbLf in Visual Basic).

This method throws any exceptions raised by the code in scriptCode.

The statements in scriptCode are compiled, and the compiled code is executed in the scope of engineModule. Any variables that are set by global code and any functions or classes that are defined in the global code in scriptCode affect the global state of engineModule, even if the global keyword is not specified, because this method overload does not specify a local dictionary. To specify a local dictionary, use the Execute(String,EngineModule,Generic IDictionary) method overload.

Note Note

If code is to be executed more than once, it is more efficient to compile it once using the Compile method and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method.

Expand image Example

The following code example demonstrates the overloads of the Execute method. The following IronPython statements are executed three times:

CopyCode image Copy Code
y = 24 + x
print 'y =', y"

  • The variable x is set to 42 in the global dictionary of the default module, and the Evaluate(String) method overload is used to execute the statements in the scope of the default module.

  • A module named "tm" is created, and the variable x is set to 3033 in the global dictionary of the new module. The Evaluate(String,EngineModule) method overload is used to execute the statements in the scope of the new module.

  • A local dictionary is created, with variable x set to 17, and the Evaluate(String,EngineModule,Generic IDictionary) method overload is used to execute the statements in the scope of module "tm" including the local dictionary.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Collections.Generic

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine()

        Dim statements As String = _
            "y = 24 + x" & vbLf & _
            "print 'y =', y"

        engine.Globals.Add("x", 42)
        engine.Execute(statements)

        Dim tm As EngineModule = engine.CreateModule("tm", true)
        tm.Globals.Add("x", 3033)
        engine.Execute(statements, tm)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("x", 17)
        engine.Execute(statements, tm, locals)

    End Sub
End Class

' This code example produces the following output:
'
'y = 66
'y = 3057
'y = 41
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Collections.Generic;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        string statements = "y = 24 + x\n" +
                            "print 'y =', y";

        engine.Globals.Add("x", 42);
        engine.Execute(statements);

        EngineModule tm = engine.CreateModule("tm", true);
        tm.Globals.Add("x", 3033);
        engine.Execute(statements, tm);

        Dictionary<string, object> locals =
            new Dictionary<string, object>();
        locals.Add("x", 17);
        engine.Execute(statements, tm, locals);
    }
}

/* This code example produces the following output:

y = 66
y = 3057
y = 41
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Execute Method (String, EngineModule, Generic IDictionary)
See Also Example
collapseAll image DropDown image

Executes the specified IronPython code in the scope of the specified module, with the specified local dictionary.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Execute ( _
    scriptCode As String, _
    engineModule As EngineModule, _
    locals As IDictionary(Of String, Object) _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim scriptCode As String
Dim engineModule As EngineModule
Dim locals As IDictionary(Of String, Object)

instance.Execute(scriptCode, engineModule, locals)
C#
public void Execute (
    string scriptCode,
    EngineModule engineModule,
    IDictionary<string,Object> locals
)
C++
public:
void Execute (
    String^ scriptCode,
    EngineModule^ engineModule,
    IDictionary<String^, Object^>^ locals
)
J#
public void Execute (
    String scriptCode,
    EngineModule engineModule,
    IDictionary<String,Object> locals
)
JScript
public function Execute (
    scriptCode : String,
    engineModule : EngineModule,
    locals : IDictionary<String,Object>
)

Parameters

scriptCode

The statements to execute.

engineModule

The module whose scope is used to execute scriptCode.

locals

A collection that implements IDictionary for objects with string keys, which represent global variables and their values.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | scriptCode contains an error such as a bad operand type.
PythonSyntaxErrorException | scriptCode contains a syntax error.
PythonNameErrorException | scriptCode contains an unrecognized symbol.
ArgumentNullException | scriptCode is a null reference (Nothing in Visual Basic).
PythonSystemExitException | scriptCode calls sys.exit.

Expand image Remarks

Separate the lines of IronPython code in statements with line feeds (\n in C#, vbLf in Visual Basic).

This method throws any exceptions raised by the code in scriptCode.

The statements in scriptCode are compiled, and the compiled code is executed in the scope of engineModule. The symbols available to scriptCode include the global state of engineModule and any variables defined in locals.

Note Note

If code is to be executed more than once, it is more efficient to compile it once using the Compile method and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method.

Expand image Example

The following code example demonstrates the overloads of the Execute method. The following IronPython statements are executed three times:

CopyCode image Copy Code
y = 24 + x
print 'y =', y"

  • The variable x is set to 42 in the global dictionary of the default module, and the Evaluate(String) method overload is used to execute the statements in the scope of the default module.

  • A module named "tm" is created, and the variable x is set to 3033 in the global dictionary of the new module. The Evaluate(String,EngineModule) method overload is used to execute the statements in the scope of the new module.

  • A local dictionary is created, with variable x set to 17, and the Evaluate(String,EngineModule,Generic IDictionary) method overload is used to execute the statements in the scope of module "tm" including the local dictionary.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Collections.Generic

Class CodeSample

    Shared Sub Main()

        Dim engine As New PythonEngine()

        Dim statements As String = _
            "y = 24 + x" & vbLf & _
            "print 'y =', y"

        engine.Globals.Add("x", 42)
        engine.Execute(statements)

        Dim tm As EngineModule = engine.CreateModule("tm", true)
        tm.Globals.Add("x", 3033)
        engine.Execute(statements, tm)

        Dim locals As New Dictionary(Of String, Object)
        locals.Add("x", 17)
        engine.Execute(statements, tm, locals)

    End Sub
End Class

' This code example produces the following output:
'
'y = 66
'y = 3057
'y = 41
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using System.Collections.Generic;

class CodeSample
{
    public static void Main()
    {
        PythonEngine engine = new PythonEngine();

        string statements = "y = 24 + x\n" +
                            "print 'y =', y";

        engine.Globals.Add("x", 42);
        engine.Execute(statements);

        EngineModule tm = engine.CreateModule("tm", true);
        tm.Globals.Add("x", 3033);
        engine.Execute(statements, tm);

        Dictionary<string, object> locals =
            new Dictionary<string, object>();
        locals.Add("x", 17);
        engine.Execute(statements, tm, locals);
    }
}

/* This code example produces the following output:

y = 66
y = 3057
y = 41
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Execute Method (String, String, EngineModule, Generic IDictionary)
See Also
collapseAll image DropDown image

Executes the specified IronPython code in the scope of the specified module, using the specified local dictionary. Optionally generates debug and traceback information using a specified file containing the IronPython code embedded in its original context, for example in an ASP.NET page.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Execute ( _
    scriptCode As String, _
    fileName As String, _
    engineModule As EngineModule, _
    locals As IDictionary(Of String, Object) _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim scriptCode As String
Dim fileName As String
Dim engineModule As EngineModule
Dim locals As IDictionary(Of String, Object)

instance.Execute(scriptCode, fileName, engineModule, locals)
C#
public void Execute (
    string scriptCode,
    string fileName,
    EngineModule engineModule,
    IDictionary<string,Object> locals
)
C++
public:
void Execute (
    String^ scriptCode,
    String^ fileName,
    EngineModule^ engineModule,
    IDictionary<String^, Object^>^ locals
)
J#
public void Execute (
    String scriptCode,
    String fileName,
    EngineModule engineModule,
    IDictionary<String,Object> locals
)
JScript
public function Execute (
    scriptCode : String,
    fileName : String,
    engineModule : EngineModule,
    locals : IDictionary<String,Object>
)

Parameters

scriptCode

The statements to execute.

fileName

The relative or absolute path to a file that contains the code in scriptCode, embedded in its original context. For example, in an ASP.NET page, or a null reference (Nothing in Visual Basic) if no debug information is desired.

engineModule

The module whose scope is used to execute scriptCode.

locals

A collection that implements IDictionary for objects with string keys, which represent global variables and their values to be used when executing scriptCode.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | scriptCode contains an error such as a bad operand type.
PythonSyntaxErrorException | scriptCode contains a syntax error.
PythonNameErrorException | scriptCode contains an unrecognized symbol.
ArgumentNullException | scriptCode is a null reference (Nothing in Visual Basic).
PythonSystemExitException | scriptCode calls sys.exit.

Expand image Remarks

The host creates scriptCode by replacing the lines of sourceFileName that do not contain IronPython code with blank lines.

Debug information is only generated if common language runtime debugging is enabled. That is, if EngineOptions.ClrDebuggingEnabled is set to true when the PythonEngine is created.

If sourceFileName is not found, no exception is thrown.

Note Note

If code is to be executed more than once, it is more efficient to compile it once using the Compile method and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.ExecuteFile Method
See Also
CollapseAll image DropDown image

Executes the IronPython statements in a file.

Expand image Overload List

Name | Description
PythonEngine.ExecuteFile (String) | Executes the IronPython statements in the specified file, using the scope of the default module.
PythonEngine.ExecuteFile (String, EngineModule) | Executes the IronPython statements in the specified file, in the scope of the specified module.
PythonEngine.ExecuteFile (String, EngineModule, Generic IDictionary) | Executes the IronPython statements in the specified file, in the scope of the specified module, using the specified local dictionary.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.ExecuteFile Method (String)
See Also
collapseAll image DropDown image

Executes the IronPython statements in the specified file, using the scope of the default module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub ExecuteFile ( _
    fileName As String _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim fileName As String

instance.ExecuteFile(fileName)
C#
public void ExecuteFile (
    string fileName
)
C++
public:
void ExecuteFile (
    String^ fileName
)
J#
public void ExecuteFile (
    String fileName
)
JScript
public function ExecuteFile (
    fileName : String
)

Parameters

fileName

The absolute or relative path of the file that contains the code.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | The file contains an error such as a bad operand type.
PythonSyntaxErrorException | The file contains a syntax error.
PythonNameErrorException | The file contains an unrecognized symbol.
ArgumentNullException | fileName is a null reference (Nothing in Visual Basic).
PythonSystemExitException | The file contains a call to sys.exit.

Expand image Remarks

This method throws any exceptions raised by the code in fileName.

The statements in fileName are compiled, and the compiled code is executed in the scope of the default module. Any variables that are set and any functions that are defined in fileName affect the global state of the default module, even if the global keyword is not specified, because this method overload does not specify a local dictionary. To specify a local dictionary, use the ExecuteFile(String,EngineModule,Generic IDictionary) method overload.

Note Note

If code is to be executed more than once, it is more efficient to compile it once using the CompileFile method and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.ExecuteFile Method (String, EngineModule)
See Also
collapseAll image DropDown image

Executes the IronPython statements in the specified file, in the scope of the specified module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub ExecuteFile ( _
    fileName As String, _
    engineModule As EngineModule _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim fileName As String
Dim engineModule As EngineModule

instance.ExecuteFile(fileName, engineModule)
C#
public void ExecuteFile (
    string fileName,
    EngineModule engineModule
)
C++
public:
void ExecuteFile (
    String^ fileName,
    EngineModule^ engineModule
)
J#
public void ExecuteFile (
    String fileName,
    EngineModule engineModule
)
JScript
public function ExecuteFile (
    fileName : String,
    engineModule : EngineModule
)

Parameters

fileName

The absolute or relative path of the file that contains the code.

engineModule

The module in whose scope the code is executed.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | The file contains an error such as a bad operand type.
PythonSyntaxErrorException | The file contains a syntax error.
PythonNameErrorException | The file contains an unrecognized symbol.
ArgumentNullException | fileName is a null reference (Nothing in Visual Basic).
PythonSystemExitException | The file contains a call to sys.exit.

Expand image Remarks

This method throws any exceptions raised by the code in fileName.

The statements in fileName are compiled, and the compiled code is executed in the scope of the engineModule. Any variables that are set and any functions that are defined in fileName affect the global state of the engineModule, even if the global keyword is not specified, because this method overload does not specify a local dictionary. To specify a local dictionary, use the ExecuteFile(String,EngineModule,Generic IDictionary) method overload.

Note Note

If code is to be executed more than once, it is more efficient to compile it once using the CompileFile method and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.ExecuteFile Method (String, EngineModule, Generic IDictionary)
See Also
collapseAll image DropDown image

Executes the IronPython statements in the specified file, in the scope of the specified module, using the specified local dictionary.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub ExecuteFile ( _
    fileName As String, _
    engineModule As EngineModule, _
    locals As IDictionary(Of String, Object) _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim fileName As String
Dim engineModule As EngineModule
Dim locals As IDictionary(Of String, Object)

instance.ExecuteFile(fileName, engineModule, locals)
C#
public void ExecuteFile (
    string fileName,
    EngineModule engineModule,
    IDictionary<string,Object> locals
)
C++
public:
void ExecuteFile (
    String^ fileName,
    EngineModule^ engineModule,
    IDictionary<String^, Object^>^ locals
)
J#
public void ExecuteFile (
    String fileName,
    EngineModule engineModule,
    IDictionary<String,Object> locals
)
JScript
public function ExecuteFile (
    fileName : String,
    engineModule : EngineModule,
    locals : IDictionary<String,Object>
)

Parameters

fileName

The absolute or relative path of the file that contains the code.

engineModule

The module in whose scope the code is executed.

locals

A collection that implements IDictionary for objects with string keys, which represent global variables and their values to be used when executing fileName.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | The file contains an error such as a bad operand type.
PythonSyntaxErrorException | The file contains a syntax error.
PythonNameErrorException | The file contains an unrecognized symbol.
ArgumentNullException | fileName is a null reference (Nothing in Visual Basic).
PythonSystemExitException | The file contains a call to sys.exit.

Expand image Remarks

This method throws any exceptions raised by the code in fileName.

The statements in fileName are compiled, and the compiled code is executed in the scope of engineModule. The symbols available to fileName include the global state of engineModule and any variables defined in locals.

Note Note

If code is to be executed more than once, it is more efficient to compile it once using the CompileFile method and execute it repeatedly using the IronPython.Hosting.CompiledCode.Execute method.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.ExecuteToConsole Method
See Also
CollapseAll image DropDown image

Executes a statement in the IronPython console environment.

Expand image Overload List

Name | Description
PythonEngine.ExecuteToConsole (String) | Executes the specified statement in the IronPython console environment and prints expressions to standard output.
PythonEngine.ExecuteToConsole (String, EngineModule, Generic IDictionary) | Executes the specified statement in the IronPython console environment and prints expressions to standard output, using the global dictionary of the specified module and optionally specifying a local dictionary.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.ExecuteToConsole Method (String)
See Also Example
collapseAll image DropDown image

Executes the specified statement in the IronPython console environment and prints expressions to standard output.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub ExecuteToConsole ( _
    text As String _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim text As String

instance.ExecuteToConsole(text)
C#
public void ExecuteToConsole (
    string text
)
C++
public:
void ExecuteToConsole (
    String^ text
)
J#
public void ExecuteToConsole (
    String text
)
JScript
public function ExecuteToConsole (
    text : String
)

Parameters

text

The IronPython statement to execute.

Expand image Exceptions

Exception type | Condition
PythonSyntaxErrorException | text contains more than one IronPython statement. -or- text contains a syntax error.
ArgumentTypeException | text contains an error such as a bad operand type.
PythonNameErrorException | text contains an unrecognized symbol.
PythonSystemExitException | text contains a call to sys.exit.

Expand image Remarks

Use the ExecuteToConsole method to execute a single statement or expression entered interactively by a console user. The statement or expression in text is executed in the scope of the default module. The symbols available to text include the global state of the default module and any variables defined in locals.

If text is a single expression, such as "2+2", or consists of a series of expressions, such as "2+2; 2*2", the value of the expressions is printed to standard output. This makes it easy to implement an interactive console that allows multiple expressions in a single line of input. You can use the SetStandardOutput method to specify where standard output is printed.

The statement to be executed can be complex. For example, text might be a complete for loop or a complete function definition. It must be a single statement, however. The string "print 42\nprint43" ("print 42" & vbLf & "print43" in Visual Basic) contains two statements, and therefore causes an exception.

If text contains a multi-line statement, the lines are separated by line feeds (\n or \r\n in C#, vbLf or vbCrLf in Visual Basic).

Use the SetStandardOutput method to specify where expressions are printed.

If a PythonEngine.CommandDispatcher delegate is assigned to the static PythonEngine.ConsoleCommandDispatcher property (Shared property in Visual Basic), the compiled statement is passed to the PythonEngine.CommandDispatcher delegate for execution. This allows console input to be executed on another thread, for example on the user interface thread of a Windows form.

Expand image Example

The following code example demonstrates the use of the ExecuteToConsole method in an extremely simple IronPython console implementation. The application consists of a SimpleConsole class with two principal methods:

  • A Run method that loops indefinitely, executing IronPython statements using the ExecuteToConsole method.

    The Run method handles any exceptions that occur, formats them using the FormatException method, and displays the formatted exceptions to the console.

  • A GetStatement method that allows the user to input a multi-line IronPython statement, using the ParseInteractiveInput method to parse the statement after each line.

    Note Note

    For a full explanation of the ParseInteractiveInput method, see the code example for that method.

The example code also contains a Main method that creates an instance of SimpleConsole and calls its Run method.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Text
Imports IronPython.Runtime.Exceptions
Imports IronPython.Hosting

Class SimpleConsole
    Private engine As New PythonEngine()
    Private running As Boolean = false

    Private Function Run() As Integer
        running = true
        engine.Import("site")

        While running
            Try
                ' Get user input, in the form of a complete,
                ' parseable statement.
                Dim executeThis As String = GetStatement()

                If running Then
                    If executeThis Is Nothing Then
                        Console.Write("")
                    Else
                        engine.ExecuteToConsole(executeThis)
                    End If
                End If

            Catch psee As PythonSystemExitException
                Dim nonIntegerExitCode As Object = Nothing
                Dim exitCode As Integer = _
                    psee.GetExitCode(nonIntegerExitCode)
                If nonIntegerExitCode IsNot Nothing Then
                    Console.WriteLine(nonIntegerExitCode.ToString())
                End If
                Return exitCode
            Catch ex As Exception
                ' Format the exception for display to the console.
                Console.Write(engine.FormatException(ex))
            End Try
        End While

        Return 0
    End Function

    Private Function GetStatement() As String
        Dim statement As New StringBuilder()
        Console.Write(">>>")

        While True
            Dim line As String = Console.ReadLine()

            ' If line is Nothing, the user entered F6 (Ctrl+Z)
            ' to end the session.
            If line Is Nothing Then
                Dim temp As PythonEngine.CommandDispatcher = _
                    PythonEngine.ConsoleCommandDispatcher
                If temp IsNot Nothing Then temp(Nothing)
                running = false
                Return Nothing
            End If

            ' If the user entered a blank line, then the statement
            ' is done and must be parsed as a complete statement.
            ' Otherwise, it is not done and must be parsed as an
            ' incomplete statement.

            Dim allowIncomplete As Boolean = True
            If line = "" Then allowIncomplete = False

            statement.Append(line)
            statement.Append(vbLf)

            If (statement.ToString() = vbLf) Or _
                (allowIncomplete _
                    And (statement.ToString().Trim().Length = 0)) Then

                Exit While
            Else
                ' Parse the statement as a complete statement if the
                ' user entered a blank line. Otherwise parse it as an
                ' incomplete statement. ParseInteractiveInput returns
                ' True only when a complete statement is submitted and
                ' parsed successfully. When that happens, the
                ' GetStatement method returns the parseable statement.
                '
                If engine.ParseInteractiveInput(statement.ToString(), _
                    allowIncomplete) Then

                    Return statement.ToString()
                End If

                Console.Write("...")
            End If
        End While

        Return Nothing
    End Function

    Shared Function Main() As Integer
        Dim sc As New SimpleConsole()
        Return sc.Run()
    End Function
End Class

' This code produces output similar to the following:
'
'>>>import clr
'>>>for s in clr.References:
'...  print s
'...
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'>>>clr.AddReference("NoSuchFile")
'Traceback (most recent call last):
'  File TheyPyConsole, line unknown, in Run
'  File , line 0, in <stdin>##8
'  File , line 0, in AddReference##13
'IOError: Could not add reference to assembly NoSuchFile
'>>>^Z
C# CopyCode image Copy Code
using System;
using System.Text;
using IronPython.Runtime.Exceptions;
using IronPython.Hosting;

class SimpleConsole
{
    private PythonEngine engine = new PythonEngine();
    private bool running = false;

    private int Run()
    {
        running = true;
        engine.Import("site");

        while (running)
            try
            {
                // Get user input, in the form of a complete,
                // parseable statement.
                string executeThis = GetStatement();

                if (running)
                {
                    if (executeThis == null)
                        Console.Write("");
                    else
                        engine.ExecuteToConsole(executeThis);
                }
            }
            catch (PythonSystemExitException psee)
            {
                Object nonIntegerExitCode;
                int exitCode = psee.GetExitCode(out nonIntegerExitCode);
                if (nonIntegerExitCode != null)
                    Console.WriteLine(nonIntegerExitCode.ToString());
                return exitCode;
            }
            catch (Exception ex)
            {
                //Format the exception for display to the console.
                Console.Write(engine.FormatException(ex));
            }

        return 0;
    }

    private string GetStatement()
    {
        StringBuilder statement = new StringBuilder();
        Console.Write(">>>");

        while (true)
        {
            string line = Console.ReadLine();

            // If line is Nothing, the user entered F6 (Ctrl+Z)
            // to end the session.
            if (line == null)
            {
                PythonEngine.CommandDispatcher temp =
                    PythonEngine.ConsoleCommandDispatcher;
                if (temp != null)
                    temp(null);
                running = false;
                return null;
            }

            // If the user entered a blank line, then the statement
            // is done and must be parsed as a complete statement.
            // Otherwise, it is not done and must be parsed as an
            // incomplete statement.

            bool allowIncomplete = true;
            if (line == "") { allowIncomplete = false; }

            statement.Append(line);
            statement.Append("\n");

            if ((statement.ToString() == "\n") ||
                (allowIncomplete && (statement.ToString().Trim().Length == 0)))
            {
                break;
            }
            else
            {
                // Parse the statement as a complete statement if the
                // user entered a blank line. Otherwise parse it as an
                // incomplete statement. ParseInteractiveInput returns
                // True only when a complete statement is submitted and
                // parsed successfully. When that happens, the
                // GetStatement method returns the parseable statement.
                //
                if (engine.ParseInteractiveInput(statement.ToString(),
                                                 allowIncomplete))
                {
                    return statement.ToString();
                }

                Console.Write("...");
            }
        }

        return null;
    }

    public static int Main()
    {
        SimpleConsole sc = new SimpleConsole();
        return sc.Run();
    }
}

/* This code produces output similar to the following:

>>>import clr
>>>for s in clr.References:
...  print s
...
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
>>>clr.AddReference("NoSuchFile")
Traceback (most recent call last):
  File TheyPyConsole, line unknown, in Run
  File , line 0, in <stdin>##8
  File , line 0, in AddReference##13
IOError: Could not add reference to assembly NoSuchFile
>>>^Z
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.ExecuteToConsole Method (String, EngineModule, Generic IDictionary)
See Also
collapseAll image DropDown image

Executes the specified statement in the IronPython console environment and prints expressions to standard output, using the global dictionary of the specified module and optionally specifying a local dictionary.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub ExecuteToConsole ( _
    text As String, _
    engineModule As EngineModule, _
    locals As IDictionary(Of String, Object) _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim text As String
Dim engineModule As EngineModule
Dim locals As IDictionary(Of String, Object)

instance.ExecuteToConsole(text, engineModule, locals)
C#
public void ExecuteToConsole (
    string text,
    EngineModule engineModule,
    IDictionary<string,Object> locals
)
C++
public:
void ExecuteToConsole (
    String^ text,
    EngineModule^ engineModule,
    IDictionary<String^, Object^>^ locals
)
J#
public void ExecuteToConsole (
    String text,
    EngineModule engineModule,
    IDictionary<String,Object> locals
)
JScript
public function ExecuteToConsole (
    text : String,
    engineModule : EngineModule,
    locals : IDictionary<String,Object>
)

Parameters

text

The IronPython statement to execute.

engineModule

The module in whose scope the code is executed.

locals

A Dictionary of objects with string keys, representing local variables and their values to be used when executing text.

Expand image Exceptions

Exception type | Condition
PythonSyntaxErrorException | text contains more than one IronPython statement. -or- text contains a syntax error.
ArgumentTypeException | text contains an error such as a bad operand type.
PythonNameErrorException | text contains an unrecognized symbol.
PythonSystemExitException | text contains a call to sys.exit.

Expand image Remarks

Use the ExecuteToConsole method to execute a single statement or expression entered interactively by a console user. The statement or expression in text is executed in the scope of engineModule. The symbols available to text include the global state of engineModule and any variables defined in locals.

If text is a single expression, such as "2+2", or consists of a series of expressions, such as "2+2; 2*2", the value of the expressions is printed to standard output. This makes it easy to implement an interactive console that allows multiple expressions in a single line of input. You can use the SetStandardOutput method to specify where standard output is printed.

The statement to be executed can be complex. For example, text might be a complete for loop or a complete function definition. It must be a single statement, however. The string "print 42\nprint43" ("print 42" & vbLf & "print43" in Visual Basic) contains two statements, and therefore causes an exception.

If text contains a multi-line statement, the lines are separated by line feeds (\n or \r\n in C#, vbLf or vbCrLf in Visual Basic).

Use the ParseInteractiveInput method to accumulate a complete multi-line statement from user input.

If a PythonEngine.CommandDispatcher delegate is assigned to the static PythonEngine.ConsoleCommandDispatcher property (Shared property in Visual Basic), the compiled statement is passed to the PythonEngine.CommandDispatcher delegate for execution. This allows console input to be executed on another thread, for example on the user interface thread of a Windows form.

This method throws any exceptions raised by text.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Finalize Method
See Also
collapseAll image DropDown image

Releases unmanaged resources and performs other cleanup operations before the PythonEngine is reclaimed by garbage collection.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Protected Overrides Sub Finalize
Visual Basic (Usage)
Me.Finalize
C#
~PythonEngine()
C++
!PythonEngine ()
J#
protected void finalize ()
JScript
protected override function Finalize ()

Expand image Remarks

This method overrides System.Object.Finalize. Application code should not call this method; an object's Finalize method is automatically invoked during garbage collection, unless finalization has been disabled by a call to the SuppressFinalize method.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.FormatException Method
See Also
CollapseAll image DropDown image

Formats an exception for display by the IronPython console.

Expand image Overload List

Name | Description
PythonEngine.FormatException (Exception) | Formats an exception for display by the IronPython console.
PythonEngine.FormatException (Exception, Object, PythonEngine.FilterStackFrame) | Formats an exception for display to the IronPython console. Do not use. This method probably will be made private in a future release.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.FormatException Method (Exception)
See Also Example
collapseAll image DropDown image

Formats an exception for display by the IronPython console.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function FormatException ( _
    exception As Exception _
) As String
Visual Basic (Usage)
Dim instance As PythonEngine
Dim exception As Exception
Dim returnValue As String

returnValue = instance.FormatException(exception)
C#
public string FormatException (
    Exception exception
)
C++
public:
String^ FormatException (
    Exception^ exception
)
J#
public String FormatException (
    Exception exception
)
JScript
public function FormatException (
    exception : Exception
) : String

Parameters

exception

The exception to format.

Return Value

A string representing the exception, using the standard format for displaying exceptions at the IronPython console.

Expand image Remarks

This method is only used for an interactive IronPython console.

Expand image Example

The following code example demonstrates the use of the FormatException method in an extremely simple IronPython console implementation. The application consists of a SimpleConsole class with two principal methods:

  • A Run method that loops indefinitely, executing IronPython statements using the ExecuteToConsole method and handling any exceptions that occur. The FormatException method is used to format exceptions for display to the console.

    Note Note

    To see the effect of the FormatException method, you can comment out the method call and just display ex.ToString(), or ex.Message.

  • A GetStatement method that allows the user to input a multi-line IronPython statement, using the ParseInteractiveInput method to parse the statement after each line.

    Note Note

    For a full explanation of the ParseInteractiveInput method, see the code example for that method.

The example code also contains a Main method that creates an instance of SimpleConsole and calls its Run method.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Text
Imports IronPython.Runtime.Exceptions
Imports IronPython.Hosting

Class SimpleConsole
    Private engine As New PythonEngine()
    Private running As Boolean = false

    Private Function Run() As Integer
        running = true
        engine.Import("site")

        While running
            Try
                ' Get user input, in the form of a complete,
                ' parseable statement.
                Dim executeThis As String = GetStatement()

                If running Then
                    If executeThis Is Nothing Then
                        Console.Write("")
                    Else
                        engine.ExecuteToConsole(executeThis)
                    End If
                End If

            Catch psee As PythonSystemExitException
                Dim nonIntegerExitCode As Object = Nothing
                Dim exitCode As Integer = _
                    psee.GetExitCode(nonIntegerExitCode)
                If nonIntegerExitCode IsNot Nothing Then
                    Console.WriteLine(nonIntegerExitCode.ToString())
                End If
                Return exitCode
            Catch ex As Exception
                ' Format the exception for display to the console.
                Console.Write(engine.FormatException(ex))
            End Try
        End While

        Return 0
    End Function

    Private Function GetStatement() As String
        Dim statement As New StringBuilder()
        Console.Write(">>>")

        While True
            Dim line As String = Console.ReadLine()

            ' If line is Nothing, the user entered F6 (Ctrl+Z)
            ' to end the session.
            If line Is Nothing Then
                Dim temp As PythonEngine.CommandDispatcher = _
                    PythonEngine.ConsoleCommandDispatcher
                If temp IsNot Nothing Then temp(Nothing)
                running = false
                Return Nothing
            End If

            ' If the user entered a blank line, then the statement
            ' is done and must be parsed as a complete statement.
            ' Otherwise, it is not done and must be parsed as an
            ' incomplete statement.

            Dim allowIncomplete As Boolean = True
            If line = "" Then allowIncomplete = False

            statement.Append(line)
            statement.Append(vbLf)

            If (statement.ToString() = vbLf) Or _
                (allowIncomplete _
                    And (statement.ToString().Trim().Length = 0)) Then

                Exit While
            Else
                ' Parse the statement as a complete statement if the
                ' user entered a blank line. Otherwise parse it as an
                ' incomplete statement. ParseInteractiveInput returns
                ' True only when a complete statement is submitted and
                ' parsed successfully. When that happens, the
                ' GetStatement method returns the parseable statement.
                '
                If engine.ParseInteractiveInput(statement.ToString(), _
                    allowIncomplete) Then

                    Return statement.ToString()
                End If

                Console.Write("...")
            End If
        End While

        Return Nothing
    End Function

    Shared Function Main() As Integer
        Dim sc As New SimpleConsole()
        Return sc.Run()
    End Function
End Class

' This code produces output similar to the following:
'
'>>>import clr
'>>>for s in clr.References:
'...  print s
'...
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'>>>clr.AddReference("NoSuchFile")
'Traceback (most recent call last):
'  File TheyPyConsole, line unknown, in Run
'  File , line 0, in <stdin>##8
'  File , line 0, in AddReference##13
'IOError: Could not add reference to assembly NoSuchFile
'>>>^Z
C# CopyCode image Copy Code
using System;
using System.Text;
using IronPython.Runtime.Exceptions;
using IronPython.Hosting;

class SimpleConsole
{
    private PythonEngine engine = new PythonEngine();
    private bool running = false;

    private int Run()
    {
        running = true;
        engine.Import("site");

        while (running)
            try
            {
                // Get user input, in the form of a complete,
                // parseable statement.
                string executeThis = GetStatement();

                if (running)
                {
                    if (executeThis == null)
                        Console.Write("");
                    else
                        engine.ExecuteToConsole(executeThis);
                }
            }
            catch (PythonSystemExitException psee)
            {
                Object nonIntegerExitCode;
                int exitCode = psee.GetExitCode(out nonIntegerExitCode);
                if (nonIntegerExitCode != null)
                    Console.WriteLine(nonIntegerExitCode.ToString());
                return exitCode;
            }
            catch (Exception ex)
            {
                //Format the exception for display to the console.
                Console.Write(engine.FormatException(ex));
            }

        return 0;
    }

    private string GetStatement()
    {
        StringBuilder statement = new StringBuilder();
        Console.Write(">>>");

        while (true)
        {
            string line = Console.ReadLine();

            // If line is Nothing, the user entered F6 (Ctrl+Z)
            // to end the session.
            if (line == null)
            {
                PythonEngine.CommandDispatcher temp =
                    PythonEngine.ConsoleCommandDispatcher;
                if (temp != null)
                    temp(null);
                running = false;
                return null;
            }

            // If the user entered a blank line, then the statement
            // is done and must be parsed as a complete statement.
            // Otherwise, it is not done and must be parsed as an
            // incomplete statement.

            bool allowIncomplete = true;
            if (line == "") { allowIncomplete = false; }

            statement.Append(line);
            statement.Append("\n");

            if ((statement.ToString() == "\n") ||
                (allowIncomplete && (statement.ToString().Trim().Length == 0)))
            {
                break;
            }
            else
            {
                // Parse the statement as a complete statement if the
                // user entered a blank line. Otherwise parse it as an
                // incomplete statement. ParseInteractiveInput returns
                // True only when a complete statement is submitted and
                // parsed successfully. When that happens, the
                // GetStatement method returns the parseable statement.
                //
                if (engine.ParseInteractiveInput(statement.ToString(),
                                                 allowIncomplete))
                {
                    return statement.ToString();
                }

                Console.Write("...");
            }
        }

        return null;
    }

    public static int Main()
    {
        SimpleConsole sc = new SimpleConsole();
        return sc.Run();
    }
}

/* This code produces output similar to the following:

>>>import clr
>>>for s in clr.References:
...  print s
...
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
>>>clr.AddReference("NoSuchFile")
Traceback (most recent call last):
  File TheyPyConsole, line unknown, in Run
  File , line 0, in <stdin>##8
  File , line 0, in AddReference##13
IOError: Could not add reference to assembly NoSuchFile
>>>^Z
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.FormatException Method (Exception, Object, PythonEngine.FilterStackFrame)
See Also
collapseAll image DropDown image

Formats an exception for display to the IronPython console. Do not use. This method probably will be made private in a future release.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function FormatException ( _
    exception As Exception, _
    pythonException As Object, _
    filter As FilterStackFrame _
) As String
Visual Basic (Usage)
Dim instance As PythonEngine
Dim exception As Exception
Dim pythonException As Object
Dim filter As FilterStackFrame
Dim returnValue As String

returnValue = instance.FormatException(exception, pythonException, filter)
C#
public string FormatException (
    Exception exception,
    Object pythonException,
    FilterStackFrame filter
)
C++
public:
String^ FormatException (
    Exception^ exception,
    Object^ pythonException,
    FilterStackFrame^ filter
)
J#
public String FormatException (
    Exception exception,
    Object pythonException,
    FilterStackFrame filter
)
JScript
public function FormatException (
    exception : Exception,
    pythonException : Object,
    filter : FilterStackFrame
) : String

Parameters

exception

A common language runtime exception whose filtered stack trace is to be included.

pythonException

An IronPython exception object that is to be included.

filter

A PythonEngine.FilterStackFrame delegate representing a method that filters stack frames for inclusion in the formatted stack trace.

Return Value

A formatted string containing exception information, suitable for display at the interactive console.

Expand image Exceptions

Exception type | Condition
NullReferenceException | exception is a null reference (Nothing in Visual Basic).

Expand image Remarks

Do not use. This method probably will be made private in a future release.

If common language runtime (CLR) debugging is enabled, the CLR exception supplied for exception is also included. Otherwise it is omitted. CLR debugging is enabled by specifying true for the ClrDebuggingEnabled property when the PythonEngine is created.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Import Method
See Also Example
collapseAll image DropDown image

Imports a module into the global dictionary of the default module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Import ( _
    moduleName As String _
) As Object
Visual Basic (Usage)
Dim instance As PythonEngine
Dim moduleName As String
Dim returnValue As Object

returnValue = instance.Import(moduleName)
C#
public Object Import (
    string moduleName
)
C++
public:
Object^ Import (
    String^ moduleName
)
J#
public Object Import (
    String moduleName
)
JScript
public function Import (
    moduleName : String
) : Object

Parameters

moduleName

The name of the module to import. For example, "System.Threading" imports that namespace as "Threading".

Return Value

A reference to the imported module.

Expand image Remarks

This method is provided as a convenient way to import modules into the default module. To import modules into other instances of EngineModule, use the EngineModule.Import method.

Use the Import method, specifying "clr" for moduleName, to import ClrModule into the default module when you create a PythonEngine. The host can cache the reference, and use the methods of ClrModule to load assemblies and make them available for import.

Note Note

It is sufficient to cache ClrModule once for any given PythonEngine instance. The same ClrModule instance is used for every EngineModule that imports "clr" and is created with that PythonEngine instance.

When a namespace from the .NET Framework is imported, the name used in the global symbol table is the last segment of the namespace name. Thus, "System.Collections.Generic" is imported as "Generic".

The IronPython import statement throws an ImportError if the module is not found. However, the Import method does not throw an exception if the module is not found. This might change in a future release. See the issue discussed here.

Expand image Example

The following code example shows one way to start a host application, initialize the IronPython execution engine, import and cache ClrModule, and provide the default module with access to the public API of the host application.

When the host application is started, the Initialize method creates an instance of PythonEngine and uses the Import method to import ClrModule into the default module. The return value is cached, to that the host has a reference to ClrModule.

The Globals property is used to store a reference to the running instance of the application as a global variable in the default module, allowing IronPython code in the default module to access the public API of the host.

To demonstrate these capabilities, the Run method does the following:

  • Executes IronPython code that calls the host application's public Greeting method.

  • Uses the host's cached reference to ClrModule to add a reference to System.Windows.Forms.dll, then executes IronPython code that shows a message box and retrieves the return value.

  • Executes IronPython code that uses ClrModule.References to display the list of assemblies that are loaded and referenced.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports IronPython.Modules

Class MyApplication

    Private engine As PythonEngine
    Private clr As ClrModule

    Private Sub Initialize()

        engine = New PythonEngine()

        ' Import ClrModule, and make it available to the host
        ' application.
        clr = engine.Import("clr")

        ' Make the running instance of the application available
        ' to the default module.
        engine.Globals.Add("MyApplication", Me)

    End Sub

    Shared Sub Main()

        Dim instance As New MyApplication()
        instance.Initialize()
        instance.Run()

    End Sub

    Private Sub Run()

        Console.WriteLine("IronPython code accesses the host API:")
        Dim statements As String = _
            "x = 'Hello'" & vbLf & _
            "MyApplication.Greeting(x)"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "Host code accesses ClrModule:")
        clr.AddReferenceByPartialName("System.Windows.Forms")
        statements = _
            "from System.Windows.Forms import *" & vbLf & _
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)" & vbLf & _
            "print 'You clicked:', result"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "IronPython code accesses clr:")
        statements = _
            "for s in clr.References:" & vbLf & _
            "  print s"
        engine.Execute(statements)
    End Sub

    Public Sub Greeting(ByVal message As String)
        Console.WriteLine("{0} from the host!", message)
    End Sub
End Class

' This code produces output similar to the following:
'
'IronPython code accesses the host API:
'Hello from the host!
'
'Host code accesses ClrModule:
'You clicked: No
'
'IronPython code accesses clr:
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using IronPython.Modules;

class MyApplication
{
    private PythonEngine engine;
    private ClrModule clr;

    private void Initialize()
    {
        engine = new PythonEngine();

        // Import ClrModule, and make it available to the host
        // application.
        clr = (ClrModule) engine.Import("clr");

        // Make the running instance of the application available
        // to the default module.
        engine.Globals.Add("MyApplication", this);
    }

    public static void Main()
    {
        MyApplication instance = new MyApplication();
        instance.Initialize();
        instance.Run();
    }

    private void Run()
    {
        Console.WriteLine("IronPython code accesses the host API:");
        string statements =
            "x = 'Hello'\n" +
            "MyApplication.Greeting(x)";
        engine.Execute(statements);

        Console.WriteLine("\nHost code accesses ClrModule:");
        clr.AddReferenceByPartialName("System.Windows.Forms");
        statements =
            "from System.Windows.Forms import *\n" +
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)\n" +
            "print 'You clicked:', result";
        engine.Execute(statements);

        Console.WriteLine("\nIronPython code accesses clr:");
        statements =
            "for s in clr.References:\n" +
            "  print s";
        engine.Execute(statements);
    }

    public void Greeting(string message)
    {
        Console.WriteLine("{0} from the host!", message);
    }
}

/* This code produces output similar to the following:

IronPython code accesses the host API:
Hello from the host!

Host code accesses ClrModule:
You clicked: No

IronPython code accesses clr:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.InitializeModules Method
See Also
collapseAll image DropDown image

Sets system state for a new PythonEngine.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub InitializeModules ( _
    prefix As String, _
    executable As String, _
    version As String _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim prefix As String
Dim executable As String
Dim version As String

instance.InitializeModules(prefix, executable, version)
C#
public void InitializeModules (
    string prefix,
    string executable,
    string version
)
C++
public:
void InitializeModules (
    String^ prefix,
    String^ executable,
    String^ version
)
J#
public void InitializeModules (
    String prefix,
    String executable,
    String version
)
JScript
public function InitializeModules (
    prefix : String,
    executable : String,
    version : String
)

Parameters

prefix

The directory path of the host application.

executable

The path and filename of the host application.

version

A string representing the version of IronPython.

Expand image Remarks

Version information is automatically set when a new PythonEngine is created. To retain it when you call this method, specify the value returned by the version property of the Sys object for version.

This method sets sys.prefix, sys.exec_prefix, sys.executable, and sys.version. The value specified for prefix is used for sys.prefix and sys.exec_prefix.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.LoadAssembly Method
See Also
collapseAll image DropDown image

Do not use. Use the AddReference method instead.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub LoadAssembly ( _
    assembly As Assembly _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim assembly As Assembly

instance.LoadAssembly(assembly)
C#
public void LoadAssembly (
    Assembly assembly
)
C++
public:
void LoadAssembly (
    Assembly^ assembly
)
J#
public void LoadAssembly (
    Assembly assembly
)
JScript
public function LoadAssembly (
    assembly : Assembly
)

Parameters

assembly

An Assembly object.

Expand image Remarks

To add a reference to a loaded assembly, use the ClrModule.AddReference method.

To load an assembly without adding a reference, use one of the following methods of ClrModule: LoadAssemblyByName, LoadAssemblyByPartialName, LoadAssemblyFromFile, or LoadAssemblyFromFileWithPath.

To load an assembly and add a reference, use one of the following methods of ClrModule: AddReference, AddReferenceByName, AddReferenceByPartialName, AddReferenceToFile, or AddReferenceToFileAndPath.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.ParseInteractiveInput Method
See Also Example
collapseAll image DropDown image

Determines whether the specified string represents a valid statement. The specified Boolean value determines whether the statement is treated as incomplete or complete.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function ParseInteractiveInput ( _
    text As String, _
    allowIncompleteStatement As Boolean _
) As Boolean
Visual Basic (Usage)
Dim instance As PythonEngine
Dim text As String
Dim allowIncompleteStatement As Boolean
Dim returnValue As Boolean

returnValue = instance.ParseInteractiveInput(text, allowIncompleteStatement)
C#
public bool ParseInteractiveInput (
    string text,
    bool allowIncompleteStatement
)
C++
public:
bool ParseInteractiveInput (
    String^ text,
    bool allowIncompleteStatement
)
J#
public boolean ParseInteractiveInput (
    String text,
    boolean allowIncompleteStatement
)
JScript
public function ParseInteractiveInput (
    text : String,
    allowIncompleteStatement : boolean
) : boolean

Parameters

text

A string containing the accumulated lines of IronPython code in the statement suite that is currently under construction. The lines are separated by line feeds.

allowIncompleteStatement

true if text should be parsed as an incomplete statement suite; otherwise false.

Return Value

true if allowIncompleteStatement is false and the line is parsed successfully; otherwise false.

Expand image Exceptions

Exception type | Condition
PythonSyntaxErrorException | A syntax error was detected in the statement.

Expand image Remarks

The ParseInteractiveInput method is used to build multi-line statement suites, and thus provides a very elementary language service. To use it, follow these steps:

  • Start with an empty statement.

  • Obtain a line of code.

  • If the line is not blank:

    • Concatenate it to the statement. Use line feeds as separators.

    • Pass the statement to the ParseInteractiveInput method, and specify true for allowIncompleteStatement. This allows the statement to be parsed even if it is, for example, only the first line of a function definition. If a syntax error occurs, ParseInteractiveInput throws PythonSyntaxErrorException and the statement should be discarded. The user should be prompted to input additional code. Otherwise it returns false, indicating that the input is a valid statement suite. However, the user might still wish to add more statements to the statement suite.

    • If no exception was thrown, obtain another line of code.

  • If the line of code is blank, or if some other input terminator is detected:

    • Pass the statement, which is presumably complete, to the ParseInteractiveInput method, and specify false for allowIncompleteStatement. If a syntax error occurs, ParseInteractiveInput throws PythonSyntaxErrorException. Otherwise, it returns true. At this point, the input is a complete statement suite that should be processed.

    • If no exception was thrown, execute the completed statement.

Expand image Example

The following code example demonstrates the use of the ParseInteractiveInput method in an extremely simple IronPython console implementation. The application consists of a SimpleConsole class with two principal methods:

  • A Run method that loops indefinitely, executing IronPython statements using the ExecuteToConsole method and handling any exceptions that occur. The FormatException method is used to format exceptions for display to the console.

  • A GetStatement method that allows the user to input a multi-line IronPython statement. As long as the user keeps entering lines of code that are not blank, the GetStatement method keeps prompting for more lines. Each line of code is concatenated to a StringBuilder that holds the statement currently being constructed.

    The statement is passed to the ParseInteractiveInput method, along with a Boolean value that indicates whether the statement should be parsed as a complete or incomplete statement. As long as the statement is incomplete, the value true is passed.

    The user signals that a statement is complete by entering a blank line, which causes the program to pass the completed statement and false to the ParseInteractiveInput method. If the statement parses, the ParseInteractiveInput method returns true, and the GetStatement method returns the completed statement.

    Note Note

    When the ParseInteractiveInput method throws PythonSyntaxErrorException, the GetStatement method does not catch the exception. Instead, the exception is allowed to terminate the method, discarding the incomplete statement.

The example code also contains a Main method that creates an instance of SimpleConsole and calls its Run method.

Visual Basic CopyCode image Copy Code
Imports System
Imports System.Text
Imports IronPython.Runtime.Exceptions
Imports IronPython.Hosting

Class SimpleConsole
    Private engine As New PythonEngine()
    Private running As Boolean = false

    Private Function Run() As Integer
        running = true
        engine.Import("site")

        While running
            Try
                ' Get user input, in the form of a complete,
                ' parseable statement.
                Dim executeThis As String = GetStatement()

                If running Then
                    If executeThis Is Nothing Then
                        Console.Write("")
                    Else
                        engine.ExecuteToConsole(executeThis)
                    End If
                End If

            Catch psee As PythonSystemExitException
                Dim nonIntegerExitCode As Object = Nothing
                Dim exitCode As Integer = _
                    psee.GetExitCode(nonIntegerExitCode)
                If nonIntegerExitCode IsNot Nothing Then
                    Console.WriteLine(nonIntegerExitCode.ToString())
                End If
                Return exitCode
            Catch ex As Exception
                ' Format the exception for display to the console.
                Console.Write(engine.FormatException(ex))
            End Try
        End While

        Return 0
    End Function

    Private Function GetStatement() As String
        Dim statement As New StringBuilder()
        Console.Write(">>>")

        While True
            Dim line As String = Console.ReadLine()

            ' If line is Nothing, the user entered F6 (Ctrl+Z)
            ' to end the session.
            If line Is Nothing Then
                Dim temp As PythonEngine.CommandDispatcher = _
                    PythonEngine.ConsoleCommandDispatcher
                If temp IsNot Nothing Then temp(Nothing)
                running = false
                Return Nothing
            End If

            ' If the user entered a blank line, then the statement
            ' is done and must be parsed as a complete statement.
            ' Otherwise, it is not done and must be parsed as an
            ' incomplete statement.

            Dim allowIncomplete As Boolean = True
            If line = "" Then allowIncomplete = False

            statement.Append(line)
            statement.Append(vbLf)

            If (statement.ToString() = vbLf) Or _
                (allowIncomplete _
                    And (statement.ToString().Trim().Length = 0)) Then

                Exit While
            Else
                ' Parse the statement as a complete statement if the
                ' user entered a blank line. Otherwise parse it as an
                ' incomplete statement. ParseInteractiveInput returns
                ' True only when a complete statement is submitted and
                ' parsed successfully. When that happens, the
                ' GetStatement method returns the parseable statement.
                '
                If engine.ParseInteractiveInput(statement.ToString(), _
                    allowIncomplete) Then

                    Return statement.ToString()
                End If

                Console.Write("...")
            End If
        End While

        Return Nothing
    End Function

    Shared Function Main() As Integer
        Dim sc As New SimpleConsole()
        Return sc.Run()
    End Function
End Class

' This code produces output similar to the following:
'
'>>>import clr
'>>>for s in clr.References:
'...  print s
'...
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'>>>clr.AddReference("NoSuchFile")
'Traceback (most recent call last):
'  File TheyPyConsole, line unknown, in Run
'  File , line 0, in <stdin>##8
'  File , line 0, in AddReference##13
'IOError: Could not add reference to assembly NoSuchFile
'>>>^Z
C# CopyCode image Copy Code
using System;
using System.Text;
using IronPython.Runtime.Exceptions;
using IronPython.Hosting;

class SimpleConsole
{
    private PythonEngine engine = new PythonEngine();
    private bool running = false;

    private int Run()
    {
        running = true;
        engine.Import("site");

        while (running)
            try
            {
                // Get user input, in the form of a complete,
                // parseable statement.
                string executeThis = GetStatement();

                if (running)
                {
                    if (executeThis == null)
                        Console.Write("");
                    else
                        engine.ExecuteToConsole(executeThis);
                }
            }
            catch (PythonSystemExitException psee)
            {
                Object nonIntegerExitCode;
                int exitCode = psee.GetExitCode(out nonIntegerExitCode);
                if (nonIntegerExitCode != null)
                    Console.WriteLine(nonIntegerExitCode.ToString());
                return exitCode;
            }
            catch (Exception ex)
            {
                //Format the exception for display to the console.
                Console.Write(engine.FormatException(ex));
            }

        return 0;
    }

    private string GetStatement()
    {
        StringBuilder statement = new StringBuilder();
        Console.Write(">>>");

        while (true)
        {
            string line = Console.ReadLine();

            // If line is Nothing, the user entered F6 (Ctrl+Z)
            // to end the session.
            if (line == null)
            {
                PythonEngine.CommandDispatcher temp =
                    PythonEngine.ConsoleCommandDispatcher;
                if (temp != null)
                    temp(null);
                running = false;
                return null;
            }

            // If the user entered a blank line, then the statement
            // is done and must be parsed as a complete statement.
            // Otherwise, it is not done and must be parsed as an
            // incomplete statement.

            bool allowIncomplete = true;
            if (line == "") { allowIncomplete = false; }

            statement.Append(line);
            statement.Append("\n");

            if ((statement.ToString() == "\n") ||
                (allowIncomplete && (statement.ToString().Trim().Length == 0)))
            {
                break;
            }
            else
            {
                // Parse the statement as a complete statement if the
                // user entered a blank line. Otherwise parse it as an
                // incomplete statement. ParseInteractiveInput returns
                // True only when a complete statement is submitted and
                // parsed successfully. When that happens, the
                // GetStatement method returns the parseable statement.
                //
                if (engine.ParseInteractiveInput(statement.ToString(),
                                                 allowIncomplete))
                {
                    return statement.ToString();
                }

                Console.Write("...");
            }
        }

        return null;
    }

    public static int Main()
    {
        SimpleConsole sc = new SimpleConsole();
        return sc.Run();
    }
}

/* This code produces output similar to the following:

>>>import clr
>>>for s in clr.References:
...  print s
...
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
>>>clr.AddReference("NoSuchFile")
Traceback (most recent call last):
  File TheyPyConsole, line unknown, in Run
  File , line 0, in <stdin>##8
  File , line 0, in AddReference##13
IOError: Could not add reference to assembly NoSuchFile
>>>^Z
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.SetStandardError Method
See Also
collapseAll image DropDown image

Redirects console error messages to the specified stream.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub SetStandardError ( _
    stream As Stream _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim stream As Stream

instance.SetStandardError(stream)
C#
public void SetStandardError (
    Stream stream
)
C++
public:
void SetStandardError (
    Stream^ stream
)
J#
public void SetStandardError (
    Stream stream
)
JScript
public function SetStandardError (
    stream : Stream
)

Parameters

stream

The stream to which console error messages are to be directed.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.SetStandardInput Method
See Also
collapseAll image DropDown image

Specifies a stream from which standard console input is to be obtained.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub SetStandardInput ( _
    stream As Stream _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim stream As Stream

instance.SetStandardInput(stream)
C#
public void SetStandardInput (
    Stream stream
)
C++
public:
void SetStandardInput (
    Stream^ stream
)
J#
public void SetStandardInput (
    Stream stream
)
JScript
public function SetStandardInput (
    stream : Stream
)

Parameters

stream

The stream from which console input is to be obtained.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.SetStandardOutput Method
See Also
collapseAll image DropDown image

Redirects standard console output to the specified stream.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub SetStandardOutput ( _
    stream As Stream _
)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim stream As Stream

instance.SetStandardOutput(stream)
C#
public void SetStandardOutput (
    Stream stream
)
C++
public:
void SetStandardOutput (
    Stream^ stream
)
J#
public void SetStandardOutput (
    Stream stream
)
JScript
public function SetStandardOutput (
    stream : Stream
)

Parameters

stream

The stream to which standard output is directed.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Shutdown Method
See Also
collapseAll image DropDown image

Shuts down this instance of the engine.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Shutdown
Visual Basic (Usage)
Dim instance As PythonEngine

instance.Shutdown
C#
public void Shutdown ()
C++
public:
void Shutdown ()
J#
public void Shutdown ()
JScript
public function Shutdown ()

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine Properties
See Also
CollapseAll image DropDown image

Expand image Public Properties

 | Name | Description
 | ConsoleCommandDispatcher | Gets or sets a delegate that allows custom actions to be performed for the execution of each console statement. This can include executing the code on another thread for improved interactive scenarios, custom pre- and post-execution events, or other host-controlled changes to the way console code is executed.
Public property | DefaultModule | Gets the default module for this engine.
Public property | Globals | Gets the dictionary of global variables for the default module.
Public property | Sys | Gets the IronPython sys module.
 | Version | Gets a structure representing the assembly version of IronPython.dll.
 | VersionString | Gets a string that contains IronPython version information.
Top

Expand image See Also

Reference

PythonEngine Class


PythonEngine.ConsoleCommandDispatcher Property
See Also
CollapseAll image DropDown image

Gets or sets a delegate that allows custom actions to be performed for the execution of each console statement. This can include executing the code on another thread for improved interactive scenarios, custom pre- and post-execution events, or other host-controlled changes to the way console code is executed.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Shared Property ConsoleCommandDispatcher As CommandDispatcher
Visual Basic (Usage)
Dim value As CommandDispatcher

value = PythonEngine.ConsoleCommandDispatcher

PythonEngine.ConsoleCommandDispatcher = value
C#
public static CommandDispatcher ConsoleCommandDispatcher { get; set; }
C++
public:
static property CommandDispatcher^ ConsoleCommandDispatcher {
    CommandDispatcher^ get ();
    void set (CommandDispatcher^ value);
}
J#
/** @property */
public static CommandDispatcher get_ConsoleCommandDispatcher ()

/** @property */
public static void set_ConsoleCommandDispatcher (CommandDispatcher value)
JScript
public static function get ConsoleCommandDispatcher () : CommandDispatcher

public static function set ConsoleCommandDispatcher (value : CommandDispatcher)

Property Value

A delegate that executes compiled IronPython console input on a different thread than the one on which the console is executing.

Expand image Remarks

Setting this property allows IronPython console commands to be intercepted each time a command is executed. A common use of this is to allow to interaction with .NET Framework classes that have to run on their own threads. For example, Windows forms and controls have to run on their own thread in order for their message loops to work properly. Otherwise, their message loops would be blocked while the console is waiting for user input.

Assigning a delegate to the static (Shared in Visual Basic) ConsoleCommandDispatcher property causes all IronPython console input to be executed using the delegate. When the IronPython console is ready to execute compiled user input, it wraps the compiled input in a delegate and passes that delegate to the ConsoleCommandDispatcher delegate currently assigned to this property. If the ConsoleCommandDispatcher property is a null reference (Nothing in Visual Basic), console input is executed normally.

In the case of Windows forms, the method represented by the ConsoleCommandDispatcher delegate simply invokes the delegate that represents the compiled commands, using the Invoke method. The Invoke method marshals the call to the thread on which the Windows forms are executing.

The IronPython tutorial includes a winforms.py module that demonstrates the use of this property to interact with Windows forms, and an avalon.py module for interacting with Windows Presentation Foundation classes.

Setting this property has no effect on IronPython code executed by the host through methods such as Evaluate, Execute, CreateMethod, and CreateLambda.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.DefaultModule Property
See Also
CollapseAll image DropDown image

Gets the default module for this engine.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Property DefaultModule As EngineModule
Visual Basic (Usage)
Dim instance As PythonEngine
Dim value As EngineModule

value = instance.DefaultModule

instance.DefaultModule = value
C#
public EngineModule DefaultModule { get; set; }
C++
public:
property EngineModule^ DefaultModule {
    EngineModule^ get ();
    void set (EngineModule^ value);
}
J#
/** @property */
public EngineModule get_DefaultModule ()

/** @property */
public void set_DefaultModule (EngineModule value)
JScript
public function get DefaultModule () : EngineModule

public function set DefaultModule (value : EngineModule)

Property Value

An EngineModule representing the default module.

Expand image Remarks

Every PythonEngine has a default module. The default module is just an instance of EngineModule, but PythonEngine provides convenience methods that simplify its use. For example, any overloads of the Execute and Evaluate methods that do not specify a module execute code in the default module. This is functionally equivalent to calling the overloads that do take an EngineModule as an argument, and passing DefaultModule as the value for that argument.

To create additional modules for executing code, use the CreateModule method.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Globals Property
See Also Example
CollapseAll image DropDown image

Gets the dictionary of global variables for the default module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public ReadOnly Property Globals As IDictionary(Of String, Object)
Visual Basic (Usage)
Dim instance As PythonEngine
Dim value As IDictionary(Of String, Object)

value = instance.Globals
C#
public IDictionary<string,Object> Globals { get; }
C++
public:
property IDictionary<String^, Object^>^ Globals {
    IDictionary<String^, Object^>^ get ();
}
J#
/** @property */
public IDictionary<String,Object> get_Globals ()
JScript
public function get Globals () : IDictionary<String,Object>

Property Value

A Dictionary of objects with string keys, (Dictionary<string,object> in C#, Dictionary(Of String, Object) in Visual Basic) representing the global variables of the default module and their values.

Expand image Remarks

You can add, remove, and change global variables for the default module by using the methods of the Dictionary. This has the same effect as adding, deleting, and changing the global variables using IronPython code.

To access the global variables of other modules, use the EngineModule.Globals property. To assign global variables when creating a module, use the CreateModule(String,Generic IDictionary,Boolean) method overload.

Expand image Example

The following code example shows one way to start a host application, initialize the IronPython execution engine, import and cache ClrModule, and provide the default module with access to the public API of the host application.

When the host application is started, the Initialize method creates an instance of PythonEngine and uses the Import method to import ClrModule into the default module. The return value is cached, to that the host has a reference to ClrModule.

The Globals property is used to store a reference to the running instance of the application as a global variable in the default module, allowing IronPython code in the default module to access the public API of the host.

To demonstrate these capabilities, the Run method does the following:

  • Executes IronPython code that calls the host application's public Greeting method.

  • Uses the host's cached reference to ClrModule to add a reference to System.Windows.Forms.dll, then executes IronPython code that shows a message box and retrieves the return value.

  • Executes IronPython code that uses ClrModule.References to display the list of assemblies that are loaded and referenced.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports IronPython.Modules

Class MyApplication

    Private engine As PythonEngine
    Private clr As ClrModule

    Private Sub Initialize()

        engine = New PythonEngine()

        ' Import ClrModule, and make it available to the host
        ' application.
        clr = engine.Import("clr")

        ' Make the running instance of the application available
        ' to the default module.
        engine.Globals.Add("MyApplication", Me)

    End Sub

    Shared Sub Main()

        Dim instance As New MyApplication()
        instance.Initialize()
        instance.Run()

    End Sub

    Private Sub Run()

        Console.WriteLine("IronPython code accesses the host API:")
        Dim statements As String = _
            "x = 'Hello'" & vbLf & _
            "MyApplication.Greeting(x)"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "Host code accesses ClrModule:")
        clr.AddReferenceByPartialName("System.Windows.Forms")
        statements = _
            "from System.Windows.Forms import *" & vbLf & _
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)" & vbLf & _
            "print 'You clicked:', result"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "IronPython code accesses clr:")
        statements = _
            "for s in clr.References:" & vbLf & _
            "  print s"
        engine.Execute(statements)
    End Sub

    Public Sub Greeting(ByVal message As String)
        Console.WriteLine("{0} from the host!", message)
    End Sub
End Class

' This code produces output similar to the following:
'
'IronPython code accesses the host API:
'Hello from the host!
'
'Host code accesses ClrModule:
'You clicked: No
'
'IronPython code accesses clr:
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using IronPython.Modules;

class MyApplication
{
    private PythonEngine engine;
    private ClrModule clr;

    private void Initialize()
    {
        engine = new PythonEngine();

        // Import ClrModule, and make it available to the host
        // application.
        clr = (ClrModule) engine.Import("clr");

        // Make the running instance of the application available
        // to the default module.
        engine.Globals.Add("MyApplication", this);
    }

    public static void Main()
    {
        MyApplication instance = new MyApplication();
        instance.Initialize();
        instance.Run();
    }

    private void Run()
    {
        Console.WriteLine("IronPython code accesses the host API:");
        string statements =
            "x = 'Hello'\n" +
            "MyApplication.Greeting(x)";
        engine.Execute(statements);

        Console.WriteLine("\nHost code accesses ClrModule:");
        clr.AddReferenceByPartialName("System.Windows.Forms");
        statements =
            "from System.Windows.Forms import *\n" +
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)\n" +
            "print 'You clicked:', result";
        engine.Execute(statements);

        Console.WriteLine("\nIronPython code accesses clr:");
        statements =
            "for s in clr.References:\n" +
            "  print s";
        engine.Execute(statements);
    }

    public void Greeting(string message)
    {
        Console.WriteLine("{0} from the host!", message);
    }
}

/* This code produces output similar to the following:

IronPython code accesses the host API:
Hello from the host!

Host code accesses ClrModule:
You clicked: No

IronPython code accesses clr:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
 */

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Sys Property
See Also
CollapseAll image DropDown image

Gets the IronPython sys module.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public ReadOnly Property Sys As SystemState
Visual Basic (Usage)
Dim instance As PythonEngine
Dim value As SystemState

value = instance.Sys
C#
public SystemState Sys { get; }
C++
public:
property SystemState^ Sys {
    SystemState^ get ();
}
J#
/** @property */
public SystemState get_Sys ()
JScript
public function get Sys () : SystemState

Property Value

An object that represents the IronPython sys module.

Expand image Remarks

The sys module is always available to the host application, even if it has not been imported into the scope of any module.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.Version Property
See Also
CollapseAll image DropDown image

Gets a structure representing the assembly version of IronPython.dll.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Shared ReadOnly Property Version As Version
Visual Basic (Usage)
Dim value As Version

value = PythonEngine.Version
C#
public static Version Version { get; }
C++
public:
static property Version^ Version {
    Version^ get ();
}
J#
/** @property */
public static Version get_Version ()
JScript
public static function get Version () : Version

Property Value

A Version structure representing the version of the assembly "IronPython.dll".

Expand image Remarks

Use the VersionString property to get a string representation that includes the .NET Framework version.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.VersionString Property
See Also
CollapseAll image DropDown image

Gets a string that contains IronPython version information.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Shared ReadOnly Property VersionString As String
Visual Basic (Usage)
Dim value As String

value = PythonEngine.VersionString
C#
public static string VersionString { get; }
C++
public:
static property String^ VersionString {
    String^ get ();
}
J#
/** @property */
public static String get_VersionString ()
JScript
public static function get VersionString () : String

Property Value

A formatted string containing human-readable version information for IronPython and for the .NET Framework.

Expand image Remarks

The IronPython version information in the string includes the Major, Minor, and Build fields of the Version structure returned by the Version property.

Expand image See Also

Reference

PythonEngine Class
PythonEngine Members


PythonEngine.CommandDispatcher Delegate
See Also
CollapseAll image DropDown image

Represents a method that executes compiled IronPython statements, and optionally performs custom actions that affect the way the compiled statements are executed.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Delegate Sub CommandDispatcher ( _
    consoleCommand As Delegate _
)
Visual Basic (Usage)
Dim instance As New CommandDispatcher(AddressOf HandlerMethod)
C#
public delegate void CommandDispatcher (
    Delegate consoleCommand
)
C++
public delegate void CommandDispatcher (
    Delegate^ consoleCommand
)
J#
/** @delegate */
public delegate void CommandDispatcher (
    Delegate consoleCommand
)
JScript
JScript supports the use of delegates, but not the declaration of new ones.

Parameters

consoleCommand

A Delegate that represents compiled IronPython statements, for execution on another thread.

Expand image Remarks

When an instance of the PythonEngine.CommandDispatcher delegate is assigned to the static ConsoleCommandDispatcher property, it is called whenever there is compiled input from the IronPython console that is ready for execution. The compiled input is in the form of a delegate, consoleCommand. The method represented by PythonEngine.CommandDispatcher can execute custom actions before and/or after invoking consoleCommand.

A common use of PythonEngine.CommandDispatcher is to allow to interaction with .NET Framework classes that have to run on their own threads, such as Windows forms. For example, consoleCommand can be invoked on the thread used by a Windows form, using the System.Windows.Forms.Control.Invoke(System.Delegate) method. This is necessary for interacting with Windows forms from the IronPython console, because whenever the console is waiting for user input it blocks the message loop of the form.

You can find examples of the use of the PythonEngine.CommandDispatcher delegate in the winforms.py and avalon.py modules, in the IronPython tutorial.

Expand image See Also

Reference


PythonEngine.FilterStackFrame Delegate
See Also
CollapseAll image DropDown image

Represents a method that determines whether the specified stack frame is included in a stack trace.

Namespace: IronPython.Hosting
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Delegate Function FilterStackFrame ( _
    frame As StackFrame _
) As Boolean
Visual Basic (Usage)
Dim instance As New FilterStackFrame(AddressOf HandlerMethod)
C#
public delegate bool FilterStackFrame (
    StackFrame frame
)
C++
public delegate bool FilterStackFrame (
    StackFrame^ frame
)
J#
/** @delegate */
public delegate boolean FilterStackFrame (
    StackFrame frame
)
JScript
JScript supports the use of delegates, but not the declaration of new ones.

Parameters

frame

The stack frame to be filtered.

Return Value

true to include the stack frame in the stack trace; otherwise false.

Expand image Remarks

The method represented by this delegate determines whether the specified stack frame is relevant to a particular debugging task. The delegate is typically invoked once for each stack frame in the call stack. The method that the PythonEngine.FilterStackFrame delegate represents examines the information in the specified frame, such as method that was called, the name of the assembly the method comes from, and so on, and returns true if the stack frame is of interest. For example, it is not particularly useful for an IronPython console error message to include stack frames for .NET Framework methods that are implementation details of the IronPython hosting API or console.

Expand image See Also

Reference


IronPython.Modules Namespace
CollapseAll image
The IronPython.Modules namespace provides host applications with access to the ClrModule class, which supports interoperation between IronPython and the common language runtime (CLR). A host application uses ClrModule to load assemblies and make their objects available to IronPython sessions. Importing ClrModule provides access to the most commonly-used assemblies in the .NET Framework.

Expand image Classes

 | Class | Description
Public class | ClrModule | Supports interoperation between IronPython and the common language runtime.
Public class | ClrModule.Reference | Represents a ref or out parameter (ByRef or OutAttribute parameter in Visual Basic) when a common language runtime method is called from IronPython code.
To make a suggestion or report a bug about Help or another feature of this product, go to the feedback site.


ClrModule Class
See Also Example Members
CollapseAll image DropDown image

Supports interoperation between IronPython and the common language runtime.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Class ClrModule
    Implements IDisposable
Visual Basic (Usage)
Dim instance As ClrModule
C#
public class ClrModule : IDisposable
C++
public ref class ClrModule : IDisposable
J#
public class ClrModule implements IDisposable
JScript
public class ClrModule implements IDisposable

Expand image Remarks

The ClrModule class can be used from a host application or from the IronPython console. From the console, type import clr to provide access to the module. From an instance of PythonEngine, use the Import method with the string "clr".

IronPython automatically loads the most commonly-used assemblies from the .NET Framework, and creates references to them. The References field contains an array of assemblies for which references have been created. You can use ClrModule to load additional assemblies and add them to the list of references.

Note Note

Because namespaces can span assemblies, you might need to load additional assemblies in order to access all the types in some namespaces.

To load an assembly without making its contents available for import, use the LoadAssemblyByName, LoadAssemblyByPartialName, LoadAssemblyFromFile, and LoadAssemblyFromFileWithPath methods. To make the contents of the loaded assembly available for import, use the AddReference method.

To load one or more assemblies and make their contents available for import, use the AddReference, AddReferenceByName, AddReferenceByPartialName, AddReferenceToFile, and AddReferenceToFileAndPath methods.

To switch between the IronPython type system and the common language runtime type system, use the GetClrType and GetPythonType methods.

Expand image Example

The following code shows the use of ClrModule in a console application that hosts IronPython. The application creates a PythonEngine and imports ClrModule into the default module of the engine. The host application caches the ClrModule and uses it to add a reference to an assembly. The references are then listed, first from the host and then by executing code in IronPython. Finally, a class is imported from the assembly, and the contents of the class dictionary are listed.

To run this code you must create a .dll assembly with the display name shown in the AddReference method call. The assembly must contain a type named TestClass.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports IronPython.Modules

Public Class Example

    Private engine As New PythonEngine()
    Private clr As ClrModule

    Friend Shared Sub Main()

        Dim e As New Example()
        e.Run()

    End Sub

    Private Sub Run()

        ' Import and cache the clr module.
        clr = engine.Import("clr")

        ' Load an assembly and make it available for import by adding
        ' it to References.
        clr.AddReference("MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")

        Console.WriteLine("List references from the host:")
        For Each obj As Object In clr.References
            Console.WriteLine(obj.ToString())
        Next

        engine.Execute("print" & vbCrLf _
            & "print ""List references from IronPython:""" & vbCrLf _
            & "for s in clr.References: print s")

        Console.WriteLine(vbCrLf & "Import TestClass from MyAssembly and show its contents:")
        engine.Import("TestClass")
        Console.WriteLine(engine.Evaluate("dir(TestClass)"))

    End Sub

End Class

'This code example produces output similar to the following:
'
'List references from the host:
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
'
'List references from IronPython:
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
'
'Import TestClass from MyAssembly and show its contents:
'['Equals', 'Finalize', 'GetAnswer', 'GetHashCode', 'GetType', 'MemberwiseClone', 'ToString', '__class__', '__doc__', '__init__', '__module__', '__new__', '__repr__']
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using IronPython.Modules;
using System.Collections;

public class Example
{
    private PythonEngine engine = new PythonEngine();
    private ClrModule clr;

    internal static void Main()
    {
        Example e = new Example();
        e.Run();
    }

    private void Run()
    {
        // Import and cache the clr module.
        clr = (ClrModule) engine.Import("clr");

        // Load an assembly and make it available for import by adding
        // it to References.
        clr.AddReference("MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");

        Console.WriteLine("List references from the host:");
        foreach (object obj in (IEnumerable) clr.References)
        {
            Console.WriteLine(obj.ToString());
        }

        engine.Execute("print\r\n" +
                     "print \"List references from IronPython:\"\r\n" +
                     "for s in clr.References: print s");

        Console.WriteLine("\r\nImport TestClass from MyAssembly and show its contents:");
        engine.Import("TestClass");
        Console.WriteLine(engine.Evaluate("dir(TestClass)"));
    }
}

/* This code example produces output similar to the following:

List references from the host:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

List references from IronPython:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null

Import TestClass from MyAssembly and show its contents:
['Equals', 'Finalize', 'GetAnswer', 'GetHashCode', 'GetType', 'MemberwiseClone', 'ToString', '__class__', '__doc__', '__init__', '__module__', '__new__', '__repr__']
 */

Expand image Inheritance Hierarchy

System.Object
IronPython.Modules.ClrModule

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

ClrModule Members
IronPython.Modules Namespace


ClrModule Members
See Also Constructors Fields Methods
CollapseAll image DropDown image

Supports interoperation between IronPython and the common language runtime.

The following tables list the members exposed by the ClrModule type.

Expand image Public Constructors

 | Name | Description
Public method | ClrModule | This member supports the IronPython hosting infrastructure and is not intended to be used directly from your code.
Top

Expand image Public Fields

 | Name | Description
Public field | References | An array of objects representing the assemblies whose contents have been made available for import.
Top

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Accepts | This member supports the IronPython hosting infrastructure and is not intended to be used directly from your code.
Public method | AddReference | Makes one or more assemblies available for import into IronPython, loading the assemblies if necessary.
Public method | AddReferenceByName | Loads a set of assemblies using their display names and makes their contents available to IronPython.
Public method | AddReferenceByPartialName | Loads a set of assemblies using partial display names and makes their contents available to IronPython.
Public method | AddReferenceToFile | Loads the specified assembly files, and makes the contents of the assemblies available to IronPython.
Public method | AddReferenceToFileAndPath | Loads the specified assembly files and makes the contents of the assemblies available to IronPython. If the path of a file is not in sys.path, it is added to sys.path.
Public method | Dispose | Releases the event handler for the AssemblyResolve event.
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | GetClrType | Returns a System.Type that allows the specified Python type object to be treated like a type object of the common language runtime.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetPythonType | Returns a dynamic type object that allows the specified type object of the common language runtime to be treated like a Python type object.
Public method | GetType | (Inherited from Object.)
Public method | LoadAssemblyByName | Loads an assembly using its display name.
Public method | LoadAssemblyByPartialName | Loads an assembly using a partial display name.
Public method | LoadAssemblyFromFile | Loads an assembly using its simple filename, without path.
Public method | LoadAssemblyFromFileWithPath | Loads an assembly file using its full path.
 | ReferenceEquals | (Inherited from Object.)
Public method | Returns | This member supports the IronPython hosting infrastructure and is not intended to be used directly from your code.
Public method | Self | Returns a null reference (Nothing in Visual Basic).
Public method | ToString | Overridden. Returns a string representation of the module.
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

ClrModule Class
IronPython.Modules Namespace


ClrModule Fields
See Also
CollapseAll image DropDown image

Expand image Public Fields

 | Name | Description
Public field | References | An array of objects representing the assemblies whose contents have been made available for import.
Top

Expand image See Also

Reference

ClrModule Class
IronPython.Modules Namespace


ClrModule.References Field
See Also
CollapseAll image DropDown image

An array of objects representing the assemblies whose contents have been made available for import.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public References As Object
Visual Basic (Usage)
Dim instance As ClrModule
Dim value As Object

value = instance.References

instance.References = value
C#
public Object References
C++
public:
Object^ References
J#
public Object References
JScript
public var References : Object

Expand image Remarks

Simply loading an assembly, using the LoadAssemblyByName, LoadAssemblyByPartialName, LoadAssemblyFromFile, and LoadAssemblyFromFileWithPath methods, does not add it to References. To add an assembly to References, use the AddReference, AddReferenceByName, AddReferenceByPartialName, AddReferenceToFile, and AddReferenceToFileAndPath methods.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule Constructor
See Also
CollapseAll image DropDown image

This member supports the IronPython hosting infrastructure and is not intended to be used directly from your code.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub New ( _
    systemState As SystemState _
)
Visual Basic (Usage)
Dim systemState As SystemState

Dim instance As New ClrModule(systemState)
C#
public ClrModule (
    SystemState systemState
)
C++
public:
ClrModule (
    SystemState^ systemState
)
J#
public ClrModule (
    SystemState systemState
)
JScript
public function ClrModule (
    systemState : SystemState
)

Parameters

systemState

Expand image Remarks

Do not use this constructor. From the IronPython console, use import clr. From PythonEngine, use the PythonEngine.Import method to import the clr module.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule Methods
See Also
CollapseAll image DropDown image

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Accepts | This member supports the IronPython hosting infrastructure and is not intended to be used directly from your code.
Public method | AddReference | Makes one or more assemblies available for import into IronPython, loading the assemblies if necessary.
Public method | AddReferenceByName | Loads a set of assemblies using their display names and makes their contents available to IronPython.
Public method | AddReferenceByPartialName | Loads a set of assemblies using partial display names and makes their contents available to IronPython.
Public method | AddReferenceToFile | Loads the specified assembly files, and makes the contents of the assemblies available to IronPython.
Public method | AddReferenceToFileAndPath | Loads the specified assembly files and makes the contents of the assemblies available to IronPython. If the path of a file is not in sys.path, it is added to sys.path.
Public method | Dispose | Releases the event handler for the AssemblyResolve event.
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | GetClrType | Returns a System.Type that allows the specified Python type object to be treated like a type object of the common language runtime.
Public method | GetHashCode | (Inherited from Object.)
Public method | GetPythonType | Returns a dynamic type object that allows the specified type object of the common language runtime to be treated like a Python type object.
Public method | GetType | (Inherited from Object.)
Public method | LoadAssemblyByName | Loads an assembly using its display name.
Public method | LoadAssemblyByPartialName | Loads an assembly using a partial display name.
Public method | LoadAssemblyFromFile | Loads an assembly using its simple filename, without path.
Public method | LoadAssemblyFromFileWithPath | Loads an assembly file using its full path.
 | ReferenceEquals | (Inherited from Object.)
Public method | Returns | This member supports the IronPython hosting infrastructure and is not intended to be used directly from your code.
Public method | Self | Returns a null reference (Nothing in Visual Basic).
Public method | ToString | Overridden. Returns a string representation of the module.
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

ClrModule Class
IronPython.Modules Namespace


ClrModule.Accepts Method
See Also
collapseAll image DropDown image

This member supports the IronPython hosting infrastructure and is not intended to be used directly from your code.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Accepts ( _
    ParamArray types As Object() _
) As Object
Visual Basic (Usage)
Dim instance As ClrModule
Dim types As Object()
Dim returnValue As Object

returnValue = instance.Accepts(types)
C#
public Object Accepts (
    params Object[] types
)
C++
public:
Object^ Accepts (
    ... array<Object^>^ types
)
J#
public Object Accepts (
    Object[] types
)
JScript
public function Accepts (
    ... types : Object[]
) : Object

Parameters

types

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.AddReference Method
See Also
collapseAll image DropDown image

Makes one or more assemblies available for import into IronPython, loading the assemblies if necessary.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub AddReference ( _
    ParamArray references As Object() _
)
Visual Basic (Usage)
Dim instance As ClrModule
Dim references As Object()

instance.AddReference(references)
C#
public void AddReference (
    params Object[] references
)
C++
public:
void AddReference (
    ... array<Object^>^ references
)
J#
public void AddReference (
    Object[] references
)
JScript
public function AddReference (
    ... references : Object[]
)

Parameters

references

An array of string representing assembly names and/or Assembly objects representing assemblies to be made available for import. The strings can be simple names, display names, or simple file names without paths.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | An element of references is a type other than string or Assembly. -or- An element of references is a null reference (Nothing in Visual Basic).
IOException | A reference to an assembly could not be added. For example, the assembly could not be found or loaded, or an empty string was specified.
ArgumentException | An element of references contains a path.

Expand image Remarks

The assemblies are added to References.

If an element of references is a string, it is used to load the assembly by name. If the load fails, the string is used to load the assembly by partial assembly name. If that load fails, the string is used as a filename. If that load fails, the assembly cannot be added and the method throws .

If references is an empty array, no exception is thrown.

To obtain Assembly objects, use the LoadAssemblyByName, LoadAssemblyByPartialName, LoadAssemblyFromFile, and LoadAssemblyFromFileWithPath methods.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.AddReferenceByName Method
See Also
collapseAll image DropDown image

Loads a set of assemblies using their display names and makes their contents available to IronPython.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub AddReferenceByName ( _
    ParamArray names As String() _
)
Visual Basic (Usage)
Dim instance As ClrModule
Dim names As String()

instance.AddReferenceByName(names)
C#
public void AddReferenceByName (
    params string[] names
)
C++
public:
void AddReferenceByName (
    ... array<String^>^ names
)
J#
public void AddReferenceByName (
    String[] names
)
JScript
public function AddReferenceByName (
    ... names : String[]
)

Parameters

names

An array of strings representing assembly names.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | An element of references is a type other than string or Assembly. -or- An element of references is a null reference (Nothing in Visual Basic).

Expand image Remarks

The assemblies are added to References.

The elements of names can represent simple names (that is, the filename without path or extension) for files in the local path, or assembly display names containing the assembly name, version, culture, and public key token. For example, the display name of MyAssembly.dll might be "MyAssembly, Version=2.0.0.0, Culture=neutral, PublicKeyToken=abc5524e86217703033".

Use this method with assembly display names to load strong-named assemblies.

If names is an empty array, no exception is thrown.

To load assemblies without making their contents available for import, use the LoadAssemblyByName method.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.AddReferenceByPartialName Method
See Also Example
collapseAll image DropDown image

Loads a set of assemblies using partial display names and makes their contents available to IronPython.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub AddReferenceByPartialName ( _
    ParamArray names As String() _
)
Visual Basic (Usage)
Dim instance As ClrModule
Dim names As String()

instance.AddReferenceByPartialName(names)
C#
public void AddReferenceByPartialName (
    params string[] names
)
C++
public:
void AddReferenceByPartialName (
    ... array<String^>^ names
)
J#
public void AddReferenceByPartialName (
    String[] names
)
JScript
public function AddReferenceByPartialName (
    ... names : String[]
)

Parameters

names

An array of strings representing partial assembly names.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | An element of references is a type other than string or Assembly. -or- An element of references is a null reference (Nothing in Visual Basic).

Expand image Remarks

The assemblies are added to References.

The elements of names can represent portions of assembly display names. For example, a partial display name might omit the version: "MyAssembly, Culture=neutral, PublicKeyToken=abc5524e86217703033".

If names is an empty array, no exception is thrown.

Expand image Example

The following code example shows one way to start a host application, initialize the IronPython execution engine, import and cache ClrModule, and provide the default module with access to the public API of the host application.

When the host application is started, the Initialize method creates an instance of PythonEngine using the parameterless constructor and uses the Import method to import ClrModule into the default module. The return value is cached, to that the host has a reference to ClrModule.

The Globals property is used to store a reference to the running instance of the application as a global variable in the default module, allowing IronPython code in the default module to access the public API of the host.

To demonstrate these capabilities, the Run method does the following:

  • Executes IronPython code that calls the host application's public Greeting method.

  • Uses the host's cached reference to ClrModule to add a reference to System.Windows.Forms.dll, then executes IronPython code that shows a message box and retrieves the return value.

  • Executes IronPython code that uses ClrModule.References to display the list of assemblies that are loaded and referenced.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports IronPython.Modules

Class MyApplication

    Private engine As PythonEngine
    Private clr As ClrModule

    Private Sub Initialize()

        engine = New PythonEngine()

        ' Import ClrModule, and make it available to the host
        ' application.
        clr = engine.Import("clr")

        ' Make the running instance of the application available
        ' to the default module.
        engine.Globals.Add("MyApplication", Me)

    End Sub

    Shared Sub Main()

        Dim instance As New MyApplication()
        instance.Initialize()
        instance.Run()

    End Sub

    Private Sub Run()

        Console.WriteLine("IronPython code accesses the host API:")
        Dim statements As String = _
            "x = 'Hello'" & vbLf & _
            "MyApplication.Greeting(x)"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "Host code accesses ClrModule:")
        clr.AddReferenceByPartialName("System.Windows.Forms")
        statements = _
            "from System.Windows.Forms import *" & vbLf & _
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)" & vbLf & _
            "print 'You clicked:', result"
        engine.Execute(statements)

        Console.WriteLine(vbLf & "IronPython code accesses clr:")
        statements = _
            "for s in clr.References:" & vbLf & _
            "  print s"
        engine.Execute(statements)
    End Sub

    Public Sub Greeting(ByVal message As String)
        Console.WriteLine("{0} from the host!", message)
    End Sub
End Class

' This code produces output similar to the following:
'
'IronPython code accesses the host API:
'Hello from the host!
'
'Host code accesses ClrModule:
'You clicked: No
'
'IronPython code accesses clr:
'mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;
using IronPython.Modules;

class MyApplication
{
    private PythonEngine engine;
    private ClrModule clr;

    private void Initialize()
    {
        engine = new PythonEngine();

        // Import ClrModule, and make it available to the host
        // application.
        clr = (ClrModule) engine.Import("clr");

        // Make the running instance of the application available
        // to the default module.
        engine.Globals.Add("MyApplication", this);
    }

    public static void Main()
    {
        MyApplication instance = new MyApplication();
        instance.Initialize();
        instance.Run();
    }

    private void Run()
    {
        Console.WriteLine("IronPython code accesses the host API:");
        string statements =
            "x = 'Hello'\n" +
            "MyApplication.Greeting(x)";
        engine.Execute(statements);

        Console.WriteLine("\nHost code accesses ClrModule:");
        clr.AddReferenceByPartialName("System.Windows.Forms");
        statements =
            "from System.Windows.Forms import *\n" +
            "result = MessageBox.Show('Click a button', 'Hello from IronPython', MessageBoxButtons.YesNoCancel)\n" +
            "print 'You clicked:', result";
        engine.Execute(statements);

        Console.WriteLine("\nIronPython code accesses clr:");
        statements =
            "for s in clr.References:\n" +
            "  print s";
        engine.Execute(statements);
    }

    public void Greeting(string message)
    {
        Console.WriteLine("{0} from the host!", message);
    }
}

/* This code produces output similar to the following:

IronPython code accesses the host API:
Hello from the host!

Host code accesses ClrModule:
You clicked: No

IronPython code accesses clr:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
 */

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.AddReferenceToFile Method
See Also
collapseAll image DropDown image

Loads the specified assembly files, and makes the contents of the assemblies available to IronPython.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub AddReferenceToFile ( _
    ParamArray files As String() _
)
Visual Basic (Usage)
Dim instance As ClrModule
Dim files As String()

instance.AddReferenceToFile(files)
C#
public void AddReferenceToFile (
    params string[] files
)
C++
public:
void AddReferenceToFile (
    ... array<String^>^ files
)
J#
public void AddReferenceToFile (
    String[] files
)
JScript
public function AddReferenceToFile (
    ... files : String[]
)

Parameters

files

An array of file names, with extensions but without paths.

Expand image Exceptions

Exception type | Condition
IOException | A reference to an assembly could not be added. For example, the assembly could not be found or loaded, or an empty string was specified.
ArgumentException | An element of files contains a path.
ArgumentTypeException | An element of references is a type other than string or Assembly. -or- An element of references is a null reference (Nothing in Visual Basic).

Expand image Remarks

The assemblies are added to References.

The assemblies are located by searching the paths in sys.path. If an assembly is not in the current paths, you can use the PythonEngine.AddToPath method to add the path to sys.path, or use the AddReferenceToFileWithPath method to load the assembly file and add its path to sys.path, or use the LoadAssemblyFromFileWithPath method to load the assembly file using its full path, and then pass the resulting Assembly object to the AddReference method.

If files is an empty array, no exception is thrown.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.AddReferenceToFileAndPath Method
See Also
collapseAll image DropDown image

Loads the specified assembly files and makes the contents of the assemblies available to IronPython. If the path of a file is not in sys.path, it is added to sys.path.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub AddReferenceToFileAndPath ( _
    ParamArray files As String() _
)
Visual Basic (Usage)
Dim instance As ClrModule
Dim files As String()

instance.AddReferenceToFileAndPath(files)
C#
public void AddReferenceToFileAndPath (
    params string[] files
)
C++
public:
void AddReferenceToFileAndPath (
    ... array<String^>^ files
)
J#
public void AddReferenceToFileAndPath (
    String[] files
)
JScript
public function AddReferenceToFileAndPath (
    ... files : String[]
)

Parameters

files

An array of assembly file names fully qualified by path.

Expand image Exceptions

Exception type | Condition
IOException | A reference to the assembly could not be added. For example, the assembly could not be found or loaded.
ArgumentException | An element of files is the empty string, or the path has an invalid format. -or- An element of files is a null reference (Nothing in Visual Basic).

Expand image Remarks

The assemblies are added to References.

If files is an empty array, no exception is thrown.

To add a reference to an assembly that is not in the paths currently included sys.path without adding the file path to sys.path, use the LoadAssemblyFromFileWithPath method to load the assembly and then pass the resulting Assembly object to the AddReference method.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.Dispose Method
See Also
collapseAll image DropDown image

Releases the event handler for the AssemblyResolve event.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub Dispose
Visual Basic (Usage)
Dim instance As ClrModule

instance.Dispose
C#
public void Dispose ()
C++
public:
virtual void Dispose () sealed
J#
public final void Dispose ()
JScript
public final function Dispose ()

Expand image Remarks

Calling this method may have adverse effects on assembly loading.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.GetClrType Method
See Also Example
collapseAll image DropDown image

Returns a System.Type that allows the specified Python type object to be treated like a type object of the common language runtime.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function GetClrType ( _
    type As Type _
) As Type
Visual Basic (Usage)
Dim instance As ClrModule
Dim type As Type
Dim returnValue As Type

returnValue = instance.GetClrType(type)
C#
public Type GetClrType (
    Type type
)
C++
public:
Type^ GetClrType (
    Type^ type
)
J#
public Type GetClrType (
    Type type
)
JScript
public function GetClrType (
    type : Type
) : Type

Parameters

type

A type object representing an IronPython type or a common language runtime type.

Return Value

A type object that has the same functionality as System.Type.

Expand image Remarks

IronPython types support default conversion to Type, so passing an IronPython type to this method automatically converts it. The method simply returns the converted type. If the specified type is already a common language runtime type, the GetClrType method simply returns it.

Use this method and the GetPythonType method to switch between the two type systems.

Expand image Example

The following example demonstrates the GetPythonType and GetClrType methods at the IronPython console.

CopyCode image Copy Code
>>> import clr
>>> s = "abc"
>>> t = type(s)
>>> t
(type 'str')
>>> clrT = clr.GetClrType(t)
>>> clrT
<System.RuntimeType object at 0x000000000000002B [System.String]>
>>> clrT.GetProperty("Length")
<System.Reflection.RuntimePropertyInfo object at 0x000000000000009D [Int32 Length]>
>>> pyT = clr.GetPythonType(clrT)
>>> pyT.GetProperty("Length")
Traceback (most recent call last):
  File , line 0, in <stdin>##40
AttributeError: type object 'str' has no attribute 'GetProperty'

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.GetPythonType Method
See Also Example
collapseAll image DropDown image

Returns a dynamic type object that allows the specified type object of the common language runtime to be treated like a Python type object.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function GetPythonType ( _
    t As Type _
) As DynamicType
Visual Basic (Usage)
Dim instance As ClrModule
Dim t As Type
Dim returnValue As DynamicType

returnValue = instance.GetPythonType(t)
C#
public DynamicType GetPythonType (
    Type t
)
C++
public:
DynamicType^ GetPythonType (
    Type^ t
)
J#
public DynamicType GetPythonType (
    Type t
)
JScript
public function GetPythonType (
    t : Type
) : DynamicType

Parameters

t

A type object representing an IronPython type or a common language runtime type.

Return Value

A type object that has the same functionality as a Python type object.

Expand image Remarks

If the specified type is already a Python type, the GetPythonType method simply returns it.

Use this method and the GetClrType method to switch between the two type systems.

Expand image Example

The following example demonstrates the GetPythonType and GetClrType methods at the IronPython console.

CopyCode image Copy Code
>>> import clr
>>> s = "abc"
>>> t = type(s)
>>> t
(type 'str')
>>> clrT = clr.GetClrType(t)
>>> clrT
<System.RuntimeType object at 0x000000000000002B [System.String]>
>>> clrT.GetProperty("Length")
<System.Reflection.RuntimePropertyInfo object at 0x000000000000009D [Int32 Length]>
>>> pyT = clr.GetPythonType(clrT)
>>> pyT.GetProperty("Length")
Traceback (most recent call last):
  File , line 0, in <stdin>##40
AttributeError: type object 'str' has no attribute 'GetProperty'

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.LoadAssemblyByName Method
See Also
collapseAll image DropDown image

Loads an assembly using its display name.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function LoadAssemblyByName ( _
    name As String _
) As Assembly
Visual Basic (Usage)
Dim instance As ClrModule
Dim name As String
Dim returnValue As Assembly

returnValue = instance.LoadAssemblyByName(name)
C#
public Assembly LoadAssemblyByName (
    string name
)
C++
public:
Assembly^ LoadAssemblyByName (
    String^ name
)
J#
public Assembly LoadAssemblyByName (
    String name
)
JScript
public function LoadAssemblyByName (
    name : String
) : Assembly

Parameters

name

The display name of the assembly, or a simple name if the assembly is in the local path.

Return Value

An Assembly object representing the loaded assembly.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | name is a null reference (Nothing in Visual Basic).

Expand image Remarks

This method calls the System.Reflection.Assembly.Load(System.String) method, and thus can throw any exception that can be thrown by System.Reflection.Assembly.Load(System.String). If the file cannot be loaded, an exception is thrown.

The name parameter can represent the simple name (that is, the filename without path or extension) of an assembly in the local path, or an assembly display name containing the assembly name, version, culture, and public key token. For example, the display name of MyAssembly.dll might be "MyAssembly, Version=2.0.0.0, Culture=neutral, PublicKeyToken=abc5524e86217703033".

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.LoadAssemblyByPartialName Method
See Also
collapseAll image DropDown image

Loads an assembly using a partial display name.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function LoadAssemblyByPartialName ( _
    name As String _
) As Assembly
Visual Basic (Usage)
Dim instance As ClrModule
Dim name As String
Dim returnValue As Assembly

returnValue = instance.LoadAssemblyByPartialName(name)
C#
public Assembly LoadAssemblyByPartialName (
    string name
)
C++
public:
Assembly^ LoadAssemblyByPartialName (
    String^ name
)
J#
public Assembly LoadAssemblyByPartialName (
    String name
)
JScript
public function LoadAssemblyByPartialName (
    name : String
) : Assembly

Parameters

name

A partial display name.

Return Value

An Assembly object representing the loaded assembly, or a null reference (Nothing in Visual Basic) if the assembly cannot be loaded.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | name is a null reference (Nothing in Visual Basic).

Expand image Remarks

The elements of names can represent portions of assembly display names. For example, a partial display name might omit the version: "MyAssembly, Culture=neutral, PublicKeyToken=abc5524e86217703033".

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.LoadAssemblyFromFile Method
See Also
collapseAll image DropDown image

Loads an assembly using its simple filename, without path.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function LoadAssemblyFromFile ( _
    file As String _
) As Assembly
Visual Basic (Usage)
Dim instance As ClrModule
Dim file As String
Dim returnValue As Assembly

returnValue = instance.LoadAssemblyFromFile(file)
C#
public Assembly LoadAssemblyFromFile (
    string file
)
C++
public:
Assembly^ LoadAssemblyFromFile (
    String^ file
)
J#
public Assembly LoadAssemblyFromFile (
    String file
)
JScript
public function LoadAssemblyFromFile (
    file : String
) : Assembly

Parameters

file

The filename and extension, without path.

Return Value

An Assembly object representing the loaded assembly, or a null reference (Nothing in Visual Basic) if the assembly could not be loaded.

Expand image Exceptions

Exception type | Condition
ArgumentException | file contains a path.
ArgumentTypeException | file is a null reference (Nothing in Visual Basic).

Expand image Remarks

If the assembly cannot be found, a null reference (Nothing in Visual Basic) is returned and no exception is thrown.

Assemblies are located by searching the paths in sys.path. If an assembly is not in the current paths, you can use the LoadAssemblyFromFileWithPath method to load the assembly file using its full path.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.LoadAssemblyFromFileWithPath Method
See Also
collapseAll image DropDown image

Loads an assembly file using its full path.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function LoadAssemblyFromFileWithPath ( _
    file As String _
) As Assembly
Visual Basic (Usage)
Dim instance As ClrModule
Dim file As String
Dim returnValue As Assembly

returnValue = instance.LoadAssemblyFromFileWithPath(file)
C#
public Assembly LoadAssemblyFromFileWithPath (
    string file
)
C++
public:
Assembly^ LoadAssemblyFromFileWithPath (
    String^ file
)
J#
public Assembly LoadAssemblyFromFileWithPath (
    String file
)
JScript
public function LoadAssemblyFromFileWithPath (
    file : String
) : Assembly

Parameters

file

The full assembly filename, including the path.

Return Value

An Assembly object representing the loaded assembly.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | file is a null reference (Nothing in Visual Basic).

Expand image Remarks

This method calls the System.Reflection.Assembly.LoadFile(System.String) method, and thus can throw any exception that can be thrown by System.Reflection.Assembly.LoadFile(System.String). If the file cannot be loaded, an exception is thrown.

Assemblies are loaded into the LoadFile context.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.Returns Method
See Also
collapseAll image DropDown image

This member supports the IronPython hosting infrastructure and is not intended to be used directly from your code.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Returns ( _
    type As Object _
) As Object
Visual Basic (Usage)
Dim instance As ClrModule
Dim type As Object
Dim returnValue As Object

returnValue = instance.Returns(type)
C#
public Object Returns (
    Object type
)
C++
public:
Object^ Returns (
    Object^ type
)
J#
public Object Returns (
    Object type
)
JScript
public function Returns (
    type : Object
) : Object

Parameters

type

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.Self Method
See Also
collapseAll image DropDown image

Returns a null reference (Nothing in Visual Basic).

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function Self As Object
Visual Basic (Usage)
Dim instance As ClrModule
Dim returnValue As Object

returnValue = instance.Self
C#
public Object Self ()
C++
public:
Object^ Self ()
J#
public Object Self ()
JScript
public function Self () : Object

Return Value

a null reference (Nothing in Visual Basic).

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.ToString Method
See Also
collapseAll image DropDown image

Returns a string representation of the module.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Overrides Function ToString As String
Visual Basic (Usage)
Dim instance As ClrModule
Dim returnValue As String

returnValue = instance.ToString
C#
public override string ToString ()
C++
public:
virtual String^ ToString () override
J#
public String ToString ()
JScript
public override function ToString () : String

Return Value

A human-readable string representing the module.

Expand image See Also

Reference

ClrModule Class
ClrModule Members
IronPython.Modules Namespace


ClrModule.Reference Generic Class
See Also Example Members
CollapseAll image DropDown image

Represents a ref or out parameter (ByRef or OutAttribute parameter in Visual Basic) when a common language runtime method is called from IronPython code.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Class Reference(Of T)
Visual Basic (Usage)
Dim instance As Reference(Of T)
C#
public class Reference<T>
C++
generic<typename T>
public ref class Reference
J#
J# supports the use of generic types and methods, but not the declaration of new ones.
JScript
JScript does not support generic types and methods.

Type Parameters

T

The type of the ref or out parameter.

Expand image Remarks

IronPython functions do not have ref and out parameters (ByRef or OutAttribute parameters in Visual Basic), because functions can return multiple values, as Python tuples.

To call a common language runtime method with ref and out parameters from IronPython code, pass a ClrModule.Reference object for each ref or out parameter. For the generic type argument, use the type of the ref or out parameter. After the call returns, you can retrieve the value of the parameter using the Value property.

Expand image Example

The following code example creates a CodeSample class with a Demo method that has a ref parameter of type DateTime and an out parameter of type str (String in the common language runtime). The example makes an instance of the CodeSample class available to the hosted IronPython engine using the global variable cs, and executes IronPython code to call the Demo method.

In the IronPython code executed by the code example, the following lines create two ClrModule.Reference objects, one for each parameter, and pass them to the Demo method:

CopyCode image Copy Code
            p1 = clr.Reference[DateTime](date)
            p2 = clr.Reference[str]()
            cs.Demo(p1, p2)

Each instance of the ClrModule.Reference generic class is strongly typed with the type of the corresponding parameter. For the ref parameter, an initial value is supplied from the date variable. No value is supplied for the out parameter.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Runtime.InteropServices

Class CodeSample

    ' An example of a method with ByRef and Out parameters.
    Public Sub Demo(ByRef p1 As DateTime, _
                    <OutAttribute> ByRef p2 As String)
        p1 = DateTime.Now
        p2 = "Hello, World!"
    End Sub

    Shared Sub Main()
        Dim engine As New PythonEngine()
        engine.Import("clr")
        engine.Import("System")
        engine.Execute("from System import DateTime")

        ' Make an instance of CodeSample available in the default
        ' module.
        engine.Globals.Add("cs", New CodeSample())

        Dim statements As String = _
            "date = DateTime(2006, 8, 7, 16, 0, 0, 0)" & vbLf & _
            "print date" & vbLf & _
            "p1 = clr.Reference[DateTime](date)" & vbLf & _
            "p2 = clr.Reference[str]()" & vbLf & _
            "cs.Demo(p1, p2)" & vbLf & _
            "date = p1.Value" & vbLf & _
            "print date" & vbLf & _
            "print p2.Value"

        engine.Execute(statements)

    End Sub
End Class

' This code example produces output similar to the following:
'
'8/7/2006 4:00:00 PM
'7/27/2006 2:37:45 PM
'Hello, World!
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

class CodeSample
{
    // An example of a method with ref and out parameters.
    public void Demo(ref DateTime p1, out string p2)
    {
        p1 = DateTime.Now;
        p2 = "Hello, World!";
    }

    static void Main()
    {
        PythonEngine engine = new PythonEngine();
        engine.Import("clr");
        engine.Import("System");
        engine.Execute("from System import DateTime");

        // Make an instance of CodeSample available in the default
        // module.
        engine.Globals.Add("cs", new CodeSample());

        string statements =
            "date = DateTime(2006, 8, 7, 16, 0, 0, 0)\n" +
            "print date\n" +
            "p1 = clr.Reference[DateTime](date)\n" +
            "p2 = clr.Reference[str]()\n" +
            "cs.Demo(p1, p2)\n" +
            "date = p1.Value\n" +
            "print date\n" +
            "print p2.Value";

        engine.Execute(statements);
    }
}

/* This code example produces output similar to the following:

8/7/2006 4:00:00 PM
7/27/2006 2:37:45 PM
Hello, World!
 */

Expand image Inheritance Hierarchy

System.Object
IronPython.Modules.ClrModule.Reference

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

ClrModule.Reference Members
IronPython.Modules Namespace


ClrModule.Reference Members
See Also Constructors Methods Properties
CollapseAll image DropDown image

Represents a ref or out parameter (ByRef or OutAttribute parameter in Visual Basic) when a common language runtime method is called from IronPython code.

The following tables list the members exposed by the ClrModule.Reference generic type.

Expand image Public Constructors

 | Name | Description
Public method | ClrModule.Reference | Overloaded. Initializes an instance of the ClrModule.Reference class.
Top

Expand image Public Properties

 | Name | Description
Public property | Value | Gets or sets the value retrieved from or passed to a ref or out parameter (ByRef or OutAttribute parameter in Visual Basic) when a common language runtime method is called from IronPython code.
Top

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
 | ReferenceEquals | (Inherited from Object.)
Public method | ToBoolean | Throws ArgumentTypeException, because a ClrModule.Reference object cannot be converted to Boolean.
Public method | ToString | Overridden. A string representation of the current instance and its value.
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

ClrModule.Reference Generic Class
IronPython.Modules Namespace


ClrModule.Reference Constructor
See Also
CollapseAll image DropDown image

Initializes an instance of the ClrModule.Reference class.

Expand image Overload List

Name | Description
ClrModule.Reference () | Initializes an instance of the ClrModule.Reference class with a default value.
ClrModule.Reference (T) | Initializes an instance of the ClrModule.Reference class, specifying an initial value.

Expand image See Also

Reference

ClrModule.Reference Generic Class
ClrModule.Reference Members
IronPython.Modules Namespace


ClrModule.Reference Constructor ()
See Also Example
CollapseAll image DropDown image

Initializes an instance of the ClrModule.Reference class with a default value.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub New
Visual Basic (Usage)
Dim instance As New Reference(Of T)
C#
public Reference ()
C++
public:
Reference ()
J#
public Reference ()
JScript
public function Reference ()

Expand image Remarks

Use this constructor when the ClrModule.Reference represents an out parameter (OutAttribute parameter in Visual Basic).

Expand image Example

The following code example declares a delegate named Example and creates an instance of that delegate to execute a simple method body in the scope of the default module. The method body uses four variables that are names of parameters of the delegate type, one variable created within the scope of the method body, and one that must be resolved in the scope of the default module.

The third and fourth parameters of the Example delegate are a ref parameter and an out parameter (ByRef and <OutAttribute> parameters in Visual Basic), so in the IronPython code for the method body they must be treated as instances of Reference<int> and Reference<string> (Reference(Of Integer) and Reference(Of String) in Visual Basic). The Value property of ClrModule.Reference is used to obtain the value of the ref parameter, and to set the values of both parameters.

The code example sets the global variable in the default module, then creates the delegate that represents the method. When the delegate is invoked, the method body prints a result, increments the ref parameter, sets the value of the out parameter, and returns the result. The host displays the returned result and the altered values of the ref and out parameters.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Runtime.InteropServices

Delegate Function Example(ByVal p1 As Double, ByVal p2 As Long, _
    ByRef p3 As Integer, <OutAttribute> ByRef p4 As String) As Double

Class CodeSample

    Shared Sub Main()
        Dim engine As New PythonEngine()

        ' The method body uses the parameter names of the delegate
        ' type, Example. Note that p3 is a ByRef parameter and p4 is
        ' an <OutAttribute> parameter, so they contain instances of
        ' ClrModule.Reference. The Reference.Value property is used
        ' to obtain the value of the ByRef parameter, and to set the
        ' values of the two parameters.
        Dim statements As String = _
            "x = p1 * (p2 + p3.Value) - globalValue" & vbLf & _
            "print 'Iron Python prints the result:', x" & vbLf & _
            "p3.Value += 1" & vbLf & _
            "p4.Value = 'Hello from IronPython!'" & vbLf & _
            "return x"

        engine.Globals.Add("globalValue", 1)

        Dim pythonMethod As Example = _
            engine.CreateMethod(Of Example)(statements)

        Dim outValue As String = Nothing
        Dim refValue As Integer = 88
        Dim result As Double = _
            pythonMethod(1.4, 12, refValue, outValue)
        Console.WriteLine("The host prints the result: {0}", result)
        Console.WriteLine("refValue = {0}, outValue = '{1}'", _
            refValue, outValue)

    End Sub
End Class

' This code example produces the following output:
'
'Iron Python prints the result: 139.0
'The host prints the result: 139
'refValue = 89, outValue = 'Hello from IronPython!'
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

delegate double Example(double p1, long p2, ref int p3, out string p4);

class CodeSample
{
    static void Main()
    {
        PythonEngine engine = new PythonEngine();

        // The method body uses the parameter names of the delegate
        // type, Example. Note that p3 is a ref parameter and p4 is
        // an out parameter, so they contain instances of
        // ClrModule.Reference. The Reference.Value property is used
        // to obtain the value of the ref parameter, and to set the
        // values of the two parameters.
        string statements =
            "x = p1 * (p2 + p3.Value) - globalValue\n" +
            "print 'Iron Python prints the result:', x\n" +
            "p3.Value += 1\n" +
            "p4.Value = 'Hello from IronPython!'\n" +
            "return x";

        engine.Globals.Add("globalValue", 1);

        Example pythonMethod = engine.CreateMethod<Example>(
            statements
        );

        string outValue = null;
        int refValue = 88;
        double result = pythonMethod(1.4, 12, ref refValue, out outValue);
        Console.WriteLine("The host prints the result: {0}",
            result);
        Console.WriteLine("refValue = {0}, outValue = '{1}'",
            refValue, outValue);
    }
}

/* This code example produces the following output:

Iron Python prints the result: 139.0
The host prints the result: 139
refValue = 89, outValue = 'Hello from IronPython!'
 */

Expand image See Also

Reference

ClrModule.Reference Generic Class
ClrModule.Reference Members
IronPython.Modules Namespace


ClrModule.Reference Constructor (T)
See Also Example
CollapseAll image DropDown image

Initializes an instance of the ClrModule.Reference class, specifying an initial value.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Sub New ( _
    value As T _
)
Visual Basic (Usage)
Dim value As T

Dim instance As New Reference(Of T)(value)
C#
public Reference (
    T value
)
C++
public:
Reference (
    T value
)
J#
public Reference (
    T value
)
JScript
public function Reference (
    value : T
)

Parameters

value

The value of the ref parameter when the target method is called.

Expand image Remarks

Use this constructor when the ClrModule.Reference represents a ref parameter (ByRef parameter in Visual Basic).

Expand image Example

The following code example creates a CodeSample class with a Demo method that has a ref parameter of type DateTime and an out parameter of type str (String in the common language runtime). The example makes an instance of the CodeSample class available to the hosted IronPython engine using the global variable cs, and executes IronPython code to call the Demo method.

In the IronPython code executed by the code example, the following line create two ClrModule.Reference objects, one for each parameter, and pass them to the Demo method:

CopyCode image Copy Code
            p1 = clr.Reference[DateTime](date)
            p2 = clr.Reference[str]()
            cs.Demo(p1, p2)

Each instance of the ClrModule.Reference generic class is strongly typed with the type of the corresponding parameter. For the ref parameter, an initial value is supplied from the date variable. No value is supplied for the out parameter.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Runtime.InteropServices

Class CodeSample

    ' An example of a method with ByRef and Out parameters.
    Public Sub Demo(ByRef p1 As DateTime, _
                    <OutAttribute> ByRef p2 As String)
        p1 = DateTime.Now
        p2 = "Hello, World!"
    End Sub

    Shared Sub Main()
        Dim engine As New PythonEngine()
        engine.Import("clr")
        engine.Import("System")
        engine.Execute("from System import DateTime")

        ' Make an instance of CodeSample available in the default
        ' module.
        engine.Globals.Add("cs", New CodeSample())

        Dim statements As String = _
            "date = DateTime(2006, 8, 7, 16, 0, 0, 0)" & vbLf & _
            "print date" & vbLf & _
            "p1 = clr.Reference[DateTime](date)" & vbLf & _
            "p2 = clr.Reference[str]()" & vbLf & _
            "cs.Demo(p1, p2)" & vbLf & _
            "date = p1.Value" & vbLf & _
            "print date" & vbLf & _
            "print p2.Value"

        engine.Execute(statements)

    End Sub
End Class

' This code example produces output similar to the following:
'
'8/7/2006 4:00:00 PM
'7/27/2006 2:37:45 PM
'Hello, World!
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

class CodeSample
{
    // An example of a method with ref and out parameters.
    public void Demo(ref DateTime p1, out string p2)
    {
        p1 = DateTime.Now;
        p2 = "Hello, World!";
    }

    static void Main()
    {
        PythonEngine engine = new PythonEngine();
        engine.Import("clr");
        engine.Import("System");
        engine.Execute("from System import DateTime");

        // Make an instance of CodeSample available in the default
        // module.
        engine.Globals.Add("cs", new CodeSample());

        string statements =
            "date = DateTime(2006, 8, 7, 16, 0, 0, 0)\n" +
            "print date\n" +
            "p1 = clr.Reference[DateTime](date)\n" +
            "p2 = clr.Reference[str]()\n" +
            "cs.Demo(p1, p2)\n" +
            "date = p1.Value\n" +
            "print date\n" +
            "print p2.Value";

        engine.Execute(statements);
    }
}

/* This code example produces output similar to the following:

8/7/2006 4:00:00 PM
7/27/2006 2:37:45 PM
Hello, World!
 */

Expand image See Also

Reference

ClrModule.Reference Generic Class
ClrModule.Reference Members
IronPython.Modules Namespace


ClrModule.Reference Methods
See Also
CollapseAll image DropDown image

Expand image Public Methods (see also Protected Methods )

 | Name | Description
Public method | Equals | Overloaded. (Inherited from Object.)
Public method | GetHashCode | (Inherited from Object.)
Public method | GetType | (Inherited from Object.)
 | ReferenceEquals | (Inherited from Object.)
Public method | ToBoolean | Throws ArgumentTypeException, because a ClrModule.Reference object cannot be converted to Boolean.
Public method | ToString | Overridden. A string representation of the current instance and its value.
Top

Expand image Protected Methods

 | Name | Description
Protected method | Finalize | (Inherited from Object.)
Protected method | MemberwiseClone | (Inherited from Object.)
Top

Expand image See Also

Reference

ClrModule.Reference Generic Class
IronPython.Modules Namespace


ClrModule.Reference.ToBoolean Method
See Also
collapseAll image DropDown image

Throws ArgumentTypeException, because a ClrModule.Reference object cannot be converted to Boolean.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function ToBoolean As Boolean
Visual Basic (Usage)
Dim instance As Reference(Of T)
Dim returnValue As Boolean

returnValue = instance.ToBoolean
C#
public bool ToBoolean ()
C++
public:
bool ToBoolean ()
J#
public boolean ToBoolean ()
JScript
public function ToBoolean () : boolean

Return Value

There is no return value, because the property always throws ArgumentTypeException.

Expand image Exceptions

Exception type | Condition
ArgumentTypeException | Accessing this property always throws this exception.

Expand image Remarks

Because this property always throws an exception, a ClrModule.Reference object cannot be used in an IronPython if statement.

This prevents the ClrModule.Reference instance from being converted to a Boolean value. The ClrModule.Reference type is an exception to the rule that any value in Python can be converted to Boolean, because it represents a ref or out parameter, which does not exist in the Python language.

Expand image See Also

Reference

ClrModule.Reference Generic Class
ClrModule.Reference Members
IronPython.Modules Namespace


ClrModule.Reference.ToString Method
See Also
collapseAll image DropDown image

A string representation of the current instance and its value.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Overrides Function ToString As String
Visual Basic (Usage)
Dim instance As Reference(Of T)
Dim returnValue As String

returnValue = instance.ToString
C#
public override string ToString ()
C++
public:
virtual String^ ToString () override
J#
public String ToString ()
JScript
public override function ToString () : String

Return Value

A string that identifies the current instance as a ClrModule.Reference object, and displays in parentheses the string representation of the current value of the Value property.

Expand image Remarks

If the current value of the Value property is a common language runtime type, the string in parentheses is the result of calling its ToString method. If the current value is a null reference (Nothing in Visual Basic) or cannot be displayed as a string, the parentheses are empty.

Expand image See Also

Reference

ClrModule.Reference Generic Class
ClrModule.Reference Members
IronPython.Modules Namespace


ClrModule.Reference Properties
See Also
CollapseAll image DropDown image

Expand image Public Properties

 | Name | Description
Public property | Value | Gets or sets the value retrieved from or passed to a ref or out parameter (ByRef or OutAttribute parameter in Visual Basic) when a common language runtime method is called from IronPython code.
Top

Expand image See Also

Reference

ClrModule.Reference Generic Class
IronPython.Modules Namespace


ClrModule.Reference.Value Property
See Also Example
CollapseAll image DropDown image

Gets or sets the value retrieved from or passed to a ref or out parameter (ByRef or OutAttribute parameter in Visual Basic) when a common language runtime method is called from IronPython code.

Namespace: IronPython.Modules
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Property Value As T
Visual Basic (Usage)
Dim instance As Reference(Of T)
Dim value As T

value = instance.Value

instance.Value = value
C#
public T Value { get; set; }
C++
public:
property T Value {
    T get ();
    void set (T value);
}
J#
/** @property */
public T get_Value ()

/** @property */
public void set_Value (T value)
JScript
public function get Value () : T

public function set Value (value : T)

Property Value

Before the common language runtime method is called from IronPython, the property value is the value that will be passed to a ref parameter. After the call, the property value is the new value the common language runtime method set for a ref or out parameter.

Expand image Remarks

Before calling a common language runtime method with a ref parameter, set the Value property to the value to be passed. There is no need to set the Value property before calling an out parameter, because the value would be ignored anyway.

After calling the common language runtime method, use the Value property to retrieve the new value the common language runtime method assigned to the ref or out parameter.

Expand image Example

The following code example creates a CodeSample class with a Demo method that has a ref parameter of type DateTime and an out parameter of type str (String in the common language runtime). The example makes an instance of the CodeSample class available to the hosted IronPython engine using the global variable cs, and executes IronPython code to call the Demo method.

In the IronPython code executed by the code example, the following line create two ClrModule.Reference objects, one for each parameter, and pass them to the Demo method:

CopyCode image Copy Code
            p1 = clr.Reference[DateTime](date)
            p2 = clr.Reference[str]()
            cs.Demo(p1, p2)

Each instance of the ClrModule.Reference generic class is strongly typed with the type of the corresponding parameter. For the ref parameter, an initial value is supplied from the date variable. No value is supplied for the out parameter.

Visual Basic CopyCode image Copy Code
Imports System
Imports IronPython.Hosting
Imports System.Runtime.InteropServices

Class CodeSample

    ' An example of a method with ByRef and Out parameters.
    Public Sub Demo(ByRef p1 As DateTime, _
                    <OutAttribute> ByRef p2 As String)
        p1 = DateTime.Now
        p2 = "Hello, World!"
    End Sub

    Shared Sub Main()
        Dim engine As New PythonEngine()
        engine.Import("clr")
        engine.Import("System")
        engine.Execute("from System import DateTime")

        ' Make an instance of CodeSample available in the default
        ' module.
        engine.Globals.Add("cs", New CodeSample())

        Dim statements As String = _
            "date = DateTime(2006, 8, 7, 16, 0, 0, 0)" & vbLf & _
            "print date" & vbLf & _
            "p1 = clr.Reference[DateTime](date)" & vbLf & _
            "p2 = clr.Reference[str]()" & vbLf & _
            "cs.Demo(p1, p2)" & vbLf & _
            "date = p1.Value" & vbLf & _
            "print date" & vbLf & _
            "print p2.Value"

        engine.Execute(statements)

    End Sub
End Class

' This code example produces output similar to the following:
'
'8/7/2006 4:00:00 PM
'7/27/2006 2:37:45 PM
'Hello, World!
C# CopyCode image Copy Code
using System;
using IronPython.Hosting;

class CodeSample
{
    // An example of a method with ref and out parameters.
    public void Demo(ref DateTime p1, out string p2)
    {
        p1 = DateTime.Now;
        p2 = "Hello, World!";
    }

    static void Main()
    {
        PythonEngine engine = new PythonEngine();
        engine.Import("clr");
        engine.Import("System");
        engine.Execute("from System import DateTime");

        // Make an instance of CodeSample available in the default
        // module.
        engine.Globals.Add("cs", new CodeSample());

        string statements =
            "date = DateTime(2006, 8, 7, 16, 0, 0, 0)\n" +
            "print date\n" +
            "p1 = clr.Reference[DateTime](date)\n" +
            "p2 = clr.Reference[str]()\n" +
            "cs.Demo(p1, p2)\n" +
            "date = p1.Value\n" +
            "print date\n" +
            "print p2.Value";

        engine.Execute(statements);
    }
}

/* This code example produces output similar to the following:

8/7/2006 4:00:00 PM
7/27/2006 2:37:45 PM
Hello, World!
 */

Expand image See Also

Reference

ClrModule.Reference Generic Class
ClrModule.Reference Members
IronPython.Modules Namespace


IronPython.Runtime.Exceptions Namespace
CollapseAll image
The IronPython.Runtime.Exceptions namespace contains exceptions that can be thrown by IronPython code. If the exceptions are not handled in IronPython code executed by the host application, the host must handle them.

Expand image Classes

 | Class | Description
Public class | ArgumentTypeException |
Public class | PythonAssertionErrorException |
Public class | PythonDeprecationWarningException |
Public class | PythonEnvironmentErrorException |
Public class | PythonFloatingPointErrorException |
Public class | PythonFutureWarningException |
Public class | PythonImportErrorException |
Public class | PythonKeyboardInterruptException |
Public class | PythonLookupErrorException |
Public class | PythonNameErrorException |
Public class | PythonOSErrorException |
Public class | PythonOverflowWarningException |
Public class | PythonPendingDeprecationWarningException |
Public class | PythonReferenceErrorException |
Public class | PythonRuntimeErrorException |
Public class | PythonRuntimeWarningException |
Public class | PythonSyntaxErrorException |
Public class | PythonSyntaxWarningException |
Public class | PythonSystemExitException |
Public class | PythonUnboundLocalErrorException |
Public class | PythonUnicodeErrorException |
Public class | PythonUnicodeTranslateErrorException |
Public class | PythonUserWarningException |
Public class | PythonWarningException |
Public class | StopIterationException |
Public class | StringException |
To make a suggestion or report a bug about Help or another feature of this product, go to the feedback site.


ArgumentTypeException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class ArgumentTypeException
    Inherits Exception
Visual Basic (Usage)
Dim instance As ArgumentTypeException
C#
[SerializableAttribute]
public class ArgumentTypeException : Exception
C++
[SerializableAttribute]
public ref class ArgumentTypeException : public Exception
J#
/** @attribute SerializableAttribute() */
public class ArgumentTypeException extends Exception
JScript
SerializableAttribute
public class ArgumentTypeException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.ArgumentTypeException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonAssertionErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonAssertionErrorException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonAssertionErrorException
C#
[SerializableAttribute]
public class PythonAssertionErrorException : Exception
C++
[SerializableAttribute]
public ref class PythonAssertionErrorException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonAssertionErrorException extends Exception
JScript
SerializableAttribute
public class PythonAssertionErrorException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonAssertionErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonDeprecationWarningException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonDeprecationWarningException
    Inherits PythonWarningException
Visual Basic (Usage)
Dim instance As PythonDeprecationWarningException
C#
[SerializableAttribute]
public class PythonDeprecationWarningException : PythonWarningException
C++
[SerializableAttribute]
public ref class PythonDeprecationWarningException : public PythonWarningException
J#
/** @attribute SerializableAttribute() */
public class PythonDeprecationWarningException extends PythonWarningException
JScript
SerializableAttribute
public class PythonDeprecationWarningException extends PythonWarningException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonWarningException
IronPython.Runtime.Exceptions.PythonDeprecationWarningException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonEnvironmentErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonEnvironmentErrorException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonEnvironmentErrorException
C#
[SerializableAttribute]
public class PythonEnvironmentErrorException : Exception
C++
[SerializableAttribute]
public ref class PythonEnvironmentErrorException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonEnvironmentErrorException extends Exception
JScript
SerializableAttribute
public class PythonEnvironmentErrorException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonEnvironmentErrorException
IronPython.Runtime.Exceptions.PythonOSErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonFloatingPointErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonFloatingPointErrorException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonFloatingPointErrorException
C#
[SerializableAttribute]
public class PythonFloatingPointErrorException : Exception
C++
[SerializableAttribute]
public ref class PythonFloatingPointErrorException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonFloatingPointErrorException extends Exception
JScript
SerializableAttribute
public class PythonFloatingPointErrorException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonFloatingPointErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonFutureWarningException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonFutureWarningException
    Inherits PythonWarningException
Visual Basic (Usage)
Dim instance As PythonFutureWarningException
C#
[SerializableAttribute]
public class PythonFutureWarningException : PythonWarningException
C++
[SerializableAttribute]
public ref class PythonFutureWarningException : public PythonWarningException
J#
/** @attribute SerializableAttribute() */
public class PythonFutureWarningException extends PythonWarningException
JScript
SerializableAttribute
public class PythonFutureWarningException extends PythonWarningException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonWarningException
IronPython.Runtime.Exceptions.PythonFutureWarningException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonImportErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonImportErrorException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonImportErrorException
C#
[SerializableAttribute]
public class PythonImportErrorException : Exception
C++
[SerializableAttribute]
public ref class PythonImportErrorException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonImportErrorException extends Exception
JScript
SerializableAttribute
public class PythonImportErrorException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonImportErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonKeyboardInterruptException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonKeyboardInterruptException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonKeyboardInterruptException
C#
[SerializableAttribute]
public class PythonKeyboardInterruptException : Exception
C++
[SerializableAttribute]
public ref class PythonKeyboardInterruptException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonKeyboardInterruptException extends Exception
JScript
SerializableAttribute
public class PythonKeyboardInterruptException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonKeyboardInterruptException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonLookupErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonLookupErrorException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonLookupErrorException
C#
[SerializableAttribute]
public class PythonLookupErrorException : Exception
C++
[SerializableAttribute]
public ref class PythonLookupErrorException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonLookupErrorException extends Exception
JScript
SerializableAttribute
public class PythonLookupErrorException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonLookupErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonNameErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonNameErrorException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonNameErrorException
C#
[SerializableAttribute]
public class PythonNameErrorException : Exception
C++
[SerializableAttribute]
public ref class PythonNameErrorException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonNameErrorException extends Exception
JScript
SerializableAttribute
public class PythonNameErrorException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonNameErrorException
IronPython.Runtime.Exceptions.PythonUnboundLocalErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonOSErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonOSErrorException
    Inherits PythonEnvironmentErrorException
Visual Basic (Usage)
Dim instance As PythonOSErrorException
C#
[SerializableAttribute]
public class PythonOSErrorException : PythonEnvironmentErrorException
C++
[SerializableAttribute]
public ref class PythonOSErrorException : public PythonEnvironmentErrorException
J#
/** @attribute SerializableAttribute() */
public class PythonOSErrorException extends PythonEnvironmentErrorException
JScript
SerializableAttribute
public class PythonOSErrorException extends PythonEnvironmentErrorException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonEnvironmentErrorException
IronPython.Runtime.Exceptions.PythonOSErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonOverflowWarningException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonOverflowWarningException
    Inherits PythonWarningException
Visual Basic (Usage)
Dim instance As PythonOverflowWarningException
C#
[SerializableAttribute]
public class PythonOverflowWarningException : PythonWarningException
C++
[SerializableAttribute]
public ref class PythonOverflowWarningException : public PythonWarningException
J#
/** @attribute SerializableAttribute() */
public class PythonOverflowWarningException extends PythonWarningException
JScript
SerializableAttribute
public class PythonOverflowWarningException extends PythonWarningException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonWarningException
IronPython.Runtime.Exceptions.PythonOverflowWarningException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonPendingDeprecationWarningException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonPendingDeprecationWarningException
    Inherits PythonWarningException
Visual Basic (Usage)
Dim instance As PythonPendingDeprecationWarningException
C#
[SerializableAttribute]
public class PythonPendingDeprecationWarningException : PythonWarningException
C++
[SerializableAttribute]
public ref class PythonPendingDeprecationWarningException : public PythonWarningException
J#
/** @attribute SerializableAttribute() */
public class PythonPendingDeprecationWarningException extends PythonWarningException
JScript
SerializableAttribute
public class PythonPendingDeprecationWarningException extends PythonWarningException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonWarningException
IronPython.Runtime.Exceptions.PythonPendingDeprecationWarningException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonReferenceErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonReferenceErrorException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonReferenceErrorException
C#
[SerializableAttribute]
public class PythonReferenceErrorException : Exception
C++
[SerializableAttribute]
public ref class PythonReferenceErrorException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonReferenceErrorException extends Exception
JScript
SerializableAttribute
public class PythonReferenceErrorException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonReferenceErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonRuntimeErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonRuntimeErrorException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonRuntimeErrorException
C#
[SerializableAttribute]
public class PythonRuntimeErrorException : Exception
C++
[SerializableAttribute]
public ref class PythonRuntimeErrorException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonRuntimeErrorException extends Exception
JScript
SerializableAttribute
public class PythonRuntimeErrorException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonRuntimeErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonRuntimeWarningException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonRuntimeWarningException
    Inherits PythonWarningException
Visual Basic (Usage)
Dim instance As PythonRuntimeWarningException
C#
[SerializableAttribute]
public class PythonRuntimeWarningException : PythonWarningException
C++
[SerializableAttribute]
public ref class PythonRuntimeWarningException : public PythonWarningException
J#
/** @attribute SerializableAttribute() */
public class PythonRuntimeWarningException extends PythonWarningException
JScript
SerializableAttribute
public class PythonRuntimeWarningException extends PythonWarningException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonWarningException
IronPython.Runtime.Exceptions.PythonRuntimeWarningException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonSyntaxErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonSyntaxErrorException
    Inherits Exception
    Implements ICustomExceptionConversion
Visual Basic (Usage)
Dim instance As PythonSyntaxErrorException
C#
[SerializableAttribute]
public class PythonSyntaxErrorException : Exception, ICustomExceptionConversion
C++
[SerializableAttribute]
public ref class PythonSyntaxErrorException : public Exception, ICustomExceptionConversion
J#
/** @attribute SerializableAttribute() */
public class PythonSyntaxErrorException extends Exception implements ICustomExceptionConversion
JScript
SerializableAttribute
public class PythonSyntaxErrorException extends Exception implements ICustomExceptionConversion

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonSyntaxErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonSyntaxWarningException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonSyntaxWarningException
    Inherits PythonWarningException
Visual Basic (Usage)
Dim instance As PythonSyntaxWarningException
C#
[SerializableAttribute]
public class PythonSyntaxWarningException : PythonWarningException
C++
[SerializableAttribute]
public ref class PythonSyntaxWarningException : public PythonWarningException
J#
/** @attribute SerializableAttribute() */
public class PythonSyntaxWarningException extends PythonWarningException
JScript
SerializableAttribute
public class PythonSyntaxWarningException extends PythonWarningException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonWarningException
IronPython.Runtime.Exceptions.PythonSyntaxWarningException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonSystemExitException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonSystemExitException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonSystemExitException
C#
[SerializableAttribute]
public class PythonSystemExitException : Exception
C++
[SerializableAttribute]
public ref class PythonSystemExitException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonSystemExitException extends Exception
JScript
SerializableAttribute
public class PythonSystemExitException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonSystemExitException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonUnboundLocalErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonUnboundLocalErrorException
    Inherits PythonNameErrorException
Visual Basic (Usage)
Dim instance As PythonUnboundLocalErrorException
C#
[SerializableAttribute]
public class PythonUnboundLocalErrorException : PythonNameErrorException
C++
[SerializableAttribute]
public ref class PythonUnboundLocalErrorException : public PythonNameErrorException
J#
/** @attribute SerializableAttribute() */
public class PythonUnboundLocalErrorException extends PythonNameErrorException
JScript
SerializableAttribute
public class PythonUnboundLocalErrorException extends PythonNameErrorException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonNameErrorException
IronPython.Runtime.Exceptions.PythonUnboundLocalErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonUnicodeErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonUnicodeErrorException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonUnicodeErrorException
C#
[SerializableAttribute]
public class PythonUnicodeErrorException : Exception
C++
[SerializableAttribute]
public ref class PythonUnicodeErrorException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonUnicodeErrorException extends Exception
JScript
SerializableAttribute
public class PythonUnicodeErrorException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonUnicodeErrorException
IronPython.Runtime.Exceptions.PythonUnicodeTranslateErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonUnicodeTranslateErrorException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonUnicodeTranslateErrorException
    Inherits PythonUnicodeErrorException
Visual Basic (Usage)
Dim instance As PythonUnicodeTranslateErrorException
C#
[SerializableAttribute]
public class PythonUnicodeTranslateErrorException : PythonUnicodeErrorException
C++
[SerializableAttribute]
public ref class PythonUnicodeTranslateErrorException : public PythonUnicodeErrorException
J#
/** @attribute SerializableAttribute() */
public class PythonUnicodeTranslateErrorException extends PythonUnicodeErrorException
JScript
SerializableAttribute
public class PythonUnicodeTranslateErrorException extends PythonUnicodeErrorException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonUnicodeErrorException
IronPython.Runtime.Exceptions.PythonUnicodeTranslateErrorException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonUserWarningException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonUserWarningException
    Inherits PythonWarningException
Visual Basic (Usage)
Dim instance As PythonUserWarningException
C#
[SerializableAttribute]
public class PythonUserWarningException : PythonWarningException
C++
[SerializableAttribute]
public ref class PythonUserWarningException : public PythonWarningException
J#
/** @attribute SerializableAttribute() */
public class PythonUserWarningException extends PythonWarningException
JScript
SerializableAttribute
public class PythonUserWarningException extends PythonWarningException

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonWarningException
IronPython.Runtime.Exceptions.PythonUserWarningException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonWarningException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class PythonWarningException
    Inherits Exception
Visual Basic (Usage)
Dim instance As PythonWarningException
C#
[SerializableAttribute]
public class PythonWarningException : Exception
C++
[SerializableAttribute]
public ref class PythonWarningException : public Exception
J#
/** @attribute SerializableAttribute() */
public class PythonWarningException extends Exception
JScript
SerializableAttribute
public class PythonWarningException extends Exception

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.PythonWarningException
Derived Classes

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


StopIterationException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public Class StopIterationException
    Inherits InvalidOperationException
Visual Basic (Usage)
Dim instance As StopIterationException
C#
[SerializableAttribute]
public class StopIterationException : InvalidOperationException
C++
[SerializableAttribute]
public ref class StopIterationException : public InvalidOperationException
J#
/** @attribute SerializableAttribute() */
public class StopIterationException extends InvalidOperationException
JScript
SerializableAttribute
public class StopIterationException extends InvalidOperationException

Expand image Inheritance Hierarchy

System.Object
System.Exception
System.SystemException
System.InvalidOperationException
IronPython.Runtime.Exceptions.StopIterationException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


StringException Class
See Also Members
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
<SerializableAttribute> _
Public NotInheritable Class StringException
    Inherits Exception
    Implements ICustomExceptionConversion
Visual Basic (Usage)
Dim instance As StringException
C#
[SerializableAttribute]
public sealed class StringException : Exception, ICustomExceptionConversion
C++
[SerializableAttribute]
public ref class StringException sealed : public Exception, ICustomExceptionConversion
J#
/** @attribute SerializableAttribute() */
public final class StringException extends Exception implements ICustomExceptionConversion
JScript
SerializableAttribute
public final class StringException extends Exception implements ICustomExceptionConversion

Expand image Inheritance Hierarchy

System.Object
System.Exception
IronPython.Runtime.Exceptions.StringException

Expand image Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Expand image See Also

Reference

IronPython.Runtime.Exceptions Namespace


PythonSyntaxErrorException.ToPythonException Method
See Also
collapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function ToPythonException As Object
Visual Basic (Usage)
Dim instance As PythonSyntaxErrorException
Dim returnValue As Object

returnValue = instance.ToPythonException
C#
public Object ToPythonException ()
C++
public:
virtual Object^ ToPythonException () sealed
J#
public final Object ToPythonException ()
JScript
public final function ToPythonException () : Object

Expand image See Also

Reference

PythonSyntaxErrorException Class
PythonSyntaxErrorException Members
IronPython.Runtime.Exceptions Namespace


StringException.ToPythonException Method
See Also
collapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public Function ToPythonException As Object
Visual Basic (Usage)
Dim instance As StringException
Dim returnValue As Object

returnValue = instance.ToPythonException
C#
public Object ToPythonException ()
C++
public:
virtual Object^ ToPythonException () sealed
J#
public final Object ToPythonException ()
JScript
public final function ToPythonException () : Object

Expand image See Also

Reference

StringException Class
StringException Members
IronPython.Runtime.Exceptions Namespace


ExceptionConverter.CreatePythonException Method
See Also
CollapseAll image DropDown image

Expand image Overload List

Name | Description
ExceptionConverter.CreatePythonException (String) |
ExceptionConverter.CreatePythonException (String, String) |
ExceptionConverter.CreatePythonException (String, String, IPythonType) |
ExceptionConverter.CreatePythonException (String, String, IPythonType, ExceptionClassCreator) |

Expand image See Also

Reference

ExceptionConverter Class
ExceptionConverter Members
IronPython.Runtime.Exceptions Namespace


ExceptionConverter.GetPythonException Method
See Also
CollapseAll image DropDown image

Expand image Overload List

Name | Description
ExceptionConverter.GetPythonException (String) |
ExceptionConverter.GetPythonException (String, String) |

Expand image See Also

Reference

ExceptionConverter Class
ExceptionConverter Members
IronPython.Runtime.Exceptions Namespace


ExceptionMapping.ClrException Property
See Also
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public ReadOnly Property ClrException As Type
Visual Basic (Usage)
Dim instance As ExceptionMapping
Dim value As Type

value = instance.ClrException
C#
public Type ClrException { get; }
C++
public:
property Type^ ClrException {
    Type^ get ();
}
J#
/** @property */
public Type get_ClrException ()
JScript
public function get ClrException () : Type

Expand image See Also

Reference

ExceptionMapping Structure
ExceptionMapping Members
IronPython.Runtime.Exceptions Namespace


ExceptionMapping.PythonException Property
See Also
CollapseAll image DropDown image

Namespace: IronPython.Runtime.Exceptions
Assembly: IronPython (in ironpython.dll)

Expand image Syntax

Visual Basic (Declaration)
Public ReadOnly Property PythonException As String
Visual Basic (Usage)
Dim instance As ExceptionMapping
Dim value As String

value = instance.PythonException
C#
public string PythonException { get; }
C++
public:
property String^ PythonException {
    String^ get ();
}
J#
/** @property */
public String get_PythonException ()
JScript
public function get PythonException () : String

Expand image See Also

Reference

ExceptionMapping Structure
ExceptionMapping Members
IronPython.Runtime.Exceptions Namespace