From 26b4116953174e2604e1a05f96e96f1213e1b4fe Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 13 Oct 2026 01:40:25 +0000 Subject: [PATCH] Let a Python subclass without a constructor take its base's arguments [patch] PythonGenerator wrote def __init__(self): super().__init__() for every class with a base type and no constructor, which hid the base's constructor, so Derived(5) raised TypeError. A constructor is now written only when there are instance-initialised fields, so a bare subclass inherits the base's. One written for a subclass takes *args and **kwargs and passes them to super().__init__ before the field initialisers. Fixes #149 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ad87XvcvgZs8kt6MK9mwQE --- .../PythonGeneratedSourceImportsTests.cs | 59 +++++++++++++++++++ Coder/Languages/PythonGenerator.cs | 15 +++-- 2 files changed, 69 insertions(+), 5 deletions(-) diff --git a/Coder.Test/Languages/PythonGeneratedSourceImportsTests.cs b/Coder.Test/Languages/PythonGeneratedSourceImportsTests.cs index 41e6b90..c3f34cf 100644 --- a/Coder.Test/Languages/PythonGeneratedSourceImportsTests.cs +++ b/Coder.Test/Languages/PythonGeneratedSourceImportsTests.cs @@ -179,6 +179,65 @@ assert mutable.State }); } + /// + /// Tests that a subclass declaring no constructor still accepts its base's arguments: one with + /// nothing to initialise inherits the base's constructor, and one with an instance-initialised + /// field forwards to it (#149). + /// + [TestMethod] + public void SubclassWithoutConstructor_AcceptsTheBaseConstructorsArguments() + { + string? python = ToolchainHarness.FindOnPath("--version", "python3", "python"); + if (python is null) + { + Assert.Inconclusive("No Python interpreter on the path, so nothing was run."); + return; + } + + SourceFile file = new("inherited"); + + // Base(x): self.x = x + ClassDeclaration baseClass = new("Base"); + FunctionDeclaration constructor = new("Base") { Kind = FunctionKind.Constructor }; + constructor.Parameters.Add(new Parameter("x", "int")); + constructor.Body.Add(new AssignmentStatement(new VariableReference("self.x"), new VariableReference("x"))); + baseClass.Members.Add(constructor); + file.Members.Add(baseClass); + + file.Members.Add(new ClassDeclaration("Derived") { BaseType = "Base" }); + + ClassDeclaration tagged = new("Tagged") { BaseType = "Base" }; + tagged.Members.Add(new FieldDeclaration("tags", TypeReference.Parse("list")) + { + InitialValue = new ConstructionExpression(), + }); + file.Members.Add(tagged); + + ToolchainHarness.InTemporaryDirectory(directory => + { + string generated = new PythonGenerator().Generate(file); + File.WriteAllText(Path.Combine(directory, "inherited.py"), generated); + File.WriteAllText( + Path.Combine(directory, "driver.py"), + """ + import inherited + + derived = inherited.Derived(5) + assert derived.x == 5, derived.x + + first = inherited.Tagged(6) + second = inherited.Tagged(x=7) + assert first.x == 6, first.x + assert second.x == 7, second.x + first.tags.append(1) + assert second.tags == [], second.tags + """); + + (int exitCode, string output) = ToolchainHarness.Run(python, "driver.py", directory); + Assert.AreEqual(0, exitCode, $"Python rejected the generated module:{Environment.NewLine}{output}{Environment.NewLine}{generated}"); + }); + } + /// /// Tests that a module whose annotations name a class that does not exist yet can be loaded. /// diff --git a/Coder/Languages/PythonGenerator.cs b/Coder/Languages/PythonGenerator.cs index 0260696..9f29698 100644 --- a/Coder/Languages/PythonGenerator.cs +++ b/Coder/Languages/PythonGenerator.cs @@ -554,8 +554,10 @@ .. classDecl.Interfaces.Select(implemented => PythonBaseFromGenericType(implemen bool hasConstructor = classDecl.Members .OfType() .Any(member => member.Kind == FunctionKind.Constructor); - bool synthesiseConstructor = !hasConstructor - && (classDecl.BaseType is not null || instanceInitialisedFields.Count > 0); + // Python inherits a constructor, so a class with nothing of its own to initialise writes + // none and takes whatever its base takes. One written for a subclass would hide the base's + // and refuse its arguments. + bool synthesiseConstructor = !hasConstructor && instanceInitialisedFields.Count > 0; if (classDecl.Members.Count == 0 && !synthesiseConstructor) { @@ -580,11 +582,14 @@ .. classDecl.Interfaces.Select(implemented => PythonBaseFromGenericType(implemen if (synthesiseConstructor) { - code.WriteLine("def __init__(self):"); + // A subclass's constructor passes on whatever it is given, so it still accepts what the + // base's constructor does and only adds the initialisers. + bool forwards = classDecl.BaseType is not null; + code.WriteLine(forwards ? "def __init__(self, *args, **kwargs):" : "def __init__(self):"); using IndentScope body = new(code); - if (classDecl.BaseType is not null) + if (forwards) { - code.WriteLine("super().__init__()"); + code.WriteLine("super().__init__(*args, **kwargs)"); } WriteConstructorPrologue(classDecl, code, NeedsConstruction, WriteInstanceInitialiser);