Skip to content

Allow None in optional dataclass fields - #555

Open
x0Lazarus wants to merge 1 commit into
alecthomas:masterfrom
x0Lazarus:fix/nullable-dataclass-fields
Open

x0Lazarus wants to merge 1 commit into
alecthomas:masterfrom
x0Lazarus:fix/nullable-dataclass-fields

Conversation

@x0Lazarus

Copy link
Copy Markdown

A dataclass field declared as nickname: Optional[str] = None currently fails validation when its value is None, including when the default is used. Both DataclassSchema and create_dataclass_schema raise MultipleInvalid: expected str because annotation handling drops the None alternative.

Keep that alternative in the field validator so an omitted default or an explicit None can produce the expected dataclass instance. Fields without defaults still require a key, nonnullable fields still reject None, and additional constraints still apply.

Six new cases fail before the change; all eight regression cases pass afterward. On Windows with Python 3.12, the normal suite passes 190 tests, and the existing 19 dataclass tests also pass when invoked explicitly. Black, isort, Flake8 and Mypy pass. The regressions are in the normally collected test file; other platforms and Python versions were not run locally.

This branch has not been deployed

No deployments
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.

1 participant