Embedding .NET into Python

Getting Started

A key goal for this project has been that Python.NET should “work just the way you’d expect in Python”, except for cases that are .NET-specific (in which case the goal is to work “just the way you’d expect in C#”).

A good way to start is to interactively explore .NET usage in python interpreter by following along with the examples in this document. If you get stuck, there are also a number of demos and unit tests located in the source directory of the distribution that can be helpful as examples. Additionally, refer to the wiki on GitHub, especially the Tutorials there.

Installation

Python.NET is available as a source release on GitHub and as a platform-independent binary wheel or source distribution from the Python Package Index.

Installing from PyPI can be done using pip install pythonnet.

To build from source (either the sdist or clone or snapshot of the repository), only the .NET6 SDK (or newer) and Python itself are required. If dotnet is on the PATH, building can be done using

python setup.py build

Loading a Runtime

All runtimes supported by clr-loader can be used, which are

Mono (mono)

Default on Linux and macOS, supported on all platforms.

.NET Framework (netfx)

Default on Windows and also only supported there. Must be at least version 4.6.1, with 4.7.2 or later recommended. For .NET 4.6 support, the wheel has to be built with the environment variable PYTHONNET_BUILD_NET46_SUPPORT=1.

.NET Core (coreclr)

Self-contained is not supported, must be at least version 3.1.

The runtime must be configured before clr is imported, otherwise the default runtime will be initialized and used. Information on the runtime in use can be retrieved using pythonnet.get_runtime_info()).

A runtime can be selected in three different ways:

Calling pythonnet.load

The function pythonnet.load() can be called explicitly. A single string parameter (like load("coreclr") will select the respective runtime. All keyword arguments are passed to the underlying clr_loader.get_<runtime-name> function.

from pythonnet import load

load("coreclr", runtime_config="/path/to/runtimeconfig.json")

Note

All runtime implementations can be initialized without additional parameters. While previous versions of clr_loader required a runtimeconfig.json to load .NET Core, this requirement was lifted for the version used in pythonnet.

Via Environment Variables

The same configurability is exposed as environment variables.

PYTHONNET_RUNTIME

selects the runtime (e.g. PYTHONNET_RUNTIME=coreclr)

PYTHONNET_<RUNTIME>_<PARAM>

is passed on as a keyword argument (e.g. PYTHONNET_MONO_LIBMONO=/path/to/libmono.so)

The equivalent configuration to the load example would be

PYTHONNET_RUNTIME=coreclr
PYTHONNET_CORECLR_RUNTIME_CONFIG=/path/to/runtimeconfig.json

Note

Only string parameters are supported this way. It has the advantage, though, that the same configuration will be used for subprocesses as well.

Constructing a Runtime instance

The runtime can also be explicitly constructed using using the clr_loader.get_* factory functions, and then set up using pythonnet.set_runtime():

from pythonnet import set_runtime
from clr_loader import get_coreclr

rt = get_coreclr(runtime_config="/path/to/runtimeconfig.json")
set_runtime(rt)

This method is only recommended, if very fine-grained control over the runtime construction is required.

Importing Modules

Python.NET allows CLR namespaces to be treated essentially as Python packages.

from System import String
from System.Collections import *

Types from any loaded assembly may be imported and used in this manner. To load an assembly, use the AddReference function in the clr module:

import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Form

Note

Earlier releases of Python.NET relied on “implicit loading” to support automatic loading of assemblies whose names corresponded to an imported namespace. This is not supported anymore, all assemblies have to be loaded explicitly with AddReference.

Python.NET uses the PYTHONPATH (sys.path) to look for assemblies to load, in addition to the usual application base and the GAC (if applicable). To ensure that you can import an assembly, put the directory containing the assembly in sys.path.

Interacting with .NET

Using Classes

Python.NET allows you to use any non-private classes, structs, interfaces, enums or delegates from Python. To create an instance of a managed class, you use the standard instantiation syntax, passing a set of arguments that match one of its public constructors:

from System.Drawing import Point

p = Point(5, 5)

In many cases, Python.NET can determine the correct constructor to call automatically based on the arguments. In some cases, it may be necessary to call a particular overloaded constructor, which is supported by a special __overloads__ attribute.

Note

For compatibility with IronPython, the same functionality is available with the Overloads attribute.

from System import String, Char, Int32

s = String.Overloads[Char, Int32]('A', 10)
s = String.__overloads__[Char, Int32]('A', 10)

Using Generics

Pythonnet also supports generic types. A generic type must be bound to create a concrete type before it can be instantiated. Generic types support the subscript syntax to create bound types:

from System.Collections.Generic import Dictionary
from System import *

dict1 = Dictionary[String, String]()
dict2 = Dictionary[String, Int32]()
dict3 = Dictionary[String, Type]()

Note