Skip to content

Commit d98d46f

Browse files
Refresh args and __cause__ of a __namespace__ exception created from .NET
When .NET constructs a generated exception subclass, its Python object is created before the base constructor runs, so its args and __cause__ describe the exception before Message and InnerException were set. Set them again once the base constructor has run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 865d592 commit d98d46f

2 files changed

Lines changed: 56 additions & 2 deletions

File tree

‎src/runtime/Types/ClassDerived.cs‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -904,8 +904,8 @@ public static void InvokeSetProperty<T>(IPythonDerivedType obj, string propertyN
904904

905905
public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, object[] args)
906906
{
907-
var selfRef = GetPyObj(obj);
908-
if (selfRef.Ref == null)
907+
var createdFromDotNet = GetPyObj(obj).Ref == null;
908+
if (createdFromDotNet)
909909
{
910910
// this might happen when the object is created from .NET
911911
using var _ = Py.GIL();
@@ -922,6 +922,18 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec
922922
null,
923923
obj,
924924
args);
925+
926+
// the Python object of an exception created from .NET got its args and __cause__
927+
// before the base constructor set its Message and InnerException
928+
if (!createdFromDotNet || obj is not Exception exception)
929+
{
930+
return;
931+
}
932+
using var gil = Py.GIL();
933+
if (!Exceptions.SetArgsAndCause(GetPyObj(obj).CheckRun(), exception))
934+
{
935+
throw PythonException.ThrowLastAsClrException();
936+
}
925937
}
926938

927939
public static void PyFinalize(IPythonDerivedType obj)

‎tests/test_exceptions.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -711,3 +711,45 @@ def test_namespaced_exception_subclass_override_errors():
711711
"inherited str outer KeyError 'inner'",
712712
"two-level inherited str outer KeyError 'inner'",
713713
]
714+
715+
716+
_NAMESPACED_EXCEPTION_FROM_DOTNET_SCRIPT = """
717+
from System import Activator, Array, Exception as ClrException, String, Type
718+
719+
class CreatedError(ClrException):
720+
__namespace__ = "Python.Test.DotNetCreatedExceptions"
721+
def __init__(self):
722+
pass
723+
724+
class ChildCreatedError(CreatedError):
725+
__namespace__ = "Python.Test.DotNetCreatedExceptions"
726+
def __init__(self):
727+
pass
728+
729+
def check(name, error):
730+
cause = error.__cause__
731+
print(name, error.Message, error.args, cause.Message if cause is not None else None,
732+
error.InnerException.Message if error.InnerException is not None else None)
733+
734+
inner = ClrException("inner")
735+
created = clr.GetClrType(CreatedError)
736+
check("activator", Activator.CreateInstance(created, Array[Object](["custom message", inner])))
737+
check("constructor info", created.GetConstructor(Array[Type]([String])).Invoke(Array[Object](["message only"])))
738+
check("parameterless", Activator.CreateInstance(created))
739+
check("child", Activator.CreateInstance(clr.GetClrType(ChildCreatedError), Array[Object](["child message", inner])))
740+
"""
741+
742+
743+
@pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime")
744+
def test_namespaced_exception_subclass_created_from_dotnet():
745+
"""The args and __cause__ of a __namespace__ exception subclass constructed from .NET
746+
match the Message and InnerException its base constructor set"""
747+
output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_FROM_DOTNET_SCRIPT)
748+
749+
default = "Exception of type 'Python.Test.DotNetCreatedExceptions.CreatedError' was thrown."
750+
assert output[-4:] == [
751+
"activator custom message ('custom message',) inner inner",
752+
"constructor info message only ('message only',) None None",
753+
f"parameterless {default} ({default!r},) None None",
754+
"child child message ('child message',) inner inner",
755+
]

0 commit comments

Comments
 (0)