Skip to content

Commit a9b04e9

Browse files
Reach a namespaced parent's Python overrides from a namespaced subclass (#180)
* Reach a namespaced parent's Python overrides from a namespaced subclass The generated type of a __namespace__ subclass reflects its own members, such as its overrides of the base's virtual methods, into the Python class dict. Subclassing another __namespace__ class, those members hid the Python overrides the parent defines, so .NET calls fell back to the .NET implementation, or threw NotImplementedException for an abstract member. Drop a reflected member from the new class dict when the Python base class overrides it in Python, so lookups reach the nearest Python override as Python's method resolution does. Closes #172 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Only skip the generated forwarders of the base's virtual methods The class dict filter also removed the reflected constructor, so a child inherited its parent's Python __init__, whose super().__init__() then ran the managed constructor a second time, and the snake_case aliases of members the child declares for .NET, which then resolved to the parent's Python members. Remove only the forwarders the generated type adds for the base's virtual methods, which is what hid the parent's Python overrides. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Skip forwarders that share a name with overloads the generated type doesn't override Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the accessors of properties the subclass redeclares for .NET Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Inline the check for the accessors of properties the class body declares Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: quantconnect-kronos[bot] <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 0e25193 commit a9b04e9

3 files changed

Lines changed: 209 additions & 0 deletions

File tree

‎src/runtime/Types/ReflectedClrType.cs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Diagnostics;
4+
using System.Linq;
5+
using System.Reflection;
46
using System.Runtime.Serialization;
57

68
using static Python.Runtime.PythonException;
@@ -86,6 +88,60 @@ internal static NewReference CreateSubclass(ClassBase baseClass,
8688
// derived class we want the python overrides in there instead if they exist.
8789
var cls_dict = Util.ReadRef(py_type, TypeOffset.tp_dict);
8890
ThrowIfIsNotZero(Runtime.PyDict_Update(cls_dict, dict));
91+
92+
// The generated type's overrides of its base's virtual methods would hide the Python overrides of
93+
// a Python base class (a __namespace__ subclass of a __namespace__ subclass), so let lookups of
94+
// those reach the Python overrides, as Python's method resolution does.
95+
var pyBaseType = Util.ReadRef(py_type, TypeOffset.tp_base);
96+
var baseVirtualMethods = baseClass.type.Value.GetMethods()
97+
.Where(m => m.IsVirtual && !m.IsFinal)
98+
.Select(m => m.Name)
99+
.ToHashSet();
100+
using var clsDict = new PyDict(cls_dict);
101+
using var keys = clsDict.Keys();
102+
foreach (PyObject key in keys)
103+
{
104+
using (key)
105+
{
106+
var inherited = Runtime._PyType_Lookup(pyBaseType, key.Reference);
107+
if (inherited.IsNull
108+
|| ManagedType.GetManagedObject(inherited) != null
109+
|| !Runtime.PyDict_GetItem(dict, key.Reference).IsNull
110+
|| ManagedType.GetManagedObject(Runtime.PyDict_GetItem(cls_dict, key.Reference)) is not MethodObject method)
111+
{
112+
continue;
113+
}
114+
115+
// a generated forwarder, possibly among overloads the generated type doesn't override (which
116+
// the parent's Python override replaces too), but not the members the class body declares for .NET,
117+
// methods or the accessors of its properties
118+
var hasForwarder = false;
119+
var declaredInBody = false;
120+
foreach (var member in method.info)
121+
{
122+
hasForwarder |= member is MethodInfo { IsVirtual: true, IsFinal: false }
123+
&& member.DeclaringType == subType
124+
&& baseVirtualMethods.Contains(member.Name);
125+
126+
// an accessor the generated type emits for a property the class body declares with
127+
// clr.clrproperty, by the names ClassDerivedObject gives them
128+
var property = member is MethodInfo { IsSpecialName: true }
129+
&& (member.Name.StartsWith("get_") || member.Name.StartsWith("set_"))
130+
? Runtime.PyDict_GetItemString(dict, member.Name.Substring(4))
131+
: BorrowedReference.Null;
132+
var isBodyPropertyAccessor = !property.IsNull
133+
&& Runtime.PyObject_HasAttrString(property, "_clr_property_type_") == 1;
134+
135+
declaredInBody |= !Runtime.PyDict_GetItemString(dict, member.Name).IsNull
136+
|| isBodyPropertyAccessor;
137+
}
138+
if (hasForwarder && !declaredInBody)
139+
{
140+
ThrowIfIsNotZero(Runtime.PyDict_DelItem(cls_dict, key.Reference));
141+
}
142+
}
143+
}
144+
89145
// Update the __classcell__ if it exists
90146
BorrowedReference cell = Runtime.PyDict_GetItemString(cls_dict, "__classcell__");
91147
if (!cell.IsNull)

‎src/testing/constructortests.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,4 +108,14 @@ public FinalizedConstructorTest(Exception toThrow)
108108
Interlocked.Increment(ref Finalized);
109109
}
110110
}
111+
112+
public class CountedConstructorTest
113+
{
114+
public static int Calls;
115+
116+
public CountedConstructorTest()
117+
{
118+
++Calls;
119+
}
120+
}
111121
}

‎tests/test_subclass.py‎

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,149 @@ def test_create_instance():
197197
assert id(y) == id(ob2)
198198

