Skip to content

Commit

Permalink
message: add namedtuple methods for backwards-compat
Browse files Browse the repository at this point in the history
Thanks to @jurrian for identifying the issue in Bogdanp/django_dramatiq#143
  • Loading branch information
Bogdanp committed Mar 25, 2023
1 parent 4fcbf7e commit 96b4a47
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
16 changes: 15 additions & 1 deletion dramatiq/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import dataclasses
import time
import uuid
from typing import Any, Dict, Generic, Optional, TypeVar
from typing import Any, Dict, Generic, Optional, Tuple, TypeVar

from .broker import get_broker
from .composition import pipeline
Expand Down Expand Up @@ -182,3 +182,17 @@ def __str__(self) -> str:

def __lt__(self, other: "Message") -> bool:
return dataclasses.astuple(self) < dataclasses.astuple(other)

# Backwards-compatibility with namedtuple.
_asdict = asdict

@property
def _field_defaults(self) -> Dict[str, Any]:
return {f.name: f.default for f in dataclasses.fields(self) if f.default is not dataclasses.MISSING}

@property
def _fields(self) -> Tuple[str, ...]:
return tuple(f.name for f in dataclasses.fields(self))

def _replace(self, **changes) -> "Message[R]":
return dataclasses.replace(self, **changes)
24 changes: 24 additions & 0 deletions tests/test_messages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import dramatiq


def test_messages_have_namedtuple_methods(stub_broker):
@dramatiq.actor
def add(x, y):
return x + y

msg1 = add.message(1, 2)
assert msg1.asdict() == msg1._asdict()

assert msg1._field_defaults == {}
assert msg1._fields == (
"queue_name",
"actor_name",
"args",
"kwargs",
"options",
"message_id",
"message_timestamp",
)

msg2 = msg1._replace(queue_name="example")
assert msg2._asdict()["queue_name"] == "example"

0 comments on commit 96b4a47

Please sign in to comment.