General

Why is it called IronPython?

See http://channel9.msdn.com/pdc2008/TL10 or http://port25.technet.com/archive/2006/06/01/2565.aspx

How do I report a bug?

On CodePlex you can file bugs by selecting the "Issue Tracker" tab and clicking on "New Work Item".

Where can I give feedback and ask questions about IronPython?

The IronPython Mailing List is a great place to get your questions about IronPython answered, and the entire IronPython team is subscribed to this. Also, our team makes quite a few decisions based on the feedback we see on this list.

What CPython version are you compatible with?

IronPython 2.7 targets CPython 2.7.x for compatibility. See the IronPython Differences document for details.

Why are some built-in modules not present?

IronPython implements all the commonly used built-in modules. Some modules are not implemented because they are OS-specific (for example, they are only relevant on SGI or the Mac). Some modules aren't present only because we didn't have time to implement them yet. See the IronPython Differences document for details.

Does the IronPython Team accept back source contributions into the IronPython and DLR codebases?

Yes, since the hand-off from Microsoft we are able to accept contributions. The source is available on GitHub and can be forked and pull requests submitted (this is the requested workflow for submitting contributions).

Licensing

Is this license OSI compliant?

Absolutely. The Apache 2.0 License has been approved by OSI.

What copyright rights does the license grant me?

See the license distributed with IronPython or http://www.opensource.org/licenses/apache2.0.php:
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

What patent rights does the license grant me?

See the license distributed with IronPython or http://www.opensource.org/licenses/apache2.0.php:
Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

Visual Studio

When will Python support be added into Visual Studio?

Please refer to http://pytools.codeplex.com for information on using IronPython with Visual Studio.

Building and Installing IronPython

Is there an installer for IronPython?

Yes. As of IronPython 2.0 we are distributing an MSI in addition to the zip file full of binaries. Furthermore, this MSI installs CPython standard modules and packages that work under IronPython.

Why does IronPython not follow the standard C# naming conventions, why so many FxCop errors?

We have fixed all FxCop errors in the IronPython.Hosting namespace which is the main public API exposed by IronPython. However, there are other public types that are marked public either because the generated IL code needs them or because of historical reasons. While we would like to fix all FxCop issues for all public types, those remaining do not affect users of IronPython. We want to release IronPython 2.0 under the principles of "release early, release often". We thought that it was unnecessary to delay the release to take the time to do this work first. These kinds of issues will be resolved as we work on future releases.

Running IronPython

How do I use CPython standard libraries?

To tell IronPython where the Python standard library is, you can add the "lib" directory of CPython to IronPython's path. To do this, put the following code into IronPython's "site.py" file (replace c:\python24\lib with your actual path to the CPython lib directory):
import sys
sys.path.append(r"c:\python24\lib")

Really this is not necessary if you install the MSI installer of IronPython though.

How do I get ipy.exe to automatically complete commands from interactive sessions?

IronPython provides a tab completion feature which lets you type in part of the name of a Python function, module, etc followed by the Tab key which will emit the rest of the name. For example, typing the following into an interactive session:
    import sys
    sys.v

followed by the Tab key will expand to:
    import sys
    sys.version


In cases where there are multiple matches, simply press the Tab key multiple times to cycle through the possibilities. To enable this feature, pass -X:TabCompletion as a command-line parameter to ipy.exe

Why do you require .NET 2.0 SP1 to run IronPython 2.0?

There are a lot of features in .NET 2.0 that we wanted to use in IronPython. These include generics, DynamicMethods, new kinds of delegates, and more. We could have supported these new features using #ifdefs to keep a version of the code base that ran on 1.1. We decided that backwards compatibility wasn’t worth complicating the code base and development of IronPython at this time. We expect that when we start working on adding support for new .NET 3.0 features to IronPython that we’ll do them in the #ifdef or similar way so that IronPython will continue to run on .NET 2.0 for the foreseeable future.

Writing Applications to run under IronPython

How does clr.AddReference work?

Static languages specify assembly dependencies while compiling the assembly, and the dependences are automatically loaded by the CLR loader as needed. However, dynamic languages are not compiled, and so need to specify and load dependent assemblies imperatively.
The CLR prefers to do assembly loading using the full assembly name (eg "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"). The Assembly.Load API requires such a full assembly name. However, IronPython exposes loading of assemblies using simple assembly names (eg. clr.AddReference("System")) since this is what script-writers expect. IronPython implements this functionality by hooking the AppDomain.AssemblyResolve event. This event is fired when the CLR is unable to resolve an assembly name. IronPython then searches the path specified in "sys.path" looking for an assembly that matches the partial name. It then loads it using the Assembly.LoadFile API.

