Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions test/dynamo/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3109,6 +3109,25 @@ def fn(x, y):
y = torch.randn(3, 4)
self.assertEqual(opt_fn(x, y), fn(x, y))

def test_methodcaller(self):
for name, args, kwargs in (
("size", (), {}),
("size", (0,), {}),
("add", (torch.randn(3, 4),), {}),
("add", (torch.randn(3, 4),), {"alpha": 2.0}),
):
with self.subTest(name=name, args=args, kwargs=kwargs):

def fn(x, y):
caller = operator.methodcaller(name, *args, **kwargs)
return caller(x), caller(y)

opt_fn = torch.compile(fullgraph=True)(fn)

x = torch.randn(3, 4)
y = torch.randn(3, 4)
self.assertEqual(opt_fn(x, y), fn(x, y))

def gen_random_range_args(self):
args_count = random.randint(1, 3)
args = [random.randint(-10, 10) for _ in range(args_count)]
Expand Down
14 changes: 13 additions & 1 deletion torch/_dynamo/polyfills/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@


# Most unary and binary operators are handled by BuiltinVariable (e.g., `pos`, `add`)
__all__ = ["attrgetter", "itemgetter"]
__all__ = ["attrgetter", "itemgetter", "methodcaller"]


_T = TypeVar("_T")
Expand Down Expand Up @@ -95,3 +95,15 @@ def getter(obj: Any) -> tuple[Any, ...]: # type: ignore[misc]
return tuple(obj[item] for item in items)

return getter


# Reference: https://docs.python.org/3/library/operator.html#operator.methodcaller
@substitute_in_graph(operator.methodcaller, is_embedded_type=True) # type: ignore[arg-type]
def methodcaller(name: str, /, *args: Any, **kwargs: Any) -> Callable[[Any], Any]:
if not isinstance(name, str):
raise TypeError("method name must be a string")

def caller(obj: Any) -> Any:
return getattr(obj, name)(*args, **kwargs)

return caller
Loading