Refactor to add TypeBasedDispatcher to simplify dispatching (#2958)

This commit is contained in:
fzyzcjy
2025-01-19 12:13:27 +08:00
committed by GitHub
parent 4d4cdb3fe7
commit 81d27c8e31
3 changed files with 169 additions and 162 deletions

View File

@@ -15,7 +15,7 @@ import urllib.request
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from json import dumps
from typing import Optional, Union
from typing import Any, Callable, List, Optional, Tuple, Type, Union
import numpy as np
import requests
@@ -363,3 +363,14 @@ def terminate_process(process):
def print_highlight(html_content: str):
html_content = str(html_content).replace("\n", "<br>")
display(HTML(f"<strong style='color: #00008B;'>{html_content}</strong>"))
class TypeBasedDispatcher:
def __init__(self, mapping: List[Tuple[Type, Callable]]):
self._mapping = mapping
def __call__(self, obj: Any):
for ty, fn in self._mapping:
if isinstance(obj, ty):
return fn(obj)
raise ValueError(f"Invalid object: {obj}")