Validating detailed types in python dataclasses

前端 未结 3 1098
日久生厌
日久生厌 2020-11-27 03:26

Python 3.7 was released a while ago, and I wanted to test some of the fancy new dataclass+typing features. Getting hints to work right is easy enough, with both

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 04:06

    Just found this question.

    pydantic can do full type validation for dataclasses out of the box. (admission: I built pydantic)

    Just use pydantic's version of the decorator, the resulting dataclass is completely vanilla.

    from datetime import datetime
    from pydantic.dataclasses import dataclass
    
    @dataclass
    class User:
        id: int
        name: str = 'John Doe'
        signup_ts: datetime = None
    
    print(User(id=42, signup_ts='2032-06-21T12:00'))
    """
    User(id=42, name='John Doe', signup_ts=datetime.datetime(2032, 6, 21, 12, 0))
    """
    
    User(id='not int', signup_ts='2032-06-21T12:00')
    

    The last line will give:

        ...
    pydantic.error_wrappers.ValidationError: 1 validation error
    id
      value is not a valid integer (type=type_error.integer)
    

提交回复
热议问题