Skip to content
Closed
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
39 changes: 39 additions & 0 deletions .chronus/changes/http-client-python-inline-discriminated-unions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
changeKind: feature
packages:
- "@typespec/http-client-python"
---

Support inline discriminated unions with an explicit model constraint and nominal
model variants. Keep the named Python union alias and declared model inheritance,
and deserialize responses and nested properties using the configured inline
discriminator. Inject absent discriminator tags when serializing nominal variants
through the union without changing shared model instances. Distinguish same-named
aliases from different namespaces. Missing or unknown tags raise `DeserializationError`. Object
envelopes and default variants are not supported.

Handle transitive discriminator inheritance and narrowed literal discriminator
fields in TypedDict views. Update `@typespec/http-specs` to `0.1.0-alpha.45` to
cover the constrained union scenarios in synchronous and asynchronous clients.
Use TCGC `0.74.0-dev.19` union constraints and keyed variants directly, with
compatible Azure prereleases and TypeSpec compiler `1.18.0-dev.15`.

```tsp
model PetBase {
kind: string;
name: string;
}
model Cat extends PetBase {
kind: "cat";
meows: boolean;
}
model Dog extends PetBase {
kind: "dog";
barks: boolean;
}
@discriminated(#{ envelope: "none" })
union Pet extends PetBase {
cat: Cat,
dog: Dog,
}
```
69 changes: 69 additions & 0 deletions packages/http-client-python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,75 @@ options:
option: value
```

## Inline discriminated unions

In the default `models-mode: dpg`, inline discriminated unions keep their named
Python union alias and their models' declared inheritance:

```tsp
model PetBase {
kind: string;
name: string;
}
model Cat extends PetBase {
kind: "cat";
meows: boolean;
}
model Dog extends PetBase {
kind: "dog";
barks: boolean;
}
@discriminated(#{ envelope: "none" })
union Pet extends PetBase {
cat: Cat,
dog: Dog,
}
```

Enable `features: [union-extends]` in `tspconfig.yaml` while union constraints are
experimental. This preview uses TCGC `0.74.0-dev.19` and consumes its SDK union
`baseType` and keyed `variants` directly. Union-to-model conversion is disabled
so `Pet` remains an annotated `Union[Cat, Dog]`, not an alias for `PetBase`.
Responses and model properties typed as `Pet` select the variant using the inline
discriminator. Models serialize through their existing literal discriminator
properties, producing JSON such as
`{"kind":"cat","name":"Whiskers","meows":true}` without an envelope.
`discriminatorPropertyName` and JSON-encoded property names are honored.
When a variant has no discriminator property, serialization through the union
injects its variant name as the tag without changing the model instance or
adding a property to the shared model class. For example, omitting `kind` from
all three models above still produces the same inline JSON through `Pet`.
Arrays, dictionaries, optional properties, and recursive references preserve this
dispatch. Direct `PetBase` and variant uses retain their existing behavior.
Same-named union aliases from different namespaces receive namespace prefixes
when emitted into the shared `_unions.py` file.

Initial support requires an explicit model constraint, nominally derived named
model variants, and either absent discriminator properties or matching required
string-literal discriminator properties.
Missing or unknown response tags raise `DeserializationError`; the constraint is
not an implicit default variant. Object envelopes, unnamed default variants,
structural variants, and existing non-literal or optional discriminator
properties are rejected with an `unsupported-discriminated-union` diagnostic.
Ordinary untagged unions and `@discriminator` model hierarchies are unchanged.

The TCGC preview imports compiler APIs that require `@typespec/compiler`
`1.18.0-dev.15`, although its published compiler peer range still specifies
`^1.17.0`. The emitter's development dependencies use an npm override to keep
one compiler version throughout the dependency graph. Applications using this
preview also need the compatible compiler and a root-level override:

```json
{
"dependencies": {
"@typespec/compiler": "1.18.0-dev.15"
},
"overrides": {
"@typespec/compiler": "$@typespec/compiler"
}
}
```

## Emitter options

### `emitter-output-dir`
Expand Down
1 change: 1 addition & 0 deletions packages/http-client-python/emitter/src/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ async function createPythonSdkContext(
const sdkContext = await createSdkContext<PythonEmitterOptions>(
context,
"@azure-tools/typespec-python",
{ convertDiscriminatedUnionsToModels: false },
);
context.program.reportDiagnostics(sdkContext.diagnostics);
return {
Expand Down
7 changes: 7 additions & 0 deletions packages/http-client-python/emitter/src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,13 @@ const libDef = {
name: "@typespec/http-client-python",
diagnostics: {
// error
"unsupported-discriminated-union": {
severity: "error",
messages: {
default:
'Python currently supports @discriminated only with envelope: "none", an explicit model constraint, and named model variants that nominally extend that constraint. Discriminator properties must be absent or matching required string literals. Object envelopes and default variants are not supported.',
},
},
"unknown-error": {
severity: "error",
messages: {
Expand Down
72 changes: 69 additions & 3 deletions packages/http-client-python/emitter/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type { HttpAuth } from "@typespec/http";
import { Visibility } from "@typespec/http";
import { dump } from "js-yaml";
import type { PythonSdkContext } from "./lib.js";
import { reportDiagnostic } from "./lib.js";
import {
camelToSnakeCase,
emitParamBase,
Expand Down Expand Up @@ -539,16 +540,81 @@ function emitBuiltInType(
}

function emitUnion(context: PythonSdkContext, type: SdkUnionType): Record<string, any> {
return getSimpleTypeResult(context, {
if (context.__typesMap.has(type)) {
return context.__typesMap.get(type)!;
}
const result: Record<string, any> = {
name: type.isGeneratedName ? undefined : type.name,
snakeCaseName: type.isGeneratedName ? undefined : camelToSnakeCase(type.name),
description: type.isGeneratedName ? "" : `Type of ${type.name}`,
internal: true,
type: "combined",
types: type.variantTypes.map((x) => getType(context, x)),
types: [],
xmlMetadata: {},
clientNamespace: getClientNamespace(context, type.namespace),
});
};
// Cache before visiting variants: a model property can refer back to this union.
context.__typesMap.set(type, result);
result.types = type.variantTypes.map((x) => getType(context, x));
if (type.discriminatedOptions) {
const metadata = getInlineUnionDiscriminator(type);
if (metadata) {
result.baseType = getType(context, metadata.baseType);
result.discriminator = {
propertyName: metadata.propertyName,
variants: Object.fromEntries(
metadata.variants.map(([tag, model]) => [tag, getType(context, model)]),
),
};
} else {
reportDiagnostic(context.program, {
code: "unsupported-discriminated-union",
target: type.__raw ?? context.program.getGlobalNamespaceType(),
});
}
}
return result;
}

function getInlineUnionDiscriminator(type: SdkUnionType):
| {
baseType: SdkModelType;
propertyName: string;
variants: [string, SdkModelType][];
}
| undefined {
const options = type.discriminatedOptions;
const baseType = type.baseType;
if (options?.envelope !== "none" || baseType?.kind !== "model" || type.variants.size === 0) {
return undefined;
}
const variants: [string, SdkModelType][] = [];
let propertyName: string | undefined;
for (const [tag, model] of type.variants) {
if (typeof tag !== "string" || model.kind !== "model") return undefined;
let base = model.baseModel;
while (base && base !== baseType) base = base.baseModel;
if (!base) return undefined;
let owner: SdkModelType | undefined = model;
let property: SdkModelPropertyType | undefined;
while (owner && !property) {
property = owner.properties.find((p) => p.__raw?.name === options.discriminatorPropertyName);
owner = owner.baseModel;
}
if (
property &&
(property.optional || property.type.kind !== "constant" || property.type.value !== tag)
) {
return undefined;
}
const wireName = property
? (property.serializationOptions.json?.name ?? property.name)
: options.discriminatorPropertyName;
if (propertyName !== undefined && wireName !== propertyName) return undefined;
propertyName = wireName;
variants.push([tag, model]);
}
return propertyName !== undefined ? { baseType, propertyName, variants } : undefined;
}

export function getConstantType(
Expand Down
Loading
Loading