C# Reference¶
- class Py¶
Public Static Functions
- class DebugGILState : public Py.GILState¶
- class GILState : public IDisposable¶
Subclassed by Py.DebugGILState
- class Python.Runtime.PythonEngine : IDisposable¶
This class provides the public interface of the Python runtime.
Public Functions
- delegate void ShutdownHandler ()¶
Called when the engine is shut down.
Shutdown handlers are run in reverse order they were added, so that resources available when running a shutdown handler are the same as what was available when it was added.
Properties
- bool DebugGIL { get; set; } = false¶
Set to
true
to enable GIL debugging assistance.
Public Static Functions
- void SetNoSiteFlag ()¶
Set the NoSiteFlag to disable loading the site module. Must be called before Initialize. https://docs.python.org/3/c-api/init.html#c.Py_NoSiteFlag
- void Initialize (IEnumerable<string> args, bool setSysArgv = true, bool initSigs = false)¶
Initialize Method
Initialize the Python runtime. It is safe to call this method more than once, though initialization will only happen on the first call. It is not necessary to hold the Python global interpreter lock (GIL) to call this method. initSigs can be set to 1 to do default python signal configuration. This will override the way signals are handled by the application.
- IntPtr InitExt ()¶
A helper to perform initialization from the context of an active CPython interpreter process - this bootstraps the managed runtime when it is imported by the CLR extension module.
- void Shutdown ()¶
Shutdown and release resources held by the Python runtime. The Python runtime can no longer be used in the current process after calling the Shutdown method.
- void AddShutdownHandler (ShutdownHandler handler)¶
Add a function to be called when the engine is shut down.
Shutdown handlers are executed in the opposite order they were added, so that you can be sure that everything that was initialized when you added the handler is still initialized when you need to shut down.
If the same shutdown handler is added several times, it will be run several times.
Don’t add shutdown handlers while running a shutdown handler.
- void RemoveShutdownHandler (ShutdownHandler handler)¶
Remove a shutdown handler.
If the same shutdown handler is added several times, only the last one is removed.
Don’t remove shutdown handlers while running a shutdown handler.
- unsafe IntPtr BeginAllowThreads ()¶
BeginAllowThreads Method
Release the Python global interpreter lock to allow other threads to run. This is equivalent to the Py_BEGIN_ALLOW_THREADS macro provided by the C Python API. For more information, see the “Extending and Embedding” section of the Python documentation on www.python.org.
- unsafe void EndAllowThreads (IntPtr ts)¶
EndAllowThreads Method
Re-aquire the Python global interpreter lock for the current thread. This is equivalent to the Py_END_ALLOW_THREADS macro provided by the C Python API. For more information, see the “Extending and Embedding” section of the Python documentation on www.python.org.
- PyObject Eval (string code, PyDict? globals = null, PyObject? locals = null)¶
Eval Method
Evaluate a Python expression and returns the result. It’s a subset of Python eval function.
- void Exec (string code, PyDict? globals = null, PyObject? locals = null)¶
Exec Method
Run a string containing Python code. It’s a subset of Python exec function.
- ulong GetPythonThreadID ()¶
Gets the Python thread ID.
- Return:
The Python thread ID.
- int Interrupt (ulong pythonThreadID)¶
Interrupts the execution of a thread.
- Param pythonThreadID:
The Python thread ID.
- Return:
The number of thread states modified; this is normally one, but will be zero if the thread id is not found.
- class Python.Runtime.PyObject : DynamicObject, IDisposable, ISerializable¶
Represents a generic Python object. The methods of this class are generally equivalent to the Python “abstract object API”. See PY2: https://docs.python.org/2/c-api/object.html PY3: https://docs.python.org/3/c-api/object.html for details.
Subclassed by Python.Runtime.NullOnly, Python.Runtime.PyIter, Python.Runtime.PyIterable, Python.Runtime.PyModule, Python.Runtime.PyNumber, Python.Runtime.PyType
Public Functions
- object? AsManagedObject (Type t)¶
AsManagedObject Method
Return a managed object of the given type, based on the value of the Python object.
- T As<T> ()¶
Return a managed object of the given type, based on the value of the Python object.
- void Dispose ()¶
The Dispose method provides a way to explicitly release the Python object represented by a PyObject instance. It is a good idea to call Dispose on PyObjects that wrap resources that are limited or need strict lifetime control. Otherwise, references to Python objects will not be released until a managed garbage collection occurs.
- PyType GetPythonType ()¶
GetPythonType Method
Returns the Python type of the object. This method is equivalent to the Python expression: type(object).
- bool TypeCheck (PyType typeOrClass)¶
TypeCheck Method
Returns true if the object o is of type typeOrClass or a subtype of typeOrClass.
- bool HasAttr (string name)¶
HasAttr Method
Returns true if the object has an attribute with the given name.
- bool HasAttr (PyObject name)
HasAttr Method
Returns true if the object has an attribute with the given name, where name is a PyObject wrapping a string or unicode object.
- PyObject GetAttr (string name)¶
GetAttr Method
Returns the named attribute of the Python object, or raises a PythonException if the attribute access fails.
- PyObject GetAttr (string name, PyObject _default)
Returns the named attribute of the Python object, or the given default object if the attribute access throws AttributeError.
This method ignores any AttrubiteError(s), even ones not raised due to missing requested attribute.
For example, if attribute getter calls other Python code, and that code happens to cause AttributeError elsewhere, it will be ignored and _default value will be returned instead.
- Param name:
Name of the attribute.
- Param _default:
The object to return on AttributeError.
- PyObject GetAttr (PyObject name)
GetAttr Method
Returns the named attribute of the Python object or raises a PythonException if the attribute access fails. The name argument is a PyObject wrapping a Python string or unicode object.
- PyObject GetAttr (PyObject name, PyObject _default)
Returns the named attribute of the Python object, or the given default object if the attribute access throws AttributeError.
This method ignores any AttrubiteError(s), even ones not raised due to missing requested attribute.
For example, if attribute getter calls other Python code, and that code happens to cause AttributeError elsewhere, it will be ignored and _default value will be returned instead.
- Param name:
Name of the attribute. Must be of Python type ‘str’.
- Param _default:
The object to return on AttributeError.
- void SetAttr (string name, PyObject value)¶
SetAttr Method
Set an attribute of the object with the given name and value. This method throws a PythonException if the attribute set fails.
- void SetAttr (PyObject name, PyObject value)
SetAttr Method
Set an attribute of the object with the given name and value, where the name is a Python string or unicode object. This method throws a PythonException if the attribute set fails.
- void DelAttr (string name)¶
DelAttr Method
Delete the named attribute of the Python object. This method throws a PythonException if the attribute set fails.
- void DelAttr (PyObject name)
DelAttr Method
Delete the named attribute of the Python object, where name is a PyObject wrapping a Python string or unicode object. This method throws a PythonException if the attribute set fails.
- PyObject GetItem (PyObject key)¶
GetItem Method
For objects that support the Python sequence or mapping protocols, return the item at the given object index. This method raises a PythonException if the indexing operation fails.
- PyObject GetItem (string key)
GetItem Method
For objects that support the Python sequence or mapping protocols, return the item at the given string index. This method raises a PythonException if the indexing operation fails.
- PyObject GetItem (int index)
GetItem Method
For objects that support the Python sequence or mapping protocols, return the item at the given numeric index. This method raises a PythonException if the indexing operation fails.
- void SetItem (PyObject key, PyObject value)¶
SetItem Method
For objects that support the Python sequence or mapping protocols, set the item at the given object index to the given value. This method raises a PythonException if the set operation fails.
- void SetItem (string key, PyObject value)
SetItem Method
For objects that support the Python sequence or mapping protocols, set the item at the given string index to the given value. This method raises a PythonException if the set operation fails.
- void SetItem (int index, PyObject value)
SetItem Method
For objects that support the Python sequence or mapping protocols, set the item at the given numeric index to the given value. This method raises a PythonException if the set operation fails.
- void DelItem (PyObject key)¶
DelItem Method
For objects that support the Python sequence or mapping protocols, delete the item at the given object index. This method raises a PythonException if the delete operation fails.
- void DelItem (string key)
DelItem Method
For objects that support the Python sequence or mapping protocols, delete the item at the given string index. This method raises a PythonException if the delete operation fails.
- void DelItem (int index)
DelItem Method
For objects that support the Python sequence or mapping protocols, delete the item at the given numeric index. This method raises a PythonException if the delete operation fails.
- long Length ()¶
Returns the length for objects that support the Python sequence protocol.
- PyIter GetIterator ()¶
Return a new (Python) iterator for the object. This is equivalent to the Python expression “iter(object)”.
- Throws PythonException:
Thrown if the object can not be iterated.
- PyObject Invoke (params PyObject[] args)¶
Invoke Method
Invoke the callable object with the given arguments, passed as a PyObject[]. A PythonException is raised if the invocation fails.
- PyObject Invoke (PyTuple args)
Invoke Method
Invoke the callable object with the given arguments, passed as a Python tuple. A PythonException is raised if the invocation fails.
- PyObject Invoke (PyObject[] args, PyDict? kw)
Invoke Method
Invoke the callable object with the given positional and keyword arguments. A PythonException is raised if the invocation fails.
- PyObject Invoke (PyTuple args, PyDict? kw)
Invoke Method
Invoke the callable object with the given positional and keyword arguments. A PythonException is raised if the invocation fails.
- PyObject InvokeMethod (string name, params PyObject[] args)¶
InvokeMethod Method
Invoke the named method of the object with the given arguments. A PythonException is raised if the invocation is unsuccessful.
- PyObject InvokeMethod (string name, PyTuple args)
InvokeMethod Method
Invoke the named method of the object with the given arguments. A PythonException is raised if the invocation is unsuccessful.
- PyObject InvokeMethod (PyObject name, params PyObject[] args)
InvokeMethod Method
Invoke the named method of the object with the given arguments. A PythonException is raised if the invocation is unsuccessful.
- PyObject InvokeMethod (PyObject name, PyTuple args)
InvokeMethod Method
Invoke the named method of the object with the given arguments. A PythonException is raised if the invocation is unsuccessful.
- PyObject InvokeMethod (string name, PyObject[] args, PyDict? kw)
InvokeMethod Method
Invoke the named method of the object with the given arguments and keyword arguments. Keyword args are passed as a PyDict object. A PythonException is raised if the invocation is unsuccessful.
- PyObject InvokeMethod (string name, PyTuple args, PyDict? kw)
InvokeMethod Method
Invoke the named method of the object with the given arguments and keyword arguments. Keyword args are passed as a PyDict object. A PythonException is raised if the invocation is unsuccessful.
- bool IsInstance (PyObject typeOrClass)¶
IsInstance Method
Return true if the object is an instance of the given Python type or class. This method always succeeds.
- bool IsSubclass (PyObject typeOrClass)¶
Return
true
if the object is identical to or derived from the given Python type or class. This method always succeeds.
- bool IsCallable ()¶
IsCallable Method
Returns true if the object is a callable object. This method always succeeds.
- bool IsIterable ()¶
IsIterable Method
Returns true if the object is iterable object. This method always succeeds.
- bool IsTrue ()¶
IsTrue Method
Return true if the object is true according to Python semantics. This method always succeeds.
- bool IsNone ()¶
Return true if the object is None
- PyList Dir ()¶
Dir Method
Return a list of the names of the attributes of the object. This is equivalent to the Python expression “dir(object)”.
- string? Repr ()¶
Repr Method
Return a string representation of the object. This method is the managed equivalent of the Python expression “repr(object)”.
- override? string ToString ()
ToString Method
Return the string representation of the object. This method is the managed equivalent of the Python expression “str(object)”.
- override bool Equals (object o)¶
Equals Method
Return true if this object is equal to the given object. This method is based on Python equality semantics.
- override int GetHashCode ()¶
GetHashCode Method
Return a hashcode based on the Python object. This returns the hash as computed by Python, equivalent to the Python expression “hash(obj)”.
- PyBuffer GetBuffer (PyBUF flags = PyBUF.SIMPLE)¶
GetBuffer Method. This Method only works for objects that have a buffer (like “bytes”, “bytearray” or “array.array”)
Send a request to the PyObject to fill in view as specified by flags. If the PyObject cannot provide a buffer of the exact type, it MUST raise PyExc_BufferError, set view->obj to NULL and return -1. On success, fill in view, set view->obj to a new reference to exporter and return 0. In the case of chained buffer providers that redirect requests to a single object, view->obj MAY refer to this object instead of exporter(See Buffer Object Structures). Successful calls to PyObject.GetBuffer must be paired with calls to PyBuffer.Dispose(), similar to malloc() and free(). Thus, after the consumer is done with the buffer, PyBuffer.Dispose() must be called exactly once.
- override IEnumerable<string> GetDynamicMemberNames ()¶
Returns the enumeration of all dynamic member names.
This method exists for debugging purposes only.
- Return:
A sequence that contains dynamic member names.
Properties
- IntPtr Handle { get; set; }¶
Gets the native handle of the underlying Python object. This value is generally for internal use by the PythonNet runtime.
- PyObject this[string key] {get;set;}
String Indexer
Provides a shorthand for the string versions of the GetItem and SetItem methods.
- PyObject this[PyObject key] {get;set;}
PyObject Indexer
Provides a shorthand for the object versions of the GetItem and SetItem methods.
- PyObject this[int index] {get;set;}
Numeric Indexer
Provides a shorthand for the numeric versions of the GetItem and SetItem methods.
- class Python.Runtime.PyDict : Python.Runtime.PyIterable¶
Represents a Python dictionary object. See the documentation at PY2: https://docs.python.org/2/c-api/dict.html PY3: https://docs.python.org/3/c-api/dict.html for details.
Public Functions
- PyDict ()¶
Creates a new Python dictionary object.
- PyDict (PyObject o)
Wraps existing dictionary object.
- Throws ArgumentException:
Thrown if the given object is not a Python dictionary object
- bool HasKey (string key)
HasKey Method
Returns true if the string key appears in the dictionary.
- PyIterable Keys ()¶
Keys Method
Returns a sequence containing the keys of the dictionary.
- PyIterable Values ()¶
Values Method
Returns a sequence containing the values of the dictionary.
- PyIterable Items ()¶
Items Method
Returns a sequence containing the items of the dictionary.
- void Clear ()¶
Clear Method
Clears the dictionary.
- class Python.Runtime.PyTuple : Python.Runtime.PySequence¶
Represents a Python tuple object. See the documentation at PY2: https://docs.python.org/2/c-api/tupleObjects.html PY3: https://docs.python.org/3/c-api/tupleObjects.html for details.
Public Functions
- PyTuple (PyObject o)¶
PyTuple Constructor
Copy constructor - obtain a PyTuple from a generic PyObject. An ArgumentException will be thrown if the given object is not a Python tuple object.
- PyTuple (PyObject[] items)
PyTuple Constructor
Creates a new PyTuple from an array of PyObject instances.
See caveats about PyTuple_SetItem: https://www.coursehero.com/file/p4j2ogg/important-exceptions-to-this-rule-PyTupleSetItem-and-PyListSetItem-These/
Public Static Functions
- class Python.Runtime.PyList : Python.Runtime.PySequence¶
Represents a standard Python list object. See the documentation at PY2: https://docs.python.org/2/c-api/list.html PY3: https://docs.python.org/3/c-api/list.html for details.
Public Functions
- PyList (PyObject o)¶
PyList Constructor
Copy constructor - obtain a PyList from a generic PyObject. An ArgumentException will be thrown if the given object is not a Python list object.
- PyList ()
Creates a new empty Python list object.
- PyList (PyObject[] items)
Creates a new Python list object from an array of objects.
- void Reverse ()¶
Reverse Method
Reverse the order of the list object in place.
- void Sort ()¶
Sort Method
Sort the list in place.
Public Static Functions
- class Python.Runtime.PyInt : Python.Runtime.PyNumber, IFormattable¶
Represents a Python integer object. See the documentation at https://docs.python.org/3/c-api/long.html
Public Functions
- PyInt (PyObject o)¶
PyInt Constructor
Copy constructor - obtain a PyInt from a generic PyObject. An ArgumentException will be thrown if the given object is not a Python int object.
- PyInt (int value)
PyInt Constructor
Creates a new Python int from an int32 value.
- PyInt (uint value)
PyInt Constructor
Creates a new Python int from a uint32 value.
- PyInt (long value)
PyInt Constructor
Creates a new Python int from an int64 value.
- PyInt (ulong value)
Creates a new Python int from a UInt64 value.
- PyInt (short value)
PyInt Constructor
Creates a new Python int from an int16 value.
- PyInt (ushort value)
PyInt Constructor
Creates a new Python int from a uint16 value.
- PyInt (byte value)
PyInt Constructor
Creates a new Python int from a byte value.
- PyInt (sbyte value)
PyInt Constructor
Creates a new Python int from an sbyte value.
- PyInt (string value)
PyInt Constructor
Creates a new Python int from a string value.
- short ToInt16 ()¶
ToInt16 Method
Return the value of the Python int object as an int16.
- int ToInt32 ()¶
Return the value of the Python int object as an Int32.
- long ToInt64 ()¶
ToInt64 Method
Return the value of the Python int object as an int64.
Public Static Functions
- class Python.Runtime.PyString : Python.Runtime.PySequence, IComparable<string>, IEquatable<string>¶
Represents a Python (ANSI) string object. See the documentation at PY2: https://docs.python.org/2/c-api/string.html PY3: No Equivalent for details.
2011-01-29: …Then why does the string constructor call PyUnicode_FromUnicode()???
- class Python.Runtime.PyType : Python.Runtime.PyObject¶
Public Functions
- PyType (PyObject o)
Wraps an existing type object.
Properties
- bool IsReady { get; set; }¶
Returns
true
when type is fully initialized
- class Python.Runtime.PyModule : Python.Runtime.PyObject¶
Public Functions
- void Import (PyModule module, string asname)
Import module as a variable of given name.
- void Import (PyObject module, string? asname = null)
The ‘import .. as ..’ statement in Python. Import a module as a variable.
- void ImportAll (PyObject module)
Import all variables of the module into this module.
- void ImportAll (PyDict dict)
Import all variables in the dictionary into this module.
- PyObject Execute (PyObject script, PyDict? locals = null)¶
Execute method
Execute a Python ast and return the result as a PyObject. The ast can be either an expression or stmts.
- T? Execute<T> (PyObject script, PyDict? locals = null)
Execute a Python ast and return the result as a PyObject, and convert the result to a Managed Object of given type. The ast can be either an expression or stmts.
- PyObject Eval (string code, PyDict? locals = null)¶
Evaluate a Python expression and return the result as a PyObject.
- T? Eval<T> (string code, PyDict? locals = null)
Evaluate a Python expression
Evaluate a Python expression and convert the result to a Managed Object of given type.
- PyModule Exec (string code, PyDict? locals = null)¶
Exec Method
Exec a Python script and save its local variables in the current local variable dict.
- PyModule Set (string name, object? value)¶
Set Variable Method
Add a new variable to the variables dict if it not exist or update its value if the variable exists.
- bool Contains (string name)¶
Returns true if the variable exists in the module.
- PyObject Get (string name)¶
Returns the value of the variable with the given name.
- Throws KeyNotFoundException:
Thrown when variable with the given name does not exist.
- bool TryGet (string name, out PyObject? value)¶
TryGet Method
Returns the value of the variable, local variable first. If the variable does not exist, return null.
- T Get<T> (string name)
Get Method
Obtain the value of the variable of given name, and convert the result to a Managed Object of given type. If the variable does not exist, throw an Exception.
- bool TryGet<T> (string name, out T? value)
TryGet Method
Obtain the value of the variable of given name, and convert the result to a Managed Object of given type. If the variable does not exist, return false.
Public Static Functions
- PyObject Import (string name)
Given a module or package name, import the module and return the resulting object.
- Param name:
Fully-qualified module or package name
- class Python.Runtime.PyIter : Python.Runtime.PyObject, IEnumerator<PyObject>¶
Represents a standard Python iterator object. See the documentation at PY2: https://docs.python.org/2/c-api/iterator.html PY3: https://docs.python.org/3/c-api/iterator.html for details.
Public Functions
- class Python.Runtime.PyBuffer : IDisposable¶
Public Functions
- bool IsContiguous (BufferOrderStyle order)¶
Returns true if the memory defined by the view is C-style (order is ‘C’) or Fortran-style (order is ‘F’) contiguous or either one (order is ‘A’). Returns false otherwise.
- Param order:
C-style (order is ‘C’) or Fortran-style (order is ‘F’) contiguous or either one (order is ‘A’)
- IntPtr GetPointer (long[] indices)¶
Get the memory area pointed to by the indices inside the given view. indices must point to an array of view->ndim indices.
- void FromContiguous (IntPtr buf, long len, BufferOrderStyle fort)¶
Copy contiguous len bytes from buf to view. fort can be ‘C’ or ‘F’ (for C-style or Fortran-style ordering).
- void ToContiguous (IntPtr buf, BufferOrderStyle order)¶
Copy len bytes from view to its contiguous representation in buf. order can be ‘C’ or ‘F’ or ‘A’ (for C-style or Fortran-style ordering or either one). 0 is returned on success, -1 on error.
- Param order:
order can be ‘C’ or ‘F’ or ‘A’ (for C-style or Fortran-style ordering or either one).
- Param buf:
Buffer to copy to
- void Write (byte[] buffer, int sourceOffset, int count, nint destinationOffset)¶
Writes a managed byte array into the buffer of a python object. This can be used to pass data like images from managed to python.
- void Read (byte[] buffer, int destinationOffset, int count, nint sourceOffset)¶
Reads the buffer of a python object into a managed byte array. This can be used to pass data like images from python to managed.
- void Dispose ()¶
Release the buffer view and decrement the reference count for view->obj. This function MUST be called when the buffer is no longer being used, otherwise reference leaks may occur. It is an error to call this function on a buffer that was not obtained via PyObject.GetBuffer.
Properties
- long?[] Shape {get;set;}
An array of length Dimensions indicating the shape of the memory as an n-dimensional array.
- long?[] Strides {get;set;}
An array of length Dimensions giving the number of bytes to skip to get to a new element in each dimension. Will be null except when PyBUF_STRIDES or PyBUF_INDIRECT flags in GetBuffer/>.
- long?[] SubOffsets {get;set;}
An array of Py_ssize_t of length ndim. If suboffsets[n] >= 0, the values stored along the nth dimension are pointers and the suboffset value dictates how many bytes to add to each pointer after de-referencing. A suboffset value that is negative indicates that no de-referencing should occur (striding in a contiguous memory block).
Public Static Functions
- long SizeFromFormat (string format)¶
Return the implied itemsize from format. On error, raise an exception and return -1. New in version 3.9.
- class Python.Runtime.PyIterable : Python.Runtime.PyObject, IEnumerable<PyObject>¶
Subclassed by Python.Runtime.PyDict, Python.Runtime.PySequence
- class Python.Runtime.PySequence : Python.Runtime.PyIterable¶
Represents a generic Python sequence. The methods of this class are equivalent to the Python “abstract sequence API”. See PY2: https://docs.python.org/2/c-api/sequence.html PY3: https://docs.python.org/3/c-api/sequence.html for details.
Subclassed by Python.Runtime.PyList, Python.Runtime.PyString, Python.Runtime.PyTuple
Public Functions
- PySequence (PyObject o)¶
Creates new instance from an existing object.
- Throws ArgumentException:
o does not provide sequence protocol
- void DelSlice (int i1, int i2)¶
DelSlice Method
Deletes the slice of the sequence with the given indices.
- nint Index (PyObject item)¶
Return the index of the given item in the sequence, or -1 if the item does not appear in the sequence.
- int Index32 (PyObject item)¶
Return the index of the given item in the sequence, or -1 if the item does not appear in the sequence.
- long Index64 (PyObject item)¶
Return the index of the given item in the sequence, or -1 if the item does not appear in the sequence.
- bool Contains (PyObject item)¶
Return true if the sequence contains the given item. This method throws a PythonException if an error occurs during the check.
- class Python.Runtime.PyNumber : Python.Runtime.PyObject¶
Represents a generic Python number. The methods of this class are equivalent to the Python “abstract number API”. See PY3: https://docs.python.org/3/c-api/number.html for details.
TODO: add all of the PyNumber_XXX methods.
Subclassed by Python.Runtime.PyFloat, Python.Runtime.PyInt