Skip to content

Instantly share code, notes, and snippets.

@mcleantom
Created November 20, 2023 21:14
Show Gist options
  • Save mcleantom/2d84d8f936f0d66ef371edf6b212ae91 to your computer and use it in GitHub Desktop.
Save mcleantom/2d84d8f936f0d66ef371edf6b212ae91 to your computer and use it in GitHub Desktop.
Pydantic Example
from __future__ import annotations
from pydantic import BaseModel, FilePath
import logging
from loguru import logger
import abc
from typing import Literal, Union
from pathlib import Path
import json
class AbstractLogger(abc.ABC):
@abc.abstractmethod
def print(self, x: str) -> None:
...
class AbstractLoggerConfig(BaseModel, abc.ABC):
def create(self) -> AbstractLogger:
...
class PrintLogger(AbstractLogger):
def __init__(self, config: PrintLoggerConfig):
self.config = config
def print(self, x: str) -> None:
print(x)
class PrintLoggerConfig(AbstractLoggerConfig):
type: Literal["print"] = "print"
def create(self) -> PrintLogger:
return PrintLogger(config=self)
class FileLoggerConfig(AbstractLoggerConfig):
type: Literal["file"] = "file"
path: FilePath = "output.txt"
def create(self) -> AbstractLogger:
return FileLogger(config=self)
class FileLogger(AbstractLogger):
def __init__(self, config: FileLoggerConfig):
self.config = config
def print(self, x: str) -> None:
with open(self.config.path, 'w') as f:
f.write(x)
class Application:
def __init__(self, config: ApplicationConfig):
self.config = config
self.logger = self.config.log_class.create()
self.logger.print("Application starting")
class ApplicationConfig(BaseModel):
log_class: Union[PrintLoggerConfig, FileLoggerConfig]
def create(self):
return Application(config=self)
config_path = Path("config.json")
app_config = ApplicationConfig.parse_file(config_path)
app = app_config.create()
{
"log_class": {
"type": "file",
"path": "output.txt"
}
}
Application starting
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment