A key goal for this project has been that Python.NET should “work justthe 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 pythoninterpreter by following along with the examples in this document. Ifyou get stuck, there are also a number of demos and unit tests locatedin the source directory of the distribution that can be helpful asexamples. Additionally, refer to thewiki onGitHub, especially theTutorials there.
Python.NET is available as a source release onGitHub and as aplatform-independent binary wheel or source distribution from thePythonPackage Index.
Installing from PyPI can be done usingpipinstallpythonnet
.
To build from source (either thesdist
or clone or snapshot of therepository), only the .NET6 SDK (or newer) and Python itself are required. Ifdotnet
is on thePATH
, building can be done using
pythonsetup.pybuild
All runtimes supported by clr-loader can be used, which are
mono
)Default on Linux and macOS, supported on all platforms.
netfx
)Default on Windows and also only supported there. Must be at least version4.7.2.
coreclr
)Self-contained is not supported, must be at least version 3.1.
The runtime must be configuredbeforeclr
is imported, otherwise thedefault runtime will be initialized and used. Information on the runtime in usecan be retrieved usingpythonnet.get_runtime_info()
).
A runtime can be selected in three different ways:
pythonnet.load
¶The functionpythonnet.load()
can be called explicitly. A singlestring parameter (likeload("coreclr")
will select the respective runtime.All keyword arguments are passed to the underlyingclr_loader.get_<runtime-name>
function.
frompythonnetimportloadload("coreclr",runtime_config="/path/to/runtimeconfig.json")
Note
All runtime implementations can be initialized without additional parameters.While previous versions ofclr_loader
required aruntimeconfig.json
to load .NET Core, this requirement was lifted for the version used inpythonnet
.
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 theload
example would be
PYTHONNET_RUNTIME=coreclrPYTHONNET_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.
Runtime
instance¶The runtime can also be explicitly constructed using using theclr_loader.get_*
factory functions, and then set up usingpythonnet.set_runtime()
:
frompythonnetimportset_runtimefromclr_loaderimportget_coreclrrt=get_coreclr(runtime_config="/path/to/runtimeconfig.json")set_runtime(rt)
This method is only recommended, if very fine-grained control over the runtimeconstruction is required.
Python.NET allows CLR namespaces to be treated essentially as Pythonpackages.
fromSystemimportStringfromSystem.Collectionsimport*
Types from any loaded assembly may be imported and used in this manner.To load an assembly, use theAddReference
function in theclr
module:
importclrclr.AddReference("System.Windows.Forms")fromSystem.Windows.FormsimportForm
Note
Earlier releases of Python.NET relied on “implicit loading” tosupport automatic loading of assemblies whose names corresponded to animported namespace. This is not supported anymore, all assemblies have to beloaded explicitly withAddReference
.
Python.NET uses the PYTHONPATH (sys.path
) to look for assemblies to load, inaddition to the usual application base and the GAC (if applicable). To ensurethat you can import an assembly, put the directory containing the assembly insys.path
.
Python.NET allows you to use any non-private classes, structs,interfaces, enums or delegates from Python. To create an instance of amanaged class, you use the standard instantiation syntax, passing a setof arguments that match one of its public constructors:
fromSystem.DrawingimportPointp=Point(5,5)
In many cases, Python.NET can determine the correct constructor to callautomatically based on the arguments. In some cases, it may be necessaryto call a particular overloaded constructor, which is supported by aspecial__overloads__
attribute.
Note
For compatibility with IronPython, the same functionality is available withtheOverloads
attribute.
fromSystemimportString,Char,Int32s=String.Overloads[Char,Int32]('A',10)s=String.__overloads__[Char,Int32]('A',10)
Pythonnet also supports generic types. A generic type must be bound tocreate a concrete type before it can be instantiated. Generic typessupport the subscript syntax to create bound types:
fromSystem.Collections.GenericimportDictionaryfromSystemimport*dict1=Dictionary[String,String]()dict2=Dictionary[String,Int32]()dict3=Dictionary[String,Type]()
Note
For backwards-compatibility reasons, this will also work with some nativePython types which are mapped to corresponding .NET types (in particularstr->System.String
andint->System.Int32
). Since these mappingsare not really one-to-one and can lead to surprising results, use of thisfunctionality is discouraged and will generate a warning in the future.
Managed classes can also be subclassed in Python, though members of thePython subclass are not visible to .NET code. See thehelloform.py
file in the/demo
directory of the distribution for a simple WindowsForms example that demonstrates subclassing a managed class.
You can get and set fields and properties of CLR objects just as if theywere regular attributes:
fromSystemimportEnvironmentname=Environment.MachineNameEnvironment.ExitCode=1
If a managed object implements one or more indexers, one can call theindexer using standard Python indexing syntax:
fromSystem.CollectionsimportHashtabletable=Hashtable()table["key 1"]="value 1"
Overloaded indexers are supported, using the same notation one would usein C#:
items[0,2]items[0,2,3]
Methods of CLR objects behave generally like normal Python methods.Static methods may be called either through the class or through aninstance of the class. All public and protected methods of CLR objectsare accessible to Python:
fromSystemimportEnvironmentdrives=Environment.GetLogicalDrives()
It is also possible to call managed methods “unbound” (passing theinstance as the first argument) just as with Python methods. This ismost often used to explicitly call methods of a base class.
Note
There is one caveat related to calling unbound methods: it ispossible for a managed class to declare a static method and an instancemethod with the same name. Since it is not possible for the runtime toknow the intent when such a method is called unbound, the static methodwill always be called.
The docstring of CLR a method (__doc__
) can be used to view thesignature of the method, including overloads if the CLR method isoverloaded. You can also use the Pythonhelp
method to inspect amanaged class:
fromSystemimportEnvironmentprint(Environment.GetFolderPath.__doc__)help(Environment)
While Python.NET will generally be able to figure out the right versionof an overloaded method to call automatically, there are cases where itis desirable to select a particular method overload explicitly.
Like constructors, all CLR methods have a__overloads__
property to allowselecting particular overloads explicitly.
Note
For compatibility with IronPython, the same functionality is available withtheOverloads
attribute.
fromSystemimportConsole,Boolean,String,UInt32Console.WriteLine.__overloads__[Boolean](True)Console.WriteLine.Overloads[String]("string")Console.WriteLine.__overloads__[UInt32](42)
Similarly, generic methods may be bound at runtime using the subscriptsyntax directly on the method:
someobject.SomeGenericMethod[UInt32](10)someobject.SomeGenericMethod[String]("10")
When a managed method hasout
orref
parameters, the argumentsappear as normal arguments in Python, but the return value of the methodis modified. There are 3 cases:
If the method isvoid
and has oneout
orref
parameter,the method returns the value of that parameter to Python. Forexample, ifsomeobject
has a managed method with signaturevoidSomeMethod1(outarg)
, it is called like so:
new_arg=someobject.SomeMethod1(arg)
where the value ofarg
is ignored, but its type is used for overloadresolution.
If the method isvoid
and has multipleout
/ref
parameters, the method returns a tuple containing theout
/ref
parameter values. For example, ifsomeobject
has a managed methodwith signaturevoidSomeMethod2(outarg,refarg2)
, it is calledlike so:
new_arg,new_arg2=someobject.SomeMethod2(arg,arg2)
Otherwise, the method returns a tuple containing the return valuefollowed by theout
/ref
parameter values. For example:
found,new_value=dictionary.TryGetValue(key,value)
Delegates defined in managed code can be implemented in Python. Adelegate type can be instantiated and passed a callable Python object toget a delegate instance. The resulting delegate instance is a truemanaged delegate that will invoke the given Python callable when it iscalled:
defmy_handler(source,args):print('my_handler called!')# instantiate a delegated=AssemblyLoadEventHandler(my_handler)# use it as an event handlerAppDomain.CurrentDomain.AssemblyLoad+=d
Delegates without
orref
parameters can be implemented inPython by following the convention described inOut and Refparameters.
Multicast delegates can be implemented by adding more callable objectsto a delegate instance:
d+=self.method1d+=self.method2d()
Events are treated as first-class objects in Python, and behave in manyways like methods. Python callbacks can be registered with eventattributes, and an event can be called to fire the event.
Note that events support a convenience spelling similar to that used inC#. You do not need to pass an explicitly instantiated delegate instanceto an event (though you can if you want). Events support the+=
and-=
operators in a way very similar to the C# idiom:
defhandler(source,args):print('my_handler called!')# register event handlerobject.SomeEvent+=handler# unregister event handlerobject.SomeEvent-=handler# fire the eventresult=object.SomeEvent(...)
Managed exceptions can be raised and caught in the same way as ordinary Pythonexceptions:
fromSystemimportNullReferenceExceptiontry:raiseNullReferenceException("aiieee!")exceptNullReferenceExceptionase:print(e.Message)print(e.Source)
The typeSystem.Array
supports the subscript syntax in order to makeit easy to create managed arrays from Python:
fromSystemimportArray,Int32myarray=Array[Int32](10)
Managed arrays support the standard Python sequence protocols:
items=SomeObject.GetArray()# Get first itemv=items[0]items[0]=v# Get last itemv=items[-1]items[-1]=v# Get lengthl=len(items)# Containment testtest=vinitems
Multidimensional arrays support indexing using the same notation onewould use in C#:
items[0,2]items[0,2,3]
Managed arrays and managed objects that implement theIEnumerable
orIEnumerable<T>
interface can be iterated over using the standard iterationPython idioms:
domain=System.AppDomain.CurrentDomainforitemindomain.GetAssemblies():name=item.GetName()
Type conversion under Python.NET is fairly straightforward - mostelemental Python types (string, int, long, etc.) convert automaticallyto compatible managed equivalents (String, Int32, etc.) and vice-versa.
Custom type conversions can be implemented asCodecs.
Types that do not have a logical equivalent in Python are exposed asinstances of managed classes or structs (System.Decimal is an example).
The .NET architecture makes a distinction betweenvaluetypes
andreferencetypes
. Reference types are allocated on the heap, andvalue types are allocated either on the stack or in-line within anobject.
A process calledboxing
is used in .NET to allow code to treat avalue type as if it were a reference type. Boxing causes a separate copyof the value type object to be created on the heap, which then hasreference type semantics.
Understanding boxing and the distinction between value types andreference types can be important when using Python.NET because thePython language has no value type semantics or syntax - in Python“everything is a reference”.
Here is a simple example that demonstrates an issue. If you are anexperienced C# programmer, you might write the following code:
items=System.Array.CreateInstance(Point,3)foriinrange(3):items[i]=Point(0,0)items[0].X=1# won't work!!
While the spelling ofitems[0].X=1
is the same in C# and Python,there is an important and subtle semantic difference. In C# (and othercompiled-to-IL languages), the compiler knows that Point is a value typeand can do the Right Thing here, changing the value in place.
In Python however, “everything’s a reference”, and there is really nospelling or semantic to allow it to do the right thing dynamically. Thespecific reason thatitems[0]
itself doesn’t change is that when yousayitems[0]
, that getitem operation creates a Python object thatholds a reference to the object atitems[0]
via a GCHandle. Thatcauses a ValueType (like Point) to be boxed, so the following setattr(.X=1
)changes the state of the boxed value, not the originalunboxed value.
The rule in Python is essentially:
the result of any attribute or item access is a boxed value
and that can be important in how you approach your code.
Because there are no value type semantics or syntax in Python, you mayneed to modify your approach. To revisit the previous example, we canensure that the changes we want to make to an array item aren’t “lost”by resetting an array member after making changes to it:
items=System.Array.CreateInstance(Point,3)foriinrange(3):items[i]=Point(0,0)# This _will_ work. We get 'item' as a boxed copy of the Point# object actually stored in the array. After making our changes# we re-set the array item to update the bits in the array.item=items[0]item.X=1items[0]=item
This is not unlike some of the cases you can find in C# where you haveto know about boxing behavior to avoid similar kinds oflostupdate
problems (generally because an implicit boxing happened that was nottaken into account in the code).
This is the same thing, just the manifestation is a little different inPython. See the .NET documentation for more details on boxing and thedifferences between value types and reference types.