[python] Use generated model names in examples and plain dicts for free-form objects

Merged
TA
9d ago
+47-15

Follow-up to #25106 (the example path oddity noted there).

Problem. toExampleValueRecursive in AbstractPythonCodegen builds the example for an object schema as <package>.models.<underscore(title)>.<title>(. The title is whatever the inline model resolver or the parent property set, so for inline models the path points at a module and class that do not exist, e.g. openapi_client.models._a_post_request_object1_prop2._a_post_request_object1_prop2( for files that are actually a_post_request_object1_prop2.py / APostRequestObject1Prop2. For a free-form type: object property there is no model at all, which is why the petstore samples contain a_property = petstore_api.models.a_property.aProperty() in test_parent.py and test_parent_with_optional_dict.py (the generated field is Dict[str, Any]).

Fix.

  • Build the path with toModelFilename(title) and toModelName(title), the same functions that name the generated files, so the example matches the real module and class.
  • When ModelUtils.isFreeFormObject is true, the example is a plain { } instead of a non-existent model.

Tests.

  • New PythonClientCodegenTest.testExampleValueForInlineObjects covering both cases; fails on master, passes with the change. PythonClientCodegenTest: 99 tests pass.
  • Samples: generated test files are never overwritten, so the stale aProperty example would have stayed in the samples forever. For the seven petstore Python variants I removed only test/test_parent.py and test/test_parent_with_optional_dict.py (both generator output, no manual edits) and regenerated each config one at a time. The diff is exactly the one a_property line per file; the regenerated files compile with py_compile and the example parses with ast.parse.

PR checklist

  • Read the contribution guidelines.
  • Built the project and regenerated the affected Python samples.
  • @mention the technical committee: @cbornet @tomplus @krjakbrjak @fa0311

Summary by cubic

Fixes Python example generation so inline models reference real generated modules and classes, and free-form objects use plain dicts instead of non-existent models.

  • Builds example paths with toModelFilename and toModelName so inline model references match generated files.
  • Returns { } for free-form objects, checking before the title so untitled ones like bare array items also become dicts instead of None.
  • Adds a unit test covering both cases and regenerates the affected petstore samples.