Skip to content

Commit

Permalink
docs: add type annotations to codebase (#509)
Browse files Browse the repository at this point in the history
Closes #500.

**PR checklist:**
- [x] Make sure to open an issue as a [bug/issue](https://github.com/googleapis/python-pubsub/issues/new/choose) before writing your code!  That way we can discuss the change, evaluate designs, and agree on the general idea
- [x] Ensure the tests and linter pass
- [x] Code coverage does not decrease (if any source code was changed)
- [x] Appropriate docs were updated (if necessary)
  • Loading branch information
plamut committed Oct 1, 2021
1 parent ecbe708 commit 093cabf
Show file tree
Hide file tree
Showing 24 changed files with 805 additions and 636 deletions.
9 changes: 6 additions & 3 deletions google/cloud/pubsub_v1/_gapic.py
Expand Up @@ -15,17 +15,20 @@
from __future__ import absolute_import

import functools
from typing import Callable, Container, Type


def add_methods(source_class, denylist=()):
def add_methods(
source_class: Type, denylist: Container[str] = ()
) -> Callable[[Type], Type]:
"""Add wrapped versions of the `api` member's methods to the class.
Any methods passed in `denylist` are not added.
Additionally, any methods explicitly defined on the wrapped class are
not added.
"""

def wrap(wrapped_fx, lookup_fx):
def wrap(wrapped_fx: Callable, lookup_fx: Callable):
"""Wrap a GAPIC method; preserve its name and docstring."""
# If this is a static or class method, then we do *not*
# send self as the first argument.
Expand All @@ -40,7 +43,7 @@ def wrap(wrapped_fx, lookup_fx):
fx = lambda self, *a, **kw: wrapped_fx(self.api, *a, **kw) # noqa
return functools.wraps(wrapped_fx)(fx)

def actual_decorator(cls):
def actual_decorator(cls: Type) -> Type:
# Reflectively iterate over most of the methods on the source class
# (the GAPIC) and make wrapped versions available on this client.
for name in dir(source_class):
Expand Down
14 changes: 6 additions & 8 deletions google/cloud/pubsub_v1/futures.py
Expand Up @@ -15,6 +15,7 @@
from __future__ import absolute_import

import concurrent.futures
from typing import Any, NoReturn

import google.api_core.future

Expand All @@ -29,27 +30,24 @@ class Future(concurrent.futures.Future, google.api_core.future.Future):
methods in this library.
"""

def running(self):
"""Return ``True`` if the associated Pub/Sub action has not yet completed.
Returns: bool:
"""
def running(self) -> bool:
"""Return ``True`` if the associated Pub/Sub action has not yet completed."""
return not self.done()

def set_running_or_notify_cancel(self):
def set_running_or_notify_cancel(self) -> NoReturn:
raise NotImplementedError(
"Only used by executors from `concurrent.futures` package."
)

def set_result(self, result):
def set_result(self, result: Any):
"""Set the return value of work associated with the future.
Do not use this method, it should only be used internally by the library and its
unit tests.
"""
return super().set_result(result=result)

def set_exception(self, exception):
def set_exception(self, exception: Exception):
"""Set the result of the future as being the given exception.
Do not use this method, it should only be used internally by the library and its
Expand Down
50 changes: 31 additions & 19 deletions google/cloud/pubsub_v1/publisher/_batch/base.py
Expand Up @@ -16,6 +16,14 @@

import abc
import enum
import typing
from typing import Optional, Sequence


if typing.TYPE_CHECKING: # pragma: NO COVER
from google.cloud import pubsub_v1
from google.cloud.pubsub_v1 import types
from google.pubsub_v1 import types as gapic_types


class Batch(metaclass=abc.ABCMeta):
Expand Down Expand Up @@ -50,7 +58,7 @@ def __len__(self):

@staticmethod
@abc.abstractmethod
def make_lock(): # pragma: NO COVER
def make_lock() -> None: # pragma: NO COVER
"""Return a lock in the chosen concurrency model.
Returns:
Expand All @@ -60,17 +68,17 @@ def make_lock(): # pragma: NO COVER

@property
@abc.abstractmethod
def messages(self): # pragma: NO COVER
def messages(self) -> Sequence["gapic_types.PubsubMessage"]: # pragma: NO COVER
"""Return the messages currently in the batch.
Returns:
Sequence: The messages currently in the batch.
The messages currently in the batch.
"""
raise NotImplementedError

@property
@abc.abstractmethod
def size(self): # pragma: NO COVER
def size(self) -> int: # pragma: NO COVER
"""Return the total size of all of the messages currently in the batch.
The size includes any overhead of the actual ``PublishRequest`` that is
Expand All @@ -84,42 +92,45 @@ def size(self): # pragma: NO COVER

@property
@abc.abstractmethod
def settings(self): # pragma: NO COVER
def settings(self) -> "types.BatchSettings": # pragma: NO COVER
"""Return the batch settings.
Returns:
~.pubsub_v1.types.BatchSettings: The batch settings. These are
considered immutable once the batch has been opened.
The batch settings. These are considered immutable once the batch has
been opened.
"""
raise NotImplementedError

@property
@abc.abstractmethod
def status(self): # pragma: NO COVER
def status(self) -> "BatchStatus": # pragma: NO COVER
"""Return the status of this batch.
Returns:
str: The status of this batch. All statuses are human-readable,
all-lowercase strings. The ones represented in the
:class:`BaseBatch.Status` enum are special, but other statuses
are permitted.
The status of this batch. All statuses are human-readable, all-lowercase
strings. The ones represented in the :class:`BaseBatch.Status` enum are
special, but other statuses are permitted.
"""
raise NotImplementedError

def cancel(self, cancellation_reason): # pragma: NO COVER
def cancel(
self, cancellation_reason: "BatchCancellationReason"
) -> None: # pragma: NO COVER
"""Complete pending futures with an exception.
This method must be called before publishing starts (ie: while the
batch is still accepting messages.)
Args:
cancellation_reason (BatchCancellationReason): The reason why this
batch has been cancelled.
cancellation_reason:
The reason why this batch has been cancelled.
"""
raise NotImplementedError

@abc.abstractmethod
def publish(self, message): # pragma: NO COVER
def publish(
self, message: "gapic_types.PubsubMessage"
) -> Optional["pubsub_v1.publisher.futures.Future"]: # pragma: NO COVER
"""Publish a single message.
Add the given message to this object; this will cause it to be
Expand All @@ -129,11 +140,12 @@ def publish(self, message): # pragma: NO COVER
This method is called by :meth:`~.PublisherClient.publish`.
Args:
message (~.pubsub_v1.types.PubsubMessage): The Pub/Sub message.
message: The Pub/Sub message.
Returns:
~google.api_core.future.Future: An object conforming to the
:class:`concurrent.futures.Future` interface.
An object conforming to the :class:`concurrent.futures.Future` interface.
If :data:`None` is returned, that signals that the batch cannot
accept a message.
"""
raise NotImplementedError

Expand Down

0 comments on commit 093cabf

Please sign in to comment.