Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
56 changes: 56 additions & 0 deletions src/runtime/Types/ReflectedClrType.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;

using static Python.Runtime.PythonException;
Expand Down Expand Up @@ -86,6 +88,60 @@ internal static NewReference CreateSubclass(ClassBase baseClass,
// derived class we want the python overrides in there instead if they exist.
var cls_dict = Util.ReadRef(py_type, TypeOffset.tp_dict);
ThrowIfIsNotZero(Runtime.PyDict_Update(cls_dict, dict));

// The generated type's overrides of its base's virtual methods would hide the Python overrides of
// a Python base class (a __namespace__ subclass of a __namespace__ subclass), so let lookups of
// those reach the Python overrides, as Python's method resolution does.
var pyBaseType = Util.ReadRef(py_type, TypeOffset.tp_base);
var baseVirtualMethods = baseClass.type.Value.GetMethods()
.Where(m => m.IsVirtual && !m.IsFinal)
.Select(m => m.Name)
.ToHashSet();
using var clsDict = new PyDict(cls_dict);
using var keys = clsDict.Keys();
foreach (PyObject key in keys)
{
using (key)
{
var inherited = Runtime._PyType_Lookup(pyBaseType, key.Reference);
if (inherited.IsNull
|| ManagedType.GetManagedObject(inherited) != null
|| !Runtime.PyDict_GetItem(dict, key.Reference).IsNull
|| ManagedType.GetManagedObject(Runtime.PyDict_GetItem(cls_dict, key.Reference)) is not MethodObject method)
{
continue;
}

// a generated forwarder, possibly among overloads the generated type doesn't override (which
// the parent's Python override replaces too), but not the members the class body declares for .NET,
// methods or the accessors of its properties
var hasForwarder = false;
var declaredInBody = false;
foreach (var member in method.info)
{
hasForwarder |= member is MethodInfo { IsVirtual: true, IsFinal: false }
&& member.DeclaringType == subType
&& baseVirtualMethods.Contains(member.Name);

// an accessor the generated type emits for a property the class body declares with
// clr.clrproperty, by the names ClassDerivedObject gives them
var property = member is MethodInfo { IsSpecialName: true }
&& (member.Name.StartsWith("get_") || member.Name.StartsWith("set_"))
? Runtime.PyDict_GetItemString(dict, member.Name.Substring(4))
: BorrowedReference.Null;
var isBodyPropertyAccessor = !property.IsNull
&& Runtime.PyObject_HasAttrString(property, "_clr_property_type_") == 1;

declaredInBody |= !Runtime.PyDict_GetItemString(dict, member.Name).IsNull
|| isBodyPropertyAccessor;
}
if (hasForwarder && !declaredInBody)
{
ThrowIfIsNotZero(Runtime.PyDict_DelItem(cls_dict, key.Reference));
}
}
}

// Update the __classcell__ if it exists
BorrowedReference cell = Runtime.PyDict_GetItemString(cls_dict, "__classcell__");
if (!cell.IsNull)
Expand Down
10 changes: 10 additions & 0 deletions src/testing/constructortests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,14 @@ public FinalizedConstructorTest(Exception toThrow)
Interlocked.Increment(ref Finalized);
}
}

public class CountedConstructorTest
{
public static int Calls;

public CountedConstructorTest()
{
++Calls;
}
}
}
143 changes: 143 additions & 0 deletions tests/test_subclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,149 @@ def test_create_instance():
assert id(y) == id(ob2)


def test_namespace_subclass_of_namespace_subclass():
"""Test managed code reaches the Python overrides a namespaced subclass inherits from a namespaced parent"""
subnamespace = test_namespace_subclass_of_namespace_subclass.__name__
namespace = "Python.Test." + subnamespace
DerivedClass = derived_class_fixture(subnamespace)

class ChildClass(DerivedClass):
__namespace__ = namespace

class GrandChildClass(ChildClass):
__namespace__ = namespace

def bar(self, x, i):
return "GrandChildClass"

for ob in (ChildClass(), GrandChildClass(), FunctionsTest.create_instance(GrandChildClass)):
assert ob.foo() == "DerivedClass"
assert FunctionsTest.test_foo(ob) == "DerivedClass"
assert ob.not_overriden() == "not_overriden"
assert list(SubClassTest.test_list(ob)) == ["A", "B", "C"]

assert FunctionsTest.test_bar(ChildClass(), "bar", 2) == "bar_bar"
assert FunctionsTest.test_bar(GrandChildClass(), "bar", 2) == "GrandChildClass"

# interface methods have no managed implementation to fall back to
InterfaceTestClass = interface_test_class_fixture(subnamespace)

class InterfaceChildClass(InterfaceTestClass):
__namespace__ = namespace

ob = InterfaceChildClass()
assert ob.foo() == "InterfaceTestClass"
assert FunctionsTest.test_foo(ob) == "InterfaceTestClass"
assert FunctionsTest.test_bar(ob, "bar", 2) == "bar/bar"

# overloads the generated type doesn't override don't hide the parent's override either
class EqualsParentClass(System.Object):
__namespace__ = namespace

def Equals(self, other):
return True

class EqualsChildClass(EqualsParentClass):
__namespace__ = namespace

other = System.Object()
ob = EqualsChildClass()
assert ob.Equals(other)
assert System.Object.Equals(ob, other)
assert ob.GetType().GetMethod("Equals", [System.Object]).Invoke(ob, [other])

# members the child declares for .NET keep their snake_case aliases over the parent's Python ones
import clr

class AliasParentClass(SubClassTest):
__namespace__ = namespace

def calculate(self):
return 1

@property
def number(self):
return 2

class AliasChildClass(AliasParentClass):
__namespace__ = namespace

@clr.clrmethod(int, [])
def Calculate(self):
return 3

@clr.clrproperty(int)
def Number(self):
return 4

ob = AliasChildClass()
assert ob.calculate() == 3
assert ob.Calculate() == 3
assert ob.number == 4
assert ob.Number == 4

# nor the accessors of a property the child redeclares
class PropertyParentClass(System.Object):
__namespace__ = namespace

def get_Number(self):
return 1

def set_Number(self, value):
self.value = value + 1

Number = clr.clrproperty(int, get_Number, set_Number)

class PropertyChildClass(PropertyParentClass):
__namespace__ = namespace

def get_Number(self):
return 3

def set_Number(self, value):
self.value = value + 3

Number = clr.clrproperty(int, get_Number, set_Number)

class PropertyDecoratedChildClass(PropertyParentClass):
__namespace__ = namespace

@clr.clrproperty(int)
def Number(self):
return 3

@Number.setter
def Number(self, value):
self.value = value + 3

for cls in (PropertyChildClass, PropertyDecoratedChildClass):
ob = cls()
prop = ob.GetType().GetProperty("Number")
assert ob.Number == 3
assert ob.get_Number() == 3
assert prop.GetValue(ob) == 3
ob.set_Number(10)
assert ob.value == 13
prop.SetValue(ob, 20)
assert ob.value == 23

# the managed constructor still runs once
from Python.Test import CountedConstructorTest

class CountedParentClass(CountedConstructorTest):
__namespace__ = namespace

def __init__(self):
super().__init__()

class CountedChildClass(CountedParentClass):
__namespace__ = namespace

CountedConstructorTest.Calls = 0
CountedChildClass()
assert CountedConstructorTest.Calls == 1


def test_events():
class EventHandler(object):
def handler(self, x, args):
Expand Down
Loading