Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: serialize typing classes assigned to fields #963

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions langfuse/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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__}
Expand Down
12 changes: 12 additions & 0 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from datetime import datetime, date, timezone
import typing
from uuid import UUID
from enum import Enum
from dataclasses import dataclass
Expand Down Expand Up @@ -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": "<typing.Sequence[int]>"}


def test_numpy_float32():
import numpy as np

Expand Down