Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
13eb3e3
Keep the Python object of a __namespace__ subclass of a .NET exception
quantconnect-kronos[bot] Nov 17, 2026
b2cafc0
Release __namespace__ exception subclasses safely
quantconnect-kronos[bot] Nov 17, 2026
d872f73
Raise errors from Message overrides in exception repr() and __init__
quantconnect-kronos[bot] Nov 17, 2026
e9ebba4
Keep exception formatting and its override errors inside the slot guards
quantconnect-kronos[bot] Nov 17, 2026
87cc5f4
Release a derived object's Python object after its base finalizers
quantconnect-kronos[bot] Nov 17, 2026
d62a333
Unwrap every reflection wrapper of an exception slot's error
quantconnect-kronos[bot] Nov 27, 2026
a476458
Reuse a derived exception's Python object as another exception's cause
quantconnect-kronos[bot] Nov 27, 2026
6815e63
Give a derived object back to Python a new wrapper after .NET GC coll…
quantconnect-kronos[bot] Nov 27, 2026
314a259
Keep a derived object's wrapper, args and release right across .NET c…
quantconnect-kronos[bot] Nov 27, 2026
47cac36
Restore a derived exception's args only when converting it, and raise…
quantconnect-kronos[bot] Nov 27, 2026
7353259
Revert "Restore a derived exception's args only when converting it, a…
quantconnect-kronos[bot] Nov 27, 2026
a7e8c6f
Revert "Keep a derived object's wrapper, args and release right acros…
quantconnect-kronos[bot] Nov 27, 2026
e25aba3
Revert "Give a derived object back to Python a new wrapper after .NET…
quantconnect-kronos[bot] Nov 27, 2026
a6afc1c
Revert "Reuse a derived exception's Python object as another exceptio…
quantconnect-kronos[bot] Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions src/runtime/ClassManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,17 +190,19 @@ internal static ClassBase CreateClass(Type type)
impl = new InterfaceObject(type);
}

else if (type == typeof(Exception) ||
type.IsSubclassOf(typeof(Exception)))
{
impl = new ExceptionClassObject(type);
}

#pragma warning disable CS0618 // Type or member is obsolete. OK for internal use.
else if (null != PythonDerivedType.GetPyObjField(type))
#pragma warning restore CS0618 // Type or member is obsolete
{
impl = new ClassDerivedObject(type);
impl = type.IsSubclassOf(typeof(Exception))
? new ExceptionClassDerivedObject(type)
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved
: new ClassDerivedObject(type);
}

else if (type == typeof(Exception) ||
type.IsSubclassOf(typeof(Exception)))
{
impl = new ExceptionClassObject(type);
}

else if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type))
Expand Down
14 changes: 11 additions & 3 deletions src/runtime/Types/ClassDerived.cs
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,8 @@ internal static Type CreateDerivedType(string name,
}
}

// add the destructor so the python object created in the constructor gets destroyed
// add the destructor so the python object created in the constructor gets destroyed,
// after the base class finalizers, which may still call the Python overrides
MethodBuilder methodBuilder = typeBuilder.DefineMethod("Finalize",
MethodAttributes.Family |
MethodAttributes.Virtual |
Expand All @@ -279,11 +280,11 @@ internal static Type CreateDerivedType(string name,
Type.EmptyTypes);
ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance));
il.Emit(OpCodes.Ldarg_0);
#pragma warning disable CS0618 // PythonDerivedType is for internal use only
il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod(nameof(PyFinalize)));
#pragma warning restore CS0618 // PythonDerivedType is for internal use only
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance));
il.Emit(OpCodes.Ret);

Type type = typeBuilder.CreateType();
Expand Down Expand Up @@ -928,7 +929,14 @@ public static void PyFinalize(IPythonDerivedType obj)
// the C# object is being destroyed which must mean there are no more
// references to the Python object as well
var self = GetPyObj(obj);
// every generated type in a chain of Python subclasses has its own Finalize calling this on the
// same object, once the finalizers of its base classes ran: only the first one queues its Python object
if (self.Ref == null)
{
return;
}
Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run);
SetPyObj(obj, BorrowedReference.Null);
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved
}

internal static void Finalize(IntPtr derived)
Expand Down
103 changes: 85 additions & 18 deletions src/runtime/Types/ExceptionClassObject.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Reflection;

namespace Python.Runtime;

