Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove Optional typing for arrays. #3

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

axelv
Copy link
Contributor

@axelv axelv commented Jun 2, 2023

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):

  • Remove the Optional[] typing for all arrays (by which I mean elements with max > 1)
  • Use Field(default=...) for required elements
  • Use Field(default_factory=list) for optional array elements
  • use Field(default=None) for optional (non-array) elements

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

axelv added 2 commits June 2, 2023 23:10
Added default factory for optional arrays.
@m0rl
Copy link
Member

m0rl commented Jul 27, 2023

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.

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