chore: enable mypy v2 pre-commit hook; fix all lint/type errors it surfaces#31
Open
Siddharth Mitra (sidmitra) wants to merge 15 commits into
Open
chore: enable mypy v2 pre-commit hook; fix all lint/type errors it surfaces#31Siddharth Mitra (sidmitra) wants to merge 15 commits into
Siddharth Mitra (sidmitra) wants to merge 15 commits into
Conversation
|
| Status | Scan Engine | Total (0) | ||||
|---|---|---|---|---|---|---|
| Open Source Security | 0 | 0 | 0 | 0 | See details | |
| Licenses | 0 | 0 | 0 | 0 | See details | |
| ✅ | Code Security | 0 | 0 | 0 | 0 | 0 issues |
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.
646a4e5 to
f8dd194
Compare
Allu Venkata Harshavardhan Reddy (avhvr)
approved these changes
May 14, 2026
cdcf0c9 to
69216b6
Compare
c7ee085 to
cb7e548
Compare
cb7e548 to
d9a1977
Compare
Uncomment and upgrade the mirrors-mypy pre-commit hook from the previously commented-out v0.902 stub to v2.1.0.
pyproject.toml: - Remove show_none_errors (dropped in mypy v2) eventbusk/brokers/base.py: - Remove stale # type: ignore on poll() and produce() abstract methods eventbusk/brokers/dummy.py: - Add missing 'return None' in Consumer.poll() eventbusk/bus.py: - Add 'from typing import Any' and annotate EventJsonEncoder.default() - Annotate self.producer as BaseProducer | None (Producer is a factory function, not a class; use the base type for the annotation) - Import BaseProducer from .brokers - Remove stale # type: ignore on event_type(**event_data) eventbusk/brokers/__init__.py: - Export BaseProducer in __all__ so bus.py import resolves cleanly
New options made explicit (all at their defaults): allow_redefinition_old = false extra_checks = false follow_untyped_imports = false no_strict_bytes = false report_deprecated_as_note = false show_error_code_links = false show_error_end = false strict_equality_for_none = false Also fix double-space typo in local_partial_types key.
pyproject.toml: - Remove suggestion-mode (dropped in pylint v4) eventbusk/brokers/__init__.py: - Add pylint: disable=invalid-name on Consumer/Producer factory aliases (PascalCase names are intentional public API, not classes) eventbusk/brokers/base.py + dummy.py + kafka.py: - Make flush/on_delivery/fail_silently keyword-only args in produce() to satisfy R0917 too-many-positional-arguments; all callers already used keyword syntax so no call-site changes needed eventbusk/brokers/dummy.py: - Move pylint: disable=useless-return to def line (R1711 is reported there); keep explicit return None to satisfy mypy warn_no_return eventbusk/brokers/kafka.py: - Add pylint: disable=catching-non-exception on except KafkaError - Add pylint: disable=bad-exception-cause on raise ProducerError from exc (KafkaError is a C-extension type; pylint can't verify its hierarchy) eventbusk/bus.py: - Annotate HooksT with TypeAlias and add inline invalid-name disable (union alias HooksT not recognised as TypeAlias by pylint naming check) - Add pylint: disable=too-many-branches on wrapper() (16 branches, limit 15) - Add public before_receive_hooks / after_receive_hooks properties tests/test_brokers.py: - Add pylint: disable=raising-non-exception on raise KafkaError(...) tests/test_bus.py: - Use public before_receive_hooks / after_receive_hooks properties - Simplify empty-list checks to 'not bus.before/after_receive_hooks' - Add pylint: disable=no-value-for-parameter on foo_processor() calls (decorator transforms signature; pylint doesn't see the wrapper)
Move inline disable comments to pylint: disable-next= on preceding line to keep lines within the 88-character flake8 limit.
d9a1977 to
5ce1a8f
Compare
There was a problem hiding this comment.
Pull request overview
This PR enables the mypy v2 pre-commit hook (upgrading from the previously commented-out stub) and updates code/config to satisfy the stricter type-checking and linting results across the project.
Changes:
- Enable and pin
mirrors-mypyv2.1.0 in pre-commit and update mypy/pylint configuration accordingly. - Tighten typing in the event bus and broker interfaces (e.g., producer type, JSON encoder typing, broker API signatures).
- Adjust broker modules/exports to satisfy typing and lint rules.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
pyproject.toml |
Updates mypy configuration for v2 (removes deprecated options, adds explicit new defaults). |
eventbusk/bus.py |
Adds type annotations/properties and tweaks event reconstruction / producer typing. |
eventbusk/brokers/base.py |
Updates abstract broker interfaces (removes stale ignores; adjusts produce signature). |
eventbusk/brokers/__init__.py |
Exports BaseProducer via __all__ for typed imports. |
eventbusk/brokers/dummy.py |
Adds explicit return None in poll() to satisfy mypy/pylint. |
eventbusk/brokers/kafka.py |
Adds targeted pylint suppression on exception chaining line. |
.pre-commit-config.yaml |
Enables mypy hook and pins to v2.1.0. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
+278
to
+281
| # TODO: Fix following | ||
| # Too many arguments for "Event" [call-arg] | ||
| event = event_type(**event_data) # type: ignore | ||
| event.event_id = event_id | ||
| event = event_type(**event_data) | ||
| setattr(event, "event_id", event_id) |
Both packages now ship py.typed and full stubs, making the blanket
# type: ignore comments on their imports unused. Removing them exposed
real type errors that are fixed here:
brokers/base.py:
- Drop # type: ignore on 'from confluent_kafka import cimpl'
brokers/kafka.py:
- Drop # type: ignore on confluent_kafka import block
- Import Message as CMessage and cast from typing (needed for fixes below)
- _consumer: CConsumer | None = None (was missing | None)
- __exit__: guard close() with 'if self._consumer is not None'
- poll/ack: assert self._consumer is not None (documents context-manager invariant)
- ack: cast(CMessage, message) so commit(message=) gets the right type
- produce: assert isinstance(value, (str, bytes)) to narrow away cimpl.Message;
CProducer.produce() only accepts str | bytes
- Drop stale # pylint: disable=bad-exception-cause; pylint 4.0.5 with
--extension-pkg-whitelist resolves KafkaException's hierarchy correctly
cli.py:
- Drop # type: ignore on 'import cotyledon' and class Worker definition
- Import WorkerId from cotyledon.types; pass WorkerId(worker_id) to super().__init__()
- self.name assignment: # type: ignore[misc] (intentional instance-level
shadow of cotyledon.Service's ClassVar[str])
- Replace assert guards in Consumer.poll/ack with RuntimeError and in Producer.produce with TypeError (ruff S101; assert is banned outside tests) - Move `Message as CMessage` to TYPE_CHECKING block — it is only referenced in string-form cast() calls so pylint flagged it as unused - Add mypy per-module overrides (ignore_missing_imports) for confluent_kafka and cotyledon — neither ships stubs in the mypy env, contradicting the earlier PR assumption - Move `# type: ignore[misc]` from self.name assignment to the class definition line in cli.py, where mypy actually fires (subclassing Any) - Wrap long logger.exception() call in bus.py (ruff E501 / ruff-format)
| # Trigger any available delivery report callbacks from previous produce | ||
| self._producer.poll(0) | ||
| if not isinstance(value, (str, bytes)): | ||
| raise TypeError(f"Expected str or bytes, got {type(value).__name__}") |
Contributor
Author
There was a problem hiding this comment.
I think the type hint is wrong here. It should be str/bytes. since we do json.dumps
Message is not true.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Uncomments and upgrades the
mirrors-mypypre-commit hook from the previously disabledv0.902stub to v2.1.0, then fixes every error surfaced by running it and the full pre-commit suite.mypy v2 — config
8 options new in mypy v2 added to
[tool.mypy](all at their defaults). Removedshow_none_errorswhich was deleted in v2.Per-module
ignore_missing_importsoverrides added forconfluent_kafkaandcotyledon— neither package ships type stubs orpy.typedin the mypy environment.mypy v2 — source fixes
brokers/base.py# type: ignoreonpoll()abstract methodbrokers/__init__.pyBaseProducernot in__all__(implicit_reexport=false)brokers/dummy.pyreturn Noneinpoll()(warn_no_return)return Nonebrokers/kafka.py_consumertyped asCConsumerbut initialised toNoneCConsumer | Nonebrokers/kafka.pycommit(message=)getsstr | bytes | Message | None, expectsMessagecast("CMessage", message)afterNonecheckbus.pyEventJsonEncoder.default()unannotated(self, o: Any) -> Anybus.pyself.producertyped as bareNoneBaseProducer | Nonecli.pysuper().__init__(worker_id)passesint, expectsWorkerIdWorkerId(worker_id)viafrom cotyledon.types import WorkerIdcli.pyclass Worker(cotyledon.Service)subclassesAny-typed base# type: ignore[misc]on class definitionpylint v4 — fixes
brokers/base.pyflush/on_delivery/fail_silentlykeyword-onlybrokers/dummy.pydisable-next=useless-returntodeflinebrokers/kafka.py# pylint: disable=catching-non-exceptiononexcept KafkaErrorbus.py# pylint: disable=too-many-branchesonreceive()ruff S101 — assert replacements
assertis banned outside tests by ruff rule S101. Replaced three bare asserts inbrokers/kafka.pywith explicit exceptions:Consumer.poll/Consumer.ack— consumer-not-open guardraise RuntimeError("Consumer is not open. Use as a context manager.")Producer.produce— value type narrowingraise TypeError(f"Expected str or bytes, got {type(value).__name__}")Message as CMessagewas also moved from the runtime import to theTYPE_CHECKINGblock, since it is only referenced in string-formcast()calls (fixing pylint W0611 unused-import).