Expand Down Expand Up @@ -29,17 +30,21 @@ internal ExceptionClassObject(Type tp) : base(tp)
{
return Exceptions.RaiseTypeError("invalid object");
}
string name = e.GetType().Name;
string message;
if (e.Message != String.Empty)
try
{
message = String.Format("{0}('{1}')", name, e.Message);
string name = e.GetType().Name;
string message = e.Message;
if (!string.IsNullOrEmpty(message))
{
return Runtime.PyString_FromString(String.Format("{0}('{1}')", name, message));
}
return Runtime.PyString_FromString(String.Format("{0}()", name));
}
else
catch (Exception error)
{
message = String.Format("{0}()", name);
SetError(error);
return default;
}
return Runtime.PyString_FromString(message);
}

/// <summary>
Expand All @@ -53,26 +58,88 @@ internal ExceptionClassObject(Type tp) : base(tp)
return Exceptions.RaiseTypeError("invalid object");
}

string message = e.ToString();
string fullTypeName = e.GetType().FullName;
string prefix = fullTypeName + ": ";
if (message.StartsWith(prefix))
// a None returned by a Python override of ToString reads as an empty message
try
{
message = message.Substring(prefix.Length);
string message = e.ToString() ?? string.Empty;
string fullTypeName = e.GetType().FullName;
string prefix = fullTypeName + ": ";
if (message.StartsWith(prefix))
{
message = message.Substring(prefix.Length);
}
else if (message.StartsWith(fullTypeName))
{
message = message.Substring(fullTypeName.Length);
}
return Runtime.PyString_FromString(message);
}
else if (message.StartsWith(fullTypeName))
catch (Exception error)
{
message = message.Substring(fullTypeName.Length);
SetError(error);
return default;
}
return Runtime.PyString_FromString(message);
}

public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw)
/// <summary>
/// Raises to Python the error of an exception member, as it is: a Python override of the member
/// throws its PythonException directly, whose InnerException is its cause, while a member the
/// Python subclass inherits runs through reflection, which wraps what it throws once per
/// generated level it goes through
/// </summary>
static void SetError(Exception error)
{
if (!base.Init(obj, args, kw)) return false;
while (error is TargetInvocationException { InnerException: { } inner })
{
error = inner;
}
Exceptions.SetError(error);
}

public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw)
=> base.Init(obj, args, kw) && SetArgsAndCause(obj);

/// <summary>
/// Sets the args and __cause__ of the constructed exception, raising to Python an error
/// its members throw, such as a Python override of Message
/// </summary>
internal static bool SetArgsAndCause(BorrowedReference obj)
{
var e = (CLRObject)GetManagedObject(obj)!;
try
{
return Exceptions.SetArgsAndCause(obj, (Exception)e.inst);
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved
}
catch (Exception error)
{
SetError(error);
return false;
}
}
}

return Exceptions.SetArgsAndCause(obj, (Exception)e.inst);
/// <summary>
/// Implementation for the managed types generated for Python subclasses of exceptions
/// that declare __namespace__: the generated object keeps its Python object as derived
/// types do, while it still reads as an exception from Python.
/// </summary>
[Serializable]
internal class ExceptionClassDerivedObject : ClassDerivedObject
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved
{
internal ExceptionClassDerivedObject(Type tp) : base(tp)
{
}

// Type slots are looked up on the implementing type's hierarchy, which here is ClassDerivedObject's
public new static NewReference tp_repr(BorrowedReference ob) => ExceptionClassObject.tp_repr(ob);
Comment thread
quantconnect-kronos-reviewer[bot] marked this conversation as resolved.
Resolved

public new static NewReference tp_str(BorrowedReference ob) => ExceptionClassObject.tp_str(ob);
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved

// ClassDerivedObject's tp_clear leaves the object to the .NET finalizer, but the exception's own fields
// (args, __cause__, __context__, __traceback__, __dict__) can form cycles that only clearing them breaks.
// The wrapper and its handle stay, as the .NET object may still use them.
public new static int tp_clear(BorrowedReference ob) => BaseUnmanagedClear(ob);
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved

public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw)
=> base.Init(obj, args, kw) && ExceptionClassObject.SetArgsAndCause(obj);
}
24 changes: 24 additions & 0 deletions src/testing/constructortests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,28 @@ public CountedConstructorTest()
++Calls;
}
}

public abstract class AbstractFinalizerCallbackTest
{
public static int Result;

public abstract int Callback();

~AbstractFinalizerCallbackTest()
{
Result = Callback();
}
}

public class VirtualFinalizerCallbackTest
{
public static int Result;

public virtual int Callback() => 7;

~VirtualFinalizerCallbackTest()
{
Result = Callback();
}
}
}
Loading
Loading