Why doesn't System behave like other Python modules?

The short answer is System is not a Python module:
>>> import System
>>> type(System)
<type 'NamespaceTracker'>

which means you'll be unable to perform certain operations on it (e.g., setattr) that you would normally be able to with Python modules.

Why am I getting errors when trying to use WinForms?

One common error that you may be getting is:
C:\IronPython>ipy.exe
IronPython 1.0.2424 on .NET 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
>>> import System.Windows.Forms as WinForms
Traceback (most recent call last):
File , line 0, in -toplevel-
AttributeError: 'package#' object has no attribute 'Windows'

The cause is that IronPython needs help finding any assemblies that are even a little bit out of the ordinary. The Built-in module clr provides functions to add references to .NET modules (clr.AddReference). For more information, see the Loading .NET Libraries exercise in the IronPython Tutorial (the tutorial.htm document is in the tutorial directory where you installed IronPython).

How do I make use of .NET features in IronPython?

Users have to opt in to this functionality. No new keywords have been added, and the existing language semantics are unchanged. A "clr" module is available for import to turn on .NET extensions. See the IronPython Tutorial for good examples (if you're reading the FAQ on the web, the tutorial.htm document is in the tutorial directory where you installed IronPython). Using the "import clr" statement adds methods to built-in types in some cases; for example, dir(int) will show a ToString attribute. Such effects only happen in the context of the module that contains the "import clr" statement.

How do I import .NET namespaces from assemblies other than System and Mscorlib?

IronPython can directly import only some of the .NET libraries -- the most commonly used ones. To use additional .NET assemblies, they must be explicitly referenced. To add a reference to a .NET assembly, use one of the clr.AddReference* functions. See IronPython Tutorial for good examples and instruction on how to do this (if you're reading the FAQ on the web, the tutorial.htm document is in the tutorial directory where you installed IronPython).

.NET Interop

How do I choose amongst a method's overloads?

.NET methods may have an Overloads attribute which can be indexed by a tuple of types to choose between overloads of a .NET method. For example, the following chooses the WriteLine method that takes an object and passes None for it:
from System import Console
Console.WriteLine.Overloads[object](None)

How can I call a method with ref, out, and params parameters?

Consider the following C# class which defines methods with ref, out, and params parameters. Following the C# code are examples in the Python interpreter of calling these methods.

File a.cs (compiled with "csc.exe /t:library a.cs"):
public class C {
    public static int MethodRef(ref int i) { i = 1; return 2; }
    public static int MethodOut(out int i) { i = 1; return 2; }
    public static int MethodParams(params object[] values) { return values.Length; }
}


Loading the class C:
>>> import clr
>>> clr.AddReference("a.dll")
>>> import C


Calling the method with ref parameters: if you pass the value (3) directly, the output value will become part of the returned tuple.
>>> C.MethodRef(3)
(2, 1)


Alternatively, you can create an instance of clr.Reference<T> and initialize it with the value that you want to pass into the method. When the call returns, the value will have been updated.
>>> import clr
>>> x = clr.Reference[int](3)
>>> x.Value
3
>>> C.MethodRef(x)
2
>>> x.Value
1


Calling the method with an out parameter is very similar, except there is no need to provide the input value. The values of the out parameters will become part of the returned tuple:
>>> C.MethodOut()
(2, 1)


You can also provide an instance of clr.Reference<T> to capture the value of the out parameter. The initial value in this case does not matter.
>>> x = clr.Reference[int]()
>>> x.Value                        # The Value is initialized to 0
0
>>> C.MethodOut(x)
2
>>> x.Value                        # Value was modified by the MethodOut method.
1
>>> x.Value = 10
>>> C.MethodOut(x)
2
>>> x.Value
1


IronPython handles methods with params arguments in a natural way. The parameters can be passed as a parameter list:
>>> C.MethodParams(1,2,3)
3
>>> C.MethodParams(1,2,3,4,5,6,)
6

How do I create a .NET array?

Here is an example that shows how to create a .NET array: "System.Arrayint((1,2,3))".
import System
System.Array[int]((1,2,3))


Here is another example that creates a multi-dimensional array of arrays and initializes it (any kind of Python sequence can be used to initialize the array):
Array[Array[int]]( ( (1,2), (2,3) ) )


If you want to create a true multi-dimensional array and set elements, you can do the following :
x = Array.CreateInstance(int, Array[int]((1,2,3)))
x[0,1,2] = 2

How do I specify generic types, such as collections?

IronPython supports an indexing-like syntax for identifying concrete realizations of generic types and methods, for example:
import System
q = System.Collections.Generic.Queue[str]()


This is similar to creating a .NET array.

How can I access .NET properties and indexers?

The following is a simple example of setting and getting the value of a property "Text" on a windows form. The syntax is the same as any attribute access.
>>> import System
>>> clr.AddReference("System.Windows.Forms")
>>> from System.Windows.Forms import Form
>>> f = Form()
>>> f.Text = "Hello"                    # Set the property
>>> f.Text                              # Get the property value
'Hello'
>>>


To call indexers, use Python's indexing syntax:
>>> import System
>>> h = System.Collections.Hashtable()
>>> h['a'] = 10
>>> h['a']
10

How does IronPython handle conversions between Python types and .NET types?

IronPython runs on the .NET Framework which provides more primitive types than Python. If you use normal Python code with IronPython, you will only encounter the standard Python types (int, long, float, str, ...). When calling .NET methods, IronPython will try to convert the argument values to the appropriate .NET types. See below for an example with integer numbers.

File a.cs (compiled with "csc.exe /t:library a.cs"):
public class C {
    public static void MethodUShort(ushort p) { }
}


The following Python code calls the "MethodUShort" on class C with different argument values:
>>> import clr
>>> clr.AddReference("a.dll")
>>> import C
>>> C.MethodUShort(1)                     # conversion will succeed
>>> C.MethodUShort(65536)                 # 65536 won't fit into System.UInt16
Traceback (most recent call last):
File , line 0, in <stdin>##20
File , line 0, in MethodUShort##19
OverflowError: Arithmetic operation resulted in an overflow.
>>> C.MethodUShort(-1)                    # neither will -1
Traceback (most recent call last):
File , line 0, in <stdin>##21
File , line 0, in MethodUShort##19
OverflowError: Arithmetic operation resulted in an overflow.

How does IronPython work with the .NET System.Char type since Python doesn't have a char type?

In IronPython, all strings of length 1 will be automatically coerced into System.Char type when System.Char type is expected. If a method returns System.Char type, the actual return value will be an instance of System.Char type, but the value can be easily converted to string:
>>> x = System.Char.Parse('a')
>>> x
<System.Char object at 0x000000000000002C [a]>
>>> str(x)
'a'

How does IronPython work with .NET structs, value types, enums?

All instances of value types are always boxed within the IronPython runtime.

How do .NET assemblies and namespaces relate to Python modules?

In IronPython, the import mechanism provides access to the namespaces in .NET assemblies. Once the assembly is referenced by the IronPython runtime, it is possible to import the namespaces contained within the assembly. Once a namespace is imported, all nested namespaces are also accessible. For more information, see the Loading .NET Libraries exercise in the IronPython Tutorial (if you're reading the FAQ on the web, the tutorial.htm document is in the tutorial directory where you installed IronPython).
>>> import System
>>> clr.AddReference("System.Windows.Forms")
>>> import System.Windows
>>> form = System.Windows.Forms.Form() 


Compatibility

Why can't I get NumPy and SciPy working under IronPython?

The short answer is http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=11333. Both NumPy and SciPy make heavy use of Python extension modules (i.e., modules with a .pyd extension) to speed up certain calls. Python extension modules in turn are C/C++ based libraries that CPython understands and can expose to real Python scripts (i.e., files with a .py extension) as native Python. IronPython cannot currently import these C/C++ libraries as IronPython is implemented in C#. It's actually a bit more complicated than this but hopefully you get the idea.

The good news is that http://www.resolversystems.com has announced they will be working on an IronPython add-in to support CPython extension modules - see http://www.resolversystems.com/news/?p=17 for the announcement. There are also a couple more options:
  • you can also utilize Python for .NET with CPython to access .NET libraries from Python code. Please note however that Python for .NET is missing some features IronPython provides such as hosting Python sessions from managed applications
  • since Python extension modules are based on C/C++ sources, it should in theory be possible to compile these into .NET assemblies which IronPython can understand

Can I write Xbox 360 games using IronPython?

While you can indeed code XNA games with IronPython, they will not run on the Xbox 360. XNA on the Xbox 360 is based on the .NET Compact Framework which doesn't support System.Reflection.Emit - see http://msdn.microsoft.com/en-us/library/bb203912.aspx. Since IronPython makes heavy use of System.Reflection.Emit it's currently impossible to get it running under the Xbox 360.

What's the state of running Zope/Plone on IronPython?

We're unaware of any specific efforts being made to get Zope running under IronPython. If this is something that's important to the IronPython Community, please bring this up on the IronPython Mailing List or vote for http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=20298.

Do you have any 2.6 features working?

Yes, several of the 2.6 features are implemented and working with 2.7 features also being available.

Do we work with the .NET Compact Framework?

No, IronPython 2.0 targets only the .NET 2.0 Common Language Runtime. The .NET Compact Framework lacks Reflection.Emit and lightweight code generation (dynamic methods), both of which IronPython requires.

How do I create, or why don't you create .pyc files?

IronPython does not cache binary products for .py files, nor write fast loading version of .py files. IronPython will likely support this kind of optimization in the future.

How does IronPython's threading model relate to CPython's with respect to object operations?

CPython has a Global Interpreter Lock, and it interprets opcodes for operations on primitive types atomically. IronPython also ensures operations on primitive types are atomic (for example, inserting into a list or removing an item at a specific index). However, IronPython's in-place addition operations (for example, "l = []; l += 2,3,4") are not atomic, so if two threads perform this operation, "l" could end up with interleaving values. Furthermore, IronPython looks up an operation's implementation method atomically and then invokes the method atomically. Between the time of the look up and the invoke, another thread could execute that replaced the definition of the operation, and the first thread would invoke the old definition it found. If a program's behavior needs to be guaranteed across this sort of scenario, your program should be ensuring this level of thread safety; the CPython specification makes no guarantees in this situation either.

Misc.

Why does ipy.exe appear to access the internet sometimes?

Microsoft signs its DLLs so that they can be verified as coming from Microsoft. Because ipy.exe is using DLLs that are signed, the .NET CLR tries to confirm the certificates that were used to sign the DLLs. When it does this, you may notice internet traffic to a certification service for signed binaries, and you may notice performance impact on start up. For a good discussion of this topic, please see Authenticode and Assemblies.

How do I compile .py files to a DLL for linking into my C# or VB program?

The pyc.py script is the closest thing to this and can now generate "standalone" binaries which embed the necessary runtime libraries as resources. The .NET framework is still required to run the executable.

How do I build and call into PYD libraries?

IronPython does not support using PYDs built for CPython since they leverage implementation details of CPython. You can get a similar effect for new "PYD"s you would like to implement by writing them in C# or VB and building a DLL for .NET.

Last edited Jun 5, 2012 at 4:20 PM by slide_o_mix, version 33

Comments

r4dian May 21, 2012 at 10:40 PM 
> "While you can indeed code XNA games with IronPython..."

Is this still true with XNA 4.0? Online examples like
http://www.ironpython.info/index.php/XNA_Example_-_Luminance
no longer work.

kanzure Sep 9, 2009 at 4:15 PM 
Another issue that isn't clear is why exactly IronPython must be this separate binary executable. Why can't I just import .NET compatibility via my normal python sessions and interpreters?

Eriol Mar 3, 2009 at 10:22 PM 
What isn't clear here is how to add new directories to search for .NET assemblies. In the tutorial it's saying to alter site.py, but since that's part of the common standard library in current IPy releases (it wasn't in 1.x), altering it seems unwise. I've seen reference to the IRONPYTHONPATH environment variable as well throughout some docs, but is that right? What about a sitecustomize.py like the new site.py suggests?

neraun Jan 27, 2009 at 2:27 PM 
Unfortunatly, yes, it is. But talking about startup time with IronPython seems to be a little taboo... You can try to use N'GEN binary but it did not change anything for me.

ewoudenberg Dec 31, 2008 at 7:33 PM 
This is very exciting -- thank you!

My one observation is that it's a bit slow to start. Is the following normal?

$ time ipy -c 'print "hi"'
hi

real 0m5.636s
user 0m0.015s
sys 0m0.046s

getelab Sep 20, 2006 at 1:10 AM 
Is there any API to work with Telnet?