Skip to content
New issue

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

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

Already on GitHub? # to your account

Option to passthrough UUID type #338

Closed
dapper91 opened this issue Feb 11, 2025 · 4 comments
Closed

Option to passthrough UUID type #338

dapper91 opened this issue Feb 11, 2025 · 4 comments

Comments

@dapper91
Copy link

Is it possible to passthrough UUID type during packing similar to datetime (using OPT_PASSTHROUGH_DATETIME)?

@exg
Copy link
Collaborator

exg commented Feb 14, 2025

I can add a new option to enable passthrough of UUID objects. Can you describe your use case?

@dapper91
Copy link
Author

I would like to be able to pack uuid as bytes using extension type and unpack it back like this:

import dataclasses as dc
from typing import Any
from uuid import UUID, uuid4

import ormsgpack as mp

@dc.dataclass
class Message:
    id: UUID
    ...


PACK_OPTIONS = mp.OPT_PASSTHROUGH_UUID | mp.OPT_PASSTHROUGH_DATACLASS

def default(obj: Any) -> mp.Ext:
    if dc.is_dataclass(obj):
        return mp.Ext(0, mp.packb(dc.astuple(obj), default=default, option=PACK_OPTIONS))
    elif isinstance(obj, UUID):
        return mp.Ext(1, obj.bytes)

    raise TypeError


def ext_hook(tag: int, data: bytes) -> Any:
    if tag == 0:
        return Message(*mp.unpackb(data, ext_hook=ext_hook))
    if tag == 1:
        return UUID(bytes=data)

    raise TypeError


msg1 = Message(id=uuid4())

data = mp.packb(msg1, default=default, option=PACK_OPTIONS)
msg2 = mp.unpackb(data, ext_hook=ext_hook)

assert msg1 == msg2

I can implement it by myself and submit MR if don't have enough time.

@exg
Copy link
Collaborator

exg commented Feb 16, 2025

I would like to be able to pack uuid as bytes using extension type and unpack it back

I see.

I can implement it by myself and submit MR if don't have enough time.

I can do it, but thanks for the offer. I will add the option and release a new version soon.

@exg
Copy link
Collaborator

exg commented Feb 16, 2025

Opened #341.

@exg exg closed this as completed Feb 22, 2025
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants