forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[dynamo] simplify implementation for
functools.reduce
(pytorch#133778)
Pull Request resolved: pytorch#133778 Approved by: https://github.com/jansel ghstack dependencies: pytorch#133712, pytorch#133769
- Loading branch information
1 parent
178e856
commit 37b4bc6
Showing
4 changed files
with
48 additions
and
16 deletions.
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 |
---|---|---|
@@ -0,0 +1,43 @@ | ||
""" | ||
Python polyfills for functools | ||
""" | ||
|
||
import functools | ||
from typing import Callable, Iterable, TypeVar | ||
|
||
from ..decorators import substitute_in_graph | ||
|
||
|
||
_T = TypeVar("_T") | ||
_U = TypeVar("_U") | ||
|
||
|
||
class _INITIAL_MISSING: | ||
pass | ||
|
||
|
||
# Reference: https://docs.python.org/3/library/functools.html#functools.reduce | ||
@substitute_in_graph(functools.reduce) | ||
def reduce( | ||
function: Callable[[_U, _T], _U], | ||
iterable: Iterable[_T], | ||
initial: _U = _INITIAL_MISSING, # type: ignore[assignment] | ||
/, | ||
) -> _U: | ||
it = iter(iterable) | ||
|
||
value: _U | ||
if initial is _INITIAL_MISSING: | ||
try: | ||
value = next(it) # type: ignore[assignment] | ||
except StopIteration: | ||
raise TypeError( | ||
"reduce() of empty iterable with no initial value", | ||
) from None | ||
else: | ||
value = initial | ||
|
||
for element in it: | ||
value = function(value, element) | ||
|
||
return value |
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