199199

200+
def test_namespace_subclass_of_namespace_subclass():
201+
"""Test managed code reaches the Python overrides a namespaced subclass inherits from a namespaced parent"""
202+
subnamespace = test_namespace_subclass_of_namespace_subclass.__name__
203+
namespace = "Python.Test." + subnamespace
204+
DerivedClass = derived_class_fixture(subnamespace)
205+
206+
class ChildClass(DerivedClass):
207+
__namespace__ = namespace
208+
209+
class GrandChildClass(ChildClass):
210+
__namespace__ = namespace
211+
212+
def bar(self, x, i):
213+
return "GrandChildClass"
214+
215+
for ob in (ChildClass(), GrandChildClass(), FunctionsTest.create_instance(GrandChildClass)):
216+
assert ob.foo() == "DerivedClass"
217+
assert FunctionsTest.test_foo(ob) == "DerivedClass"
218+
assert ob.not_overriden() == "not_overriden"
219+
assert list(SubClassTest.test_list(ob)) == ["A", "B", "C"]
220+
221+
assert FunctionsTest.test_bar(ChildClass(), "bar", 2) == "bar_bar"
222+
assert FunctionsTest.test_bar(GrandChildClass(), "bar", 2) == "GrandChildClass"
223+
224+
# interface methods have no managed implementation to fall back to
225+
InterfaceTestClass = interface_test_class_fixture(subnamespace)
226+
227+
class InterfaceChildClass(InterfaceTestClass):
228+
__namespace__ = namespace
229+
230+
ob = InterfaceChildClass()
231+
assert ob.foo() == "InterfaceTestClass"
232+
assert FunctionsTest.test_foo(ob) == "InterfaceTestClass"
233+
assert FunctionsTest.test_bar(ob, "bar", 2) == "bar/bar"
234+
235+
# overloads the generated type doesn't override don't hide the parent's override either
236+
class EqualsParentClass(System.Object):
237+
__namespace__ = namespace
238+
239+
def Equals(self, other):
240+
return True
241+
242+
class EqualsChildClass(EqualsParentClass):
243+
__namespace__ = namespace
244+
245+
other = System.Object()
246+
ob = EqualsChildClass()
247+
assert ob.Equals(other)
248+
assert System.Object.Equals(ob, other)
249+
assert ob.GetType().GetMethod("Equals", [System.Object]).Invoke(ob, [other])
250+
251+
# members the child declares for .NET keep their snake_case aliases over the parent's Python ones
252+
import clr
253+
254+
class AliasParentClass(SubClassTest):
255+
__namespace__ = namespace
256+
257+
def calculate(self):
258+
return 1
259+
260+
@property
261+
def number(self):
262+
return 2
263+
264+
class AliasChildClass(AliasParentClass):
265+
__namespace__ = namespace
266+
267+
@clr.clrmethod(int, [])
268+
def Calculate(self):
269+
return 3
270+
271+
@clr.clrproperty(int)
272+
def Number(self):
273+
return 4
274+
275+
ob = AliasChildClass()
276+
assert ob.calculate() == 3
277+
assert ob.Calculate() == 3
278+
assert ob.number == 4
279+
assert ob.Number == 4
280+
281+
# nor the accessors of a property the child redeclares
282+
class PropertyParentClass(System.Object):
283+
__namespace__ = namespace
284+
285+
def get_Number(self):
286+
return 1
287+
288+
def set_Number(self, value):
289+
self.value = value + 1
290+
291+
Number = clr.clrproperty(int, get_Number, set_Number)
292+
293+
class PropertyChildClass(PropertyParentClass):
294+
__namespace__ = namespace
295+
296+
def get_Number(self):
297+
return 3
298+
299+
def set_Number(self, value):
300+
self.value = value + 3
301+
302+
Number = clr.clrproperty(int, get_Number, set_Number)
303+
304+
class PropertyDecoratedChildClass(PropertyParentClass):
305+
__namespace__ = namespace
306+
307+
@clr.clrproperty(int)
308+
def Number(self):
309+
return 3
310+
311+
@Number.setter
312+
def Number(self, value):
313+
self.value = value + 3
314+
315+
for cls in (PropertyChildClass, PropertyDecoratedChildClass):
316+
ob = cls()
317+
prop = ob.GetType().GetProperty("Number")
318+
assert ob.Number == 3
319+
assert ob.get_Number() == 3
320+
assert prop.GetValue(ob) == 3
321+
ob.set_Number(10)
322+
assert ob.value == 13
323+
prop.SetValue(ob, 20)
324+
assert ob.value == 23
325+
326+
# the managed constructor still runs once
327+
from Python.Test import CountedConstructorTest
328+
329+
class CountedParentClass(CountedConstructorTest):
330+
__namespace__ = namespace
331+
332+
def __init__(self):
333+
super().__init__()
334+
335+
class CountedChildClass(CountedParentClass):
336+
__namespace__ = namespace
337+
338+
CountedConstructorTest.Calls = 0
339+
CountedChildClass()
340+
assert CountedConstructorTest.Calls == 1
341+
342+
200343
def test_events():
201344
class EventHandler(object):
202345
def handler(self, x, args):

0 commit comments

Comments
 (0)