Skip to content

py: generics#164

Open
MikhailArtemyev wants to merge 6 commits into
mainfrom
py-generics
Open

py: generics#164
MikhailArtemyev wants to merge 6 commits into
mainfrom
py-generics

Conversation

@MikhailArtemyev
Copy link
Copy Markdown
Collaborator

Generator changes

  • Python generator reads schema.generic?.params from the IR and
    emits TypeVar declarations and Generic[T1, T2] superclasses for
    Bundle, BundleEntry, BundleEntryResponse, and DomainResource
  • Resource-typed fields (BundleEntry.resource,
    DomainResource.contained) become TypeVars instead of
    ResourceFamily
  • New static asset resource_preprocessor.py — copied per FHIR
    package when any schema has resource generic params
  • Each generic class gets a model_validator(mode='before') calling
    preprocess_resource_fields, restoring polymorphic dispatch by
    resourceType for bare Bundle.from_json() usage
  • Removed resource_family_validator.py asset and all
    resource_families.py generation — ResourceFamily types fully
    replaced

Before / after

Resource field type:

# Before
entry: ResourceFamily | None
                         
# After
entry: T1 | None  # T1 = TypeVar('T1', bound=Resource,
default=Resource)

Bare Bundle.from_json() now works again:
bundle = Bundle.from_json('{"type":"collection","entry":[{"resource":
{"resourceType":"Patient","id":"p-1"}}]}')
assert type(bundle.entry[0].resource) is Patient

# Typed usage narrows statically
bundle: Bundle[Patient] =
Bundle[Patient].model_validate(response.json())

Tests                    

- Added test_bundle.pyruntime tests for Bundle[T] type narrowing
- Added test_bundle_from_json in test_sdk.pyverifies bare
Bundle.from_json polymorphic dispatch
- Fixed client.search to use model_validate (dict) instead of
from_json (string)
- Fixed mypy strict error in client.py with # type: 
ignore[valid-type] for runtime generic subscript

…or polymorphic Bundl .from_json dispatch

py: regenerate Python examples with generic Bundle and resource_preprocessor

test: verify Bundle[T] type narrowing and bare Bundle.from_json

py: updated examples
Copy link
Copy Markdown
Collaborator

@ryukzak ryukzak left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice job!

Comment thread examples/python/test_bundle.py
Comment thread examples/python/test_sdk.py Outdated
Comment thread test/api/write-generator/python.test.ts Outdated
Comment thread examples/python/client.py Outdated
Comment thread src/api/writer-generator/python.ts Outdated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants