Skip to content

Generated exceptions constructed from .NET retain stale args and omit their cause #168

Open

Description

Observed behavior

When .NET creates a generated (__namespace__) exception subclass, its Python args and __cause__ describe the object before its base constructor ran. Its managed Message and InnerException are correct afterward, but returning the registered Python wrapper does not refresh those attributes.

Reproduced on Python 3.11 / .NET 10 with pythonnet commit 089e5a8a34ad6c8a03d93a9c4911b00231ec1f41:

from pythonnet import load
load("coreclr")
import clr
from System import Activator, Array, Object, Exception as ClrException

class Error(ClrException):
    __namespace__ = "Synthetic.Errors"
    def __init__(self):
        pass

inner = ClrException("inner")
error = Activator.CreateInstance(
    clr.GetClrType(Error), Array[Object](["custom message", inner]))
print(error.Message)
print(error.args)
print(error.__cause__)

Actual:

custom message
("Exception of type 'Synthetic.Errors.Error' was thrown.",)
None

Expected: args == ("custom message",) and a cause representing inner.

Cause and fix requirement

PythonDerivedType.InvokeCtor (src/runtime/Types/ClassDerived.cs:904-923) allocates the Python wrapper before calling the base constructor. CLRObject.Create initializes exception attributes at that time. The ExceptionClassDerivedObject.Init refresh applies to Python-side construction, not this .NET constructor path.

Refresh the Python exception attributes after successful managed construction without replacing the registered Python wrapper or rerunning the constructor. Add coverage that constructs through Activator or ConstructorInfo and verifies the managed fields and Python attributes agree.

This is a limited follow-up to #167, not an additional regression blocker: current master (060af02) aborts when this generated instance returns from .NET, whereas #167 makes the instance return successfully. Priority P2: limited to .NET-created generated exception subclasses; no broader impact established.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions