Repository navigation
Reach a namespaced parent's Python overrides from a namespaced subclass - #180
quantconnect-kronos[bot] merged 5 commits into
Conversation
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>
There was a problem hiding this comment.
Approved. When a Python base class resolves a name to a Python attribute and the class body doesn't define it, the reflected entry is dropped from the class dict. Python's own lookup then reaches the nearest Python override, and PythonDerivedType.InvokeMethod finds it from .NET too. The .NET fallback still goes through reflection (InvokeMember(origMethodName)), so dropping the Python entry doesn't affect it. A single-level __namespace__ class has a reflected .NET type as its base, and that base's lookup finds managed members, so nothing is dropped for it.
I ran extra checks locally against this head and against master. All of these pass here. On master, one crashes and six fail:
- a grandchild override calling
super().foo(): master recurses until the process dies, here it reaches the parent's Pythonfoo - a parent's name-mangled private helper (
self.__helper()), which on master resolved to the child's generated_P__helper - an event implemented in Python on the parent (
add_TestEvent), raised from .NET - an instance created from .NET (
create_instance) of a child without its own members ToStringandIComparable.CompareToreached from .NET through a two-level chain@clr.clrmethodand@clr.clrpropertydefined on the parent, used from Python and through reflection on the child
My check that a single-level class still exposes its .NET members passes on both.
Also a behavior change, and the right one: a child whose parent has a Python __init__ now runs it. So Child() raises a TypeError when that __init__ needs arguments, as Parent() already does. Before, it silently skipped the parent's __init__.
Set risk:low: the change is small and easy to revert, its test fails without the runtime change, CI is green (including the Lean regression and unit test runs), and the description reports an end-to-end run that failed before the change and passes with it.
There was a problem hiding this comment.
Request changes: the dictionary filter also removes constructor descriptors and aliases for CLR members explicitly declared by the child. I reproduced duplicate managed construction and changed member results against master; both come from pruning more than the virtual forwarding members needed for #172. Details and the narrower scope are inline.
Local validation passed: 489 Python tests, 1,050 embedding tests (8 skipped), and 2 managed Python-runner tests. End-to-end inherited-dispatch assertions also passed, but that process subsequently encountered an independently known shutdown error.
Set risk:high: the broader constructor and member-binding changes introduce regressions despite the passing suites.
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>
There was a problem hiding this comment.
Requesting changes. The narrowed filter fixes both regressions the other review found: the snake_case aliases of members the child declares for .NET keep returning the child's members, and the managed constructor runs once. I checked both locally. But the filter now misses a virtual member that has another overload which isn't a generated forwarder, so the issue's failure is still there for that member. Details are inline.
Locally on this head, pytest --runtime netcore tests passes and CI is green.
risk:high stays: the change leaves a .NET call to a virtual member returning the .NET result, which is the wrong result the issue is about. A fix for that, with a test, would bring this back toward risk:low.
…oesn't override Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Approved. cba03d4 fixes the other review's accessor finding. A get_/set_ accessor now counts as declared by the class body when the body's value for the property name carries _clr_property_type_. That's the same rule ClassDerivedObject.CreateDerivedType uses (src/runtime/Types/ClassDerived.cs:206-235) to emit those accessors instead of forwarders, so the filter can't mistake one for the other. The new test covers named and decorated redeclarations, with getter and setter, from Python and through reflection. tests/test_subclass.py passes locally on this head, and CI is green.
One optional suggestion is inline.
Set risk:low: the change is small and easy to revert, and it only touches classes whose Python base overrides the member. Each case found in review has a test, CI is green (Lean regression and unit test runs included), and the reported end-to-end run failed before the change and passes with it. That run predates the last two commits, which only keep more members in the dict than before and are covered by the new tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Approved. c0b08ef inlines the property-accessor check as isBodyPropertyAccessor, as I suggested last time. It doesn't change behavior: a member counts as declared in the class body under exactly the same conditions as before.
There was a problem hiding this comment.
Approved. cba03d4 and c0b08ef resolve my outstanding accessor finding: the filter preserves the special-name getters/setters emitted for a property declared in the child body. The check matches AddPythonProperty, and the new tests exercise named and decorated redeclarations through Python and CLR reflection.
I reproduced the previous getter/setter results of 1/11 on 9d63d13 and verified 3/13 on this head. Local validation passed: 489 Python tests (23 skipped), 1,050 embedding tests (8 skipped), and 2 managed-runner tests.
Tested end to end on this head: inherited ToString, Equals, and CompareTo reach the parent's Python implementations; both property redeclaration forms retain the child's getter and setter results. That run completed cleanly. A broader fixture-backed variant passed its assertions but failed during shutdown on both this head and unchanged master, so that failure is not attributed to this change.
risk:low: the change is small and reversible, the constructor and member-binding regressions are fixed and covered by tests, and the focused end-to-end run verifies the corrected dispatch without changing the working property results.
Closes #172
What changed and why
ReflectedClrType.CreateSubclassbuilds the Python class of a__namespace__subclass from its generated .NET type, whose reflected members fill the class dict, then copies the class body over them. The generated type has its own members for every virtual member of its base, its overrides included. When the base is itself a__namespace__Python class, those reflected members sat in the child's dict and hid the Python overrides the parent defines. SoPythonDerivedType.InvokeMethodlooked up the method, found the managed binding, and treated it as not overridden:NotImplementedException: Python object does not have a '<name>' methodThe same shadowing hid the parent's methods from Python calls too, so
child.foo()also returned the .NET result.The class dict now drops a name whose reflected methods include a generated forwarder of the base's virtual methods (also through its snake_case alias) when the Python base class resolves that name to a Python (non-managed) attribute and the class body defines neither the name nor any of those methods' .NET names, nor the
@clr.clrpropertyaget_/set_accessor among them belongs to. Overloads the generated type doesn't override (such as the staticObject.Equals(object, object)beside the virtualEquals(object)) go with it, as the parent's Python override already replaced the whole overload set. Lookups then reach the nearest Python override as Python's method resolution does, both from Python and from .NET (through the generated override'sInvokeMethod). Everything else in the class dict stays as before: members the class body defines or declares for .NET (@clr.clrmethod,@clr.clrproperty) with their aliases, constructors and__init__, properties, and members no Python base overrides.Construction is unchanged: a
__namespace__child still doesn't inherit a__namespace__parent's Python__init__, as on master, so the managed constructor runs once.Classes without a Python
__namespace__base are unchanged: their Python base defines no Python overrides of the generated type's members.Tests
New
test_namespace_subclass_of_namespace_subclassintests/test_subclass.py:__namespace__child and grandchild of a__namespace__subclass ofSubClassTest(virtual members): .NET calls (FunctionsTest.test_foo,test_bar,SubClassTest.test_list) and Python calls reach the parent's Python overrides, the grandchild's ownbaroverride wins over the parent's, a member nobody overrides still runs the .NET one, and an instance created from .NET (FunctionsTest.create_instance) behaves the same__namespace__child of a__namespace__implementation ofIInterfaceTest(no .NET implementation to fall back to): .NET calls reach the parent's Python methods__namespace__child of a__namespace__System.Objectsubclass overridingEquals, whose overloads mix the virtualEquals(object)with the staticEquals(object, object):Equalsfrom Python,System.Object.Equals(child, other), and reflection'sInvokereach the parent's override__namespace__child declaring@clr.clrmethodCalculateand@clr.clrpropertyNumberover a parent's Pythoncalculateandnumber:calculate()/numberstill return the child's members__namespace__children redeclaring a parent's@clr.clrpropertyNumber, by namedget_Number/set_Numbermethods and by the decorator with a setter: the property,get_Number()/set_Number()from Python, and reflection'sGetValue/SetValueall reach the child's getter and setter__namespace__child of a__namespace__parent whose__init__callssuper().__init__()runs the managed constructor onceWithout the runtime change, the test fails with
assert 'foo' == 'DerivedClass'; with the previous commit's filter (forwarders only), it fails on theEqualscase; with 9d63d13's, it fails on the decorated property'sget_Number()(assert 1 == 3).The CI steps, run locally on Python 3.11 / .NET 10 after
pip install -v .:dotnet test --runtime any-x64 src/embed_tests/ --filter "FullyQualifiedName!~SetPythonPath": 1049 passed, 8 skippeddotnet test --runtime any-x64 src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passedpytest --runtime netcore tests: 489 passed, 23 skippeddotnet test --runtime any-x64 src/python_tests_runner/: 2 passedAlso tested end to end in a Lean Python backtest whose algorithm defines
__namespace__chains, calls them from .NET and fails unless each result is right: a child of aSystem.Objectsubclass overridingToString, formatted byString.Format, and a child of aSystem.IComparableimplementation, compared byComparer.Default:String.FormatreturnedNamespaceChain172.ChainChild, the .NET default, and the comparison threwTargetInvocationException(NotImplementedExceptioninside).python parentand42. With the earlier narrowed change (forwarders only), the process then hitInvalidOperationException: GIL must always be released...fromPy.GILState.Finalizeat shutdown, after the algorithm finished. A build of master hits the same shutdown error in the same setup, so it is not from this change.The backtest wasn't rerun for the last two commits, which widen the filter to names that also carry non-overridden overloads and keep the accessors of properties the child redeclares; the algorithm's members (
ToString,CompareTo) have no other overloads and the algorithm redeclares no property.