-
-
Notifications
You must be signed in to change notification settings - Fork 988
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Type annotate pyro.poutine.messenger
#3290
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,22 @@ | ||
# Copyright (c) 2017-2019 Uber Technologies, Inc. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
from __future__ import annotations | ||
|
||
from contextlib import contextmanager | ||
from functools import partial | ||
from types import TracebackType | ||
from typing import Any, Callable, Iterator, List, Optional, Type | ||
|
||
from .runtime import _PYRO_STACK | ||
from .runtime import _PYRO_STACK, Message | ||
|
||
|
||
def _context_wrap(context, fn, *args, **kwargs): | ||
def _context_wrap( | ||
context: Messenger, | ||
fn: Callable, | ||
*args: Any, | ||
**kwargs: Any, | ||
) -> Any: | ||
with context: | ||
return fn(*args, **kwargs) | ||
|
||
|
@@ -26,13 +35,17 @@ class _bound_partial(partial): | |
def __init__(self, func): | ||
self.func = func | ||
|
||
def __get__(self, instance, owner): | ||
def __get__( | ||
self, | ||
instance: Optional[object], | ||
owner: Optional[Type[object]] = None, | ||
) -> object: | ||
if instance is None: | ||
return self | ||
return partial(self.func, instance) | ||
|
||
|
||
def unwrap(fn): | ||
def unwrap(fn: Callable) -> Callable: | ||
""" | ||
Recursively unwraps poutines. | ||
""" | ||
|
@@ -61,17 +74,15 @@ class Messenger: | |
Most inference operations are implemented in subclasses of this. | ||
""" | ||
|
||
def __call__(self, fn): | ||
def __call__(self, fn: Callable) -> Callable: | ||
if not callable(fn): | ||
raise ValueError( | ||
"{} is not callable, did you mean to pass it as a keyword arg?".format( | ||
fn | ||
) | ||
f"{fn!r} is not callable, did you mean to pass it as a keyword arg?" | ||
) | ||
wraps = _bound_partial(partial(_context_wrap, self, fn)) | ||
return wraps | ||
|
||
def __enter__(self): | ||
def __enter__(self) -> Messenger: | ||
""" | ||
:returns: self | ||
:rtype: pyro.poutine.Messenger | ||
|
@@ -103,7 +114,12 @@ def __enter__(self): | |
# but it could in principle be enabled... | ||
raise ValueError("cannot install a Messenger instance twice") | ||
|
||
def __exit__(self, exc_type, exc_value, traceback): | ||
def __exit__( | ||
self, | ||
exc_type: Optional[Type[Exception]], | ||
exc_value: Optional[Exception], | ||
traceback: Optional[TracebackType], | ||
) -> None: | ||
""" | ||
:param exc_type: exception type, e.g. ValueError | ||
:param exc_value: exception instance? | ||
|
@@ -146,30 +162,33 @@ def __exit__(self, exc_type, exc_value, traceback): | |
for i in range(loc, len(_PYRO_STACK)): | ||
_PYRO_STACK.pop() | ||
|
||
def _reset(self): | ||
def _reset(self) -> None: | ||
pass | ||
|
||
def _process_message(self, msg): | ||
def _process_message(self, msg: Message) -> None: | ||
""" | ||
:param msg: current message at a trace site | ||
:returns: None | ||
|
||
Process the message by calling appropriate method of itself based | ||
on message type. The message is updated in place. | ||
""" | ||
method = getattr(self, "_pyro_{}".format(msg["type"]), None) | ||
method = getattr(self, f"_pyro_{msg['type']}", None) | ||
if method is not None: | ||
return method(msg) | ||
return None | ||
method(msg) | ||
|
||
def _postprocess_message(self, msg): | ||
method = getattr(self, "_pyro_post_{}".format(msg["type"]), None) | ||
def _postprocess_message(self, msg: Message) -> None: | ||
method = getattr(self, f"_pyro_post_{msg['type']}", None) | ||
if method is not None: | ||
return method(msg) | ||
return None | ||
method(msg) | ||
|
||
@classmethod | ||
def register(cls, fn=None, type=None, post=None): | ||
def register( | ||
cls, | ||
fn: Optional[Callable] = None, | ||
type: Optional[str] = None, | ||
post: Optional[bool] = None, | ||
) -> Callable: | ||
""" | ||
:param fn: function implementing operation | ||
:param str type: name of the operation | ||
|
@@ -197,7 +216,11 @@ def some_function(msg) | |
return fn | ||
|
||
@classmethod | ||
def unregister(cls, fn=None, type=None): | ||
def unregister( | ||
cls, | ||
fn: Optional[Callable] = None, | ||
type: Optional[str] = None, | ||
) -> Optional[Callable]: | ||
""" | ||
:param fn: function implementing operation | ||
:param str type: name of the operation | ||
|
@@ -227,7 +250,9 @@ def unregister(cls, fn=None, type=None): | |
|
||
|
||
@contextmanager | ||
def block_messengers(predicate): | ||
def block_messengers( | ||
predicate: Callable[[Messenger], bool] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is great! |
||
) -> Iterator[List[Messenger]]: | ||
""" | ||
EXPERIMENTAL Context manager to temporarily remove matching messengers from | ||
the _PYRO_STACK. Note this does not call the ``.__exit__()`` and | ||
|
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should we be more precise and allow passing of type information?