pytorch
873cc7a4 - Support 3 argument variant of the getattr() call where the third arg is the default return value (#61599)

Commit
3 years ago
Support 3 argument variant of the getattr() call where the third arg is the default return value (#61599) Summary: Issue: https://github.com/pytorch/pytorch/issues/56909 Note the emitted code for such a call will either be a) getattr() call with first two args if the attribute name (which must be a string literal) is determined to be valid based on the hasAttr() result, or b) just the AST node for the default value (the 3rd arg) alone with no getattr call at all. Test code: ``` import torch import numpy as np class Shape: def __init__(self): self.center = 1.0 def f(x): s = Shape() return getattr(s, "missing", []) y = torch.jit.script(f) print(y.graph) ``` Output: ``` graph(%x : Tensor): %s.1 : __torch__.Shape = prim::CreateObject() %2 : NoneType = prim::CallMethod[name="__init__"](%s.1) # ts.py:10:8 %4 : Tensor[] = prim::ListConstruct() return (%4) ``` Another example: ``` import torch class Shape: def __init__(self): self.center = 1.0 def f(x): s = Shape() y = getattr(s, "center") w : list[float] = [1.0] z = getattr(s, "missing", w) z.append(y) return z y = torch.jit.script(f) print(y.graph) --- output --- graph(%x : Tensor): %5 : float = prim::Constant[value=1.]() # ts.py:12:23 %s.1 : __torch__.Shape = prim::CreateObject() %2 : NoneType = prim::CallMethod[name="__init__"](%s.1) # ts.py:10:8 %center : float = prim::GetAttr[name="center"](%s.1) %w.1 : float[] = prim::ListConstruct(%5) %11 : float[] = aten::append(%w.1, %center) # ts.py:14:4 return (%w.1) ``` Fixes #{56969} Pull Request resolved: https://github.com/pytorch/pytorch/pull/61599 Reviewed By: ZolotukhinM Differential Revision: D29776058 Pulled By: jerryzhenleicai fbshipit-source-id: 76333bd54002e08a064677c1f287115a80cc7c8e
Author
Jerry Cai
Parents
Loading