2023-08-02 20:19:16 +08:00
|
|
|
from pydantic import BaseModel
|
2023-08-02 14:24:28 +08:00
|
|
|
from typing import Optional
|
|
|
|
|
2023-08-02 18:32:22 +08:00
|
|
|
|
2023-08-02 20:19:16 +08:00
|
|
|
class AllOptional(type(BaseModel)):
|
2023-08-02 14:24:28 +08:00
|
|
|
def __new__(cls, name, bases, namespaces, **kwargs):
|
|
|
|
annotations = namespaces.get('__annotations__', {})
|
|
|
|
for base in bases:
|
2023-08-02 20:19:16 +08:00
|
|
|
annotations.update(getattr(base, '__annotations__', {}))
|
2023-08-02 14:24:28 +08:00
|
|
|
for field in annotations:
|
|
|
|
if not field.startswith('__'):
|
|
|
|
annotations[field] = Optional[annotations[field]]
|
|
|
|
namespaces['__annotations__'] = annotations
|
2023-08-02 20:19:16 +08:00
|
|
|
|
|
|
|
# Set default values
|
|
|
|
for field in annotations:
|
|
|
|
if not field.startswith('__') and field not in namespaces:
|
|
|
|
namespaces[field] = None # set default value to None only if it's not already set
|
|
|
|
|
2023-08-02 14:24:28 +08:00
|
|
|
return super().__new__(cls, name, bases, namespaces, **kwargs)
|