Source code for confluent_kafka.common.topic_partition
# Copyright 2025 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""``TopicPartition``: Java's ``org.apache.kafka.common.TopicPartition``."""
from __future__ import annotations
import functools
from typing import Any
from confluent_kafka._java import java_str
__all__ = ["TopicPartition"]
[docs]
class TopicPartition:
"""A topic name and partition number.
Java: ``org.apache.kafka.common.TopicPartition``. Immutable, with value
equality, so it can key a ``dict``.
"""
__slots__ = ("_partition", "_topic")
def __init__(self, *, topic: str, partition: int) -> None:
self._partition = partition
self._topic = topic
@classmethod
def _of(cls, topic: str, partition: int) -> TopicPartition:
"""What ``__init__`` builds, without its keyword call: for the client,
which builds one per completed record (``RecordMetadata._from_ffi``)."""
self = cls.__new__(cls)
self._partition = partition
self._topic = topic
return self
[docs]
def partition(self) -> int:
return self._partition
[docs]
def topic(self) -> str:
return self._topic
def __hash__(self) -> int:
return hash((self._partition, self._topic))
def __eq__(self, other: object) -> bool:
if self is other:
return True
if type(other) is not type(self):
return NotImplemented
assert isinstance(other, TopicPartition)
return self._partition == other._partition and self._topic == other._topic
def __str__(self) -> str:
return java_str(self._topic) + "-" + str(self._partition)
def __reduce__(self) -> tuple[Any, ...]:
"""Rebuild through the public constructor by keyword (``pickle``,
``copy``): Java's class is ``Serializable``, and its cached ``hash``
field is not saved (CLAUDE.md, Python Binding Conventions, Types, JDK
interfaces)."""
return (functools.partial(type(self), topic=self._topic, partition=self._partition), ())