Skip to content
Advertisement

Validate dataclass field with custom defined method?

While working with dataclasses, type hints are good but what I’m looking also for is a Validation of passed values (such as string of max length 50, int with upper limit of 100 etc)

Is there anyway to validate passed value ? For example, Pydantic has these Validators. I’m looking for something native without adding external libraries. My only solution is:

JavaScript

where validate_str is just a custom decorator method to check length of provided value, but then I repeat myself. I would like to pass validator somehow in same row of dataclass attribute as:

JavaScript

Advertisement

Answer

The ideal approach would be to use a modified version of the Validator example from the Python how-to guide on descriptors.

For example:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement