From 7d98cef31349063eced470edfef54cfe130a718d Mon Sep 17 00:00:00 2001 From: Matthias Kind Date: Sat, 12 Oct 2024 12:42:54 +0200 Subject: [PATCH] fix: serialize typing classes assigned to fields --- langfuse/serializer.py | 8 ++++++++ tests/test_serializer.py | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/langfuse/serializer.py b/langfuse/serializer.py index 200cd809..9057e53e 100644 --- a/langfuse/serializer.py +++ b/langfuse/serializer.py @@ -6,6 +6,7 @@ import enum from json import JSONEncoder from typing import Any +import typing from uuid import UUID from collections.abc import Sequence from langfuse.api.core import serialize_datetime @@ -107,6 +108,13 @@ def default(self, obj: Any): if isinstance(obj, Sequence): return [self.default(item) for item in obj] + # typing.get_origin only available in Python 3.8 and above + try: + if isinstance(obj, type) or typing.get_origin(obj) is not None: + return f"<{getattr(obj, 'name', str(obj))}>" + except Exception: + pass + if hasattr(obj, "__slots__"): return self.default( {slot: getattr(obj, slot, None) for slot in obj.__slots__} diff --git a/tests/test_serializer.py b/tests/test_serializer.py index e0156153..4c3775fe 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -1,4 +1,5 @@ from datetime import datetime, date, timezone +import typing from uuid import UUID from enum import Enum from dataclasses import dataclass @@ -182,6 +183,17 @@ def __init__(self): assert json.loads(serializer.encode(obj)) == {"field": "value"} +def test_slots_types(): + class SlotClass: + def __init__(self): + self.something = typing.Sequence[int] + + obj = SlotClass() + + serializer = EventSerializer() + assert json.loads(serializer.encode(obj)) == {"something": ""} + + def test_numpy_float32(): import numpy as np