beda-software / fhir-py-types

Convert FHIR StructureDefinition into Python type annotations
BSD 3-Clause "New" or "Revised" License
15 stars 1 forks source link

Remove Optional typing for arrays. #3

Open axelv opened 1 year ago

axelv commented 1 year ago

Optional typing for an array can be annoying because it forces you to check for None each time you want to iterate over a array. A better solution might be (which I implemented in this pull request):

This makes it more convenient to iterate over array elements:

my_bundle = Bundle.parse_file("my_bundle.json")
assert my_bundle.entry is not None, "No entries in this bundle"
for entry in my_bundle_entry:
    pass # do stuff

becomes

my_bundle = Bundle.parse_file("my_bundle.json")
for entry in my_bundle_entry: # entry is always a list
    pass # do stuff

Note that for required elements the default=... will validate that a non-empty list is passed when parsing. More info on this https://docs.pydantic.dev/latest/usage/models/#required-optional-fields

m0rl commented 1 year ago

Thanks for the proposal! I understand the issue (and wonder how much easier things like that would be should we have optional chaining available in python) but I'm afraid with the changes we would also have to have a different BaseModel (that will automatically exclude default_factory generated data on the resource serialization). Which in its turn will make things more complicated.