Skip to content

Improve typing coverage of middleware classes - #735

Merged
LincolnPuzey merged 1 commit into
Bogdanp:masterfrom
jenstroeger:add-middleware-typing
Jul 28, 2025
Merged

LincolnPuzey merged 1 commit into
Bogdanp:masterfrom
jenstroeger:add-middleware-typing

Conversation

@jenstroeger

@jenstroeger jenstroeger commented Jul 14, 2025 •

Copy link
Copy Markdown
Contributor

Closes #521

Following up on comment #731 (comment). Alas, I am not familiar enough with Sphinx to work with the NameError caused by the missing (typing only) imports (perhaps related issue sphinx-doc/sphinx#13137).

Comment thread dramatiq/middleware/middleware.py Resolved
@LincolnPuzey

Copy link
Copy Markdown
Collaborator

Alas, I am not familiar enough with Sphinx to work with the NameError caused by the missing (typing only) imports

I think the NameError happens when importing the module - which is why it happens in all the tests too.

The problem is that the Broker annotation used here (and later)

def before_ack(self, broker: Broker, message: Message) -> None:

is evaluated as an expression, but the Broker class is not actually imported, since the import is in the if TYPE_CHECKING guard. So the expression evaluation gives a NameError.

I think if you rebase this now that #737 is merged, the errors should go away.

@jenstroeger
jenstroeger force-pushed the add-middleware-typing branch 2 times, most recently from c9bffc5 to 74c9639 Compare July 24, 2025 13:39
Comment thread dramatiq/middleware/middleware.py Resolved
@jenstroeger

Copy link
Copy Markdown
Contributor Author

@LincolnPuzey this PR adds type annotations only to the Middleware base class. Shall we leave the sub-classes alone for now and consider them “internal”, or type them also?

@jenstroeger
jenstroeger requested a review from LincolnPuzey July 24, 2025 13:58
@LincolnPuzey

LincolnPuzey commented Jul 25, 2025 •

Copy link
Copy Markdown
Collaborator

Shall we leave the sub-classes alone for now and consider them “internal”, or type them also?

Totally up to you. I would suggest typing the __init__ methods since those are public interface. (as opposed to the hook implementations which are called internally by dramatiq).

@LincolnPuzey

Copy link
Copy Markdown
Collaborator

(oops clicked wrong button)

@jenstroeger

Copy link
Copy Markdown
Contributor Author

I would suggest typing the __init__ methods since those are public interface. (as opposed to the hook implementations which are called internally by dramatiq).

Agreed, done. This PR requires #743 to pass CI though.

Comment thread dramatiq/middleware/retries.py Resolved
Comment thread dramatiq/middleware/middleware.py Outdated
return []

def before_ack(self, broker, message):
def before_ack(self, broker: Broker, message: Message) -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think for before/after ack/nack, it should use MessageProxy, rather than Message

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have to dig some more through the code but at a first glance I didn’t quite find all the locations where these events are issued by the various brokers… 🤔

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its inside the _ConsumerThread of the Worker

dramatiq/dramatiq/worker.py

Lines 365 to 386 in 5c492e4

def post_process_message(self, message: MessageProxy):
"""Called by worker threads whenever they're done processing
individual messages, signaling that each message is ready to
be acked or rejected.
"""
if TYPE_CHECKING:
assert self.consumer
while True:
try:
if message.failed:
self.logger.debug("Rejecting message %r.", message.message_id)
self.broker.emit_before("nack", message)
self.consumer.nack(message)
self.broker.emit_after("nack", message)
else:
self.logger.debug("Acknowledging message %r.", message.message_id)
self.broker.emit_before("ack", message)
self.consumer.ack(message)
self.broker.emit_after("ack", message)
return

Comment thread dramatiq/middleware/middleware.py Resolved
Comment thread dramatiq/middleware/shutdown.py Resolved
raise_thread_exception(thread_id, Shutdown)


_GeventShutdownManager: Optional[Type[_ShutdownManager]] = None

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rather than adding the if TYPE_CHECKING block,
can you try changing just this first line to
_GeventShutdownManager: Type[_ShutdownManager]

so rather than _GeventShutdownManager being either None/the actual class (two different types),
it is undefined / the actual class (which is one type).

@jenstroeger jenstroeger Jul 27, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm. Looking at the code I assume that the intention of

_GeventShutdownManager = None
if is_gevent_active():   
    ...
    _GeventShutdownManager = __GeventShutdownManager

is to make the name available for the middleware initialization. But both uses of _GeventShutdownManager are guarded by is_gevent_active(). So, I removed the module variable _GeventShutdownManager and renamed the class __GeventShutdownManager to _GeventShutdownManager and the code still checks and tests just fine on my local machine:

=================================== 175 passed, 131 skipped, 1 warning in 241.83s (0:04:01) ===================================

Let me push the changes, and please do take a careful look as well.

Addendum: similar pattern here:

_GeventTimeout: Optional["gevent.Timeout"] = None
if is_gevent_active():
from gevent import Timeout
class __GeventTimeout(Timeout):
"""Cooperative timeout class for gevent with logging on timeouts."""
def __init__(self, *args, logger=None, thread_id=None, after_expiration=None, **kwargs):
super().__init__(*args, **kwargs)
self.logger = logger or get_logger(__name__, type(self))
self.thread_id = thread_id
self.after_expiration = after_expiration
def _on_expiration(self, prev_greenlet, ex):
self.logger.warning(
"Time limit exceeded. Raising exception in worker thread %r.",
self.thread_id,
)
res = super()._on_expiration(prev_greenlet, ex)
if self.after_expiration is not None:
self.after_expiration()
return res
_GeventTimeout = __GeventTimeout
but the _GeventTimeoutManager class isn’t guarded.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmmm I can't see a reason for __GeventShutdownManager.
It is clearly a private name, so I'm happy to get rid of it.

Overall I think this is a good simplification.

@jenstroeger
jenstroeger force-pushed the add-middleware-typing branch 2 times, most recently from 0a83892 to ecde645 Compare July 27, 2025 09:26

@LincolnPuzey LincolnPuzey left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing all those comments :)

@LincolnPuzey LincolnPuzey changed the title Improve typing on middleware functions Improve typing coverage of middleware classes Jul 28, 2025
@LincolnPuzey
LincolnPuzey merged commit 7b10ff4 into Bogdanp:master Jul 28, 2025
@jenstroeger

Copy link
Copy Markdown
Contributor Author

@LincolnPuzey do you know when you folks might release the new Dramatiq package with all the typing?

@LincolnPuzey

Copy link
Copy Markdown
Collaborator

@jenstroeger There is no planned date. You can always install from the master branch in the meantime

@vitosamson

Copy link
Copy Markdown

@LincolnPuzey is there a cadence that you follow for releases or is the process totally ad hoc? We can't install from the master branch for a production application but we'd love to pull in this and other changes. Would it be possible to cut a release sometime in the near future? The last release was three months ago.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FeatReq: Typehints in dramatiq.middleware

3 participants