Created
November 20, 2023 21:14
-
-
Save mcleantom/2d84d8f936f0d66ef371edf6b212ae91 to your computer and use it in GitHub Desktop.
Pydantic Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"log_class": { | |
"type": "file", | |
"path": "output.txt" | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Application starting |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment