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
11 changes: 10 additions & 1 deletion assets/api/writer-generator/python/fhirpy_base_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Union, Optional, Iterator, Tuple, Dict
from typing import TYPE_CHECKING, Any, Union, Optional, Iterator, Tuple, Dict
from pydantic import BaseModel, Field
from typing import Protocol

Expand All @@ -15,6 +15,15 @@ class FhirpyBaseModel(BaseModel):
after Pydantic finishes model construction, so that fhirpy can detect it
via cls.resourceType for search/fetch operations.
"""

if TYPE_CHECKING:
# Set at runtime per-subclass by __pydantic_init_subclass__ below. Declared here
# so static type-checkers see it: fhirpy's ResourceProtocol requires a settable
# `resourceType`, and snake_case models expose the field as `resource_type`
# (alias "resourceType"). A settable instance attr (not ClassVar) satisfies the
# protocol's mutable member; the default keeps it optional for the pydantic mypy plugin.
resourceType: str = ""

id: Optional[str] = Field(None, alias="id")

@classmethod
Expand Down
22 changes: 21 additions & 1 deletion src/api/writer-generator/python/writer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@ export interface PythonGeneratorOptions extends WriterOptions {
generateProfile?: boolean;
rootPackageName: string; /// e.g. <rootPackageName>.hl7_fhir_r4_core.Patient.
fieldFormat: StringFormatKey;
/**
* Which client integration to generate into the output models.
* - `"fhirpy"` — models extend `FhirpyBaseModel` for use with the fhirpy async client (default).
* - `"none"` — plain Pydantic models with no client-specific code.
*/
client?: "fhirpy" | "none";
/**
* @deprecated Use `client` instead: `fhirpyClient: true` → `client: "fhirpy"`,
* `fhirpyClient: false` → `client: "none"`.
*/
fhirpyClient?: boolean;
}

Expand All @@ -105,10 +115,20 @@ export class Python extends Writer<PythonGeneratorOptions> {
constructor(options: PythonGeneratorOptions) {
super({ ...options, resolveAssets: options.resolveAssets ?? resolvePyAssets });
this.nameFormatFunction = this.getFieldFormatFunction(options.fieldFormat);
this.forFhirpyClient = options.fhirpyClient ?? false;
this.forFhirpyClient = this.resolveClient(options);
this.fieldFormat = options.fieldFormat;
}

/** Resolve which client integration to emit. `client` wins; `fhirpyClient` is the deprecated fallback; default is fhirpy. */
private resolveClient(options: PythonGeneratorOptions): boolean {
if (options.client !== undefined) return options.client === "fhirpy";
if (options.fhirpyClient !== undefined) {
this.logger()?.warn('python: `fhirpyClient` is deprecated; use `client: "fhirpy" | "none"` instead.');
return options.fhirpyClient;
}
return true; // default: fhirpy client
}

override async generate(tsIndex: TypeSchemaIndex): Promise<void> {
this.tsIndex = tsIndex;
const groups: TypeSchemaPackageGroups = {
Expand Down
30 changes: 30 additions & 0 deletions test/api/write-generator/python.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ describe("Python Writer Generator", async () => {
const result = await new APIBuilder({ register: r4Manager, logger: mkErrorLogger() })
.python({
inMemoryOnly: true,
client: "none",
})
.generate();
expect(result.success).toBeTrue();
Expand Down Expand Up @@ -112,6 +113,7 @@ describe("Python R4 Example (with generateProfile)", async () => {
.python({
inMemoryOnly: true,
generateProfile: true,
client: "none",
})
.generate();
const files = result.filesGenerated.python!;
Expand Down Expand Up @@ -150,6 +152,7 @@ describe("Python US Core Example", async () => {
.python({
inMemoryOnly: true,
generateProfile: true,
client: "none",
})
.generate();
const files = result.filesGenerated.python!;
Expand Down Expand Up @@ -182,3 +185,30 @@ describe("Python US Core Example", async () => {
expect(files["generated/hl7_fhir_us_core/profiles/__init__.py"]).toMatchSnapshot();
});
});

describe("Python client option", async () => {
const gen = async (opts: { client?: "fhirpy" | "none"; fhirpyClient?: boolean }) => {
const result = await new APIBuilder({ register: r4Manager, logger: mkErrorLogger() })
.python({ inMemoryOnly: true, ...opts })
.generate();
expect(result.success).toBeTrue();
return result.filesGenerated.python!;
};

it("defaults to the fhirpy client", async () => {
const files = await gen({});
expect(files["generated/fhirpy_base_model.py"]).toBeDefined();
expect(files["generated/hl7_fhir_r4_core/resource.py"]).toContain("FhirpyBaseModel");
});

it('client: "none" emits plain models with no fhirpy code', async () => {
const files = await gen({ client: "none" });
expect(files["generated/fhirpy_base_model.py"]).toBeUndefined();
expect(files["generated/hl7_fhir_r4_core/resource.py"]).not.toContain("FhirpyBaseModel");
});

it("deprecated fhirpyClient: true still selects the fhirpy client", async () => {
const files = await gen({ fhirpyClient: true });
expect(files["generated/fhirpy_base_model.py"]).toBeDefined();
});
});
Loading