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

Closed
wants to merge 2 commits into 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.

@ruscoder
Copy link
Member

I like this idea, and it's not an issue to adjust automatic exclude of default factories during serialized since we already have a custom BaseModel

@ruscoder
Copy link
Member

I merged main into your branch and changed the behaviour by getting rid of Ellipsis for literals - because it has broken the resource initialization.

Also, I've adjusted model_dump and model_dump_json by setting exclude_* to true, and exclude_unset removes all default values that were not explicitly set during initialization - it closes the concern of @m0rl

New PR - #21

@ruscoder ruscoder closed this Dec 15, 2024
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.

3 participants