Skip to content
This repository has been archived by the owner on Aug 19, 2023. It is now read-only.

Support nullable fields #57

Closed
s-knibbs opened this issue Jun 14, 2019 · 1 comment · Fixed by #78
Closed

Support nullable fields #57

s-knibbs opened this issue Jun 14, 2019 · 1 comment · Fixed by #78
Labels
enhancement New feature or request

Comments

@s-knibbs
Copy link
Owner

There should be an option to allow nullable fields. I propose the following api:

@dataclass
class Address(JsonSchemaMixin):
    company: Optional[str] = field(default=None, metadata=dict(nullable=True))
    building: str
    street: str
    ...

There are a couple of ways to support nullable fields in JSON schema, either:

{
  "properties": {
    "company": {"type": ["string", "null"]}
  }
}

or:

{
  "properties": {
    "company": {"oneOf": [{"type": "string"}, {"type": "null"}]}
  }
}

The former is not supported in Swagger / OpenAPI though. OpenAPI 3 also supports the following:

{
  "properties": {
    "company": {"type": "string", "nullable": true}
  }
}
@HHK1
Copy link

HHK1 commented Sep 30, 2020

@s-knibbs

I've encountered an issue with the Nullable type.

What I would like to achieve is to allow Null values to be passed during instantiation with from_dict, but that they remain filtered out.

@dataclass
class WithOptional(JSONSchemaMixin):
    my_field: Optional[str]


WithOptional.from_dict({ "my_field": None }) # Error, None is not of type str

@dataclass
class WithNullable(JSONSchemaMixin):
    my_field: Nullable[str]

WithNullable.from_dict({ "my_field": None }) # Works
WithNullable.from_dict({ "my_field": None }).to_dict() # Includes { "my_field": None }, which is not what I want either

Is there a way to achieve this somehow ? I understand the need for Nullable, but I don't get why optional would fail to init with an explicit null value.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants