Skip to content
Merged
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
12 changes: 6 additions & 6 deletions haystack/dataclasses/byte_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from typing import Any, Self

from haystack.utils.dataclasses import _warn_on_inplace_mutation
from haystack.utils.misc import _guess_mime_type
Expand Down Expand Up @@ -41,7 +41,7 @@ def from_file_path(
mime_type: str | None = None,
meta: dict[str, Any] | None = None,
guess_mime_type: bool = False,
) -> "ByteStream":
) -> Self:
"""
Create a ByteStream from the contents read from a file.

Expand All @@ -58,7 +58,7 @@ def from_file_path(
@classmethod
def from_string(
cls, text: str, encoding: str = "utf-8", mime_type: str | None = None, meta: dict[str, Any] | None = None
) -> "ByteStream":
) -> Self:
"""
Create a ByteStream encoding a string.

Expand Down Expand Up @@ -113,12 +113,12 @@ def _to_trace_dict(self) -> dict[str, Any]:
return {"data": f"Binary data ({len(self.data)} bytes)", "meta": self.meta, "mime_type": self.mime_type}

@classmethod
def from_dict(cls, data: dict[str, Any]) -> "ByteStream":
def from_dict(cls, data: dict[str, Any]) -> Self:
"""
Create a ByteStream from a dictionary representation.

:param data: A dictionary with keys 'data', 'meta', and 'mime_type'.

:returns: A ByteStream instance.
:returns: An instance of this class.
"""
return ByteStream(data=bytes(data["data"]), meta=data.get("meta", {}), mime_type=data.get("mime_type"))
return cls(data=bytes(data["data"]), meta=data.get("meta", {}), mime_type=data.get("mime_type"))
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
fixes:
- |
``ByteStream.from_dict()`` now preserves subclasses when deserializing a
dictionary, instead of always returning a ``ByteStream`` instance.
11 changes: 11 additions & 0 deletions test/dataclasses/test_byte_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,17 @@ def test_from_dict():
assert str(b2) == str(b)


def test_from_dict_preserves_subclass():
class CustomByteStream(ByteStream):
pass

original = CustomByteStream.from_string("Hello, world!", mime_type="text/plain", meta={"foo": "bar"})
restored = CustomByteStream.from_dict(original.to_dict())

assert isinstance(restored, CustomByteStream)
assert restored.to_dict() == original.to_dict()


def test_no_warning_on_init():
with warnings.catch_warnings():
warnings.simplefilter("error", Warning)
Expand Down
Loading