Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

2
Dataclass required field, but value can be nullable?
Post Body

I am testing the contents of some messages, and I have a bit of a conundrum. I have a spec for the messages, which includes a number of required and optional fields (the spec is AsyncAPI 2.5.0, if that helps). The spec gives a number of fields that are explicitly required, but are allowed to have a value of null.

I'm using marshmallow-dataclass to build the schema:

from typing import ClassVar, Type

from marshmallow import Schema
from marshmallow_dataclass import dataclass


@dataclass
class RequiredButNullable:
    Schema: ClassVar[Type[Schema]]
    required_field: str  # Required, cannot be null
    required_but_nullable: int  # this field must be present, but can be null
    some_other_field: float | None  # optional field, can be missing

If I load a valid message with required_but_nullable set to null, it throws a validation error, but if I change the typing to int | None, it allows an invalid message that is missing required_but_nullable.

Is there a way to define a custom type, e.g. Nullable[int], or do I need to add some form of validation function?

Author
Account Strength
100%
Account Age
5 years
Verified Email
Yes
Verified Flair
No
Total Karma
42,840
Link Karma
11,154
Comment Karma
30,795
Profile updated: 6 days ago
Posts updated: 6 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
11 months ago