diff --git a/python/paddle/fluid/tests/unittests/dygraph_to_static/test_loop.py b/python/paddle/fluid/tests/unittests/dygraph_to_static/test_loop.py index fabfa8edc3c83aa85a2d9c60bcc6801b5c9a39bd..5c84da8e621be91b434f2926b236e17363f00b30 100644 --- a/python/paddle/fluid/tests/unittests/dygraph_to_static/test_loop.py +++ b/python/paddle/fluid/tests/unittests/dygraph_to_static/test_loop.py @@ -441,5 +441,39 @@ class TestErrorInForLoop(TestTransformForLoop): self.dyfunc = for_loop_dyfunc_not_support +class Net(paddle.nn.Layer): + def __init__(self): + super().__init__() + + self.layer_dict = paddle.nn.LayerDict( + { + "conv1": paddle.nn.Conv2D(3, 3, 1), + "conv2": paddle.nn.Conv2D(3, 3, 1), + "conv3": paddle.nn.Conv2D(3, 3, 1), + } + ) + + def forward(self, x): + out = 0 + for layer_name in self.layer_dict: + out += self.layer_dict[layer_name](x) + return out + + +class TestForLoopMeetDict(unittest.TestCase): + def test_start(self): + + net = Net() + model = paddle.jit.to_static( + net, + input_spec=[ + paddle.static.InputSpec( + shape=[None, 3, 224, 224], dtype='float32' + ) + ], + ) + paddle.jit.save(model, "./inference/inference") + + if __name__ == '__main__': unittest.main() diff --git a/python/paddle/jit/dy2static/convert_operators.py b/python/paddle/jit/dy2static/convert_operators.py index 3ec3dba88df2bcbf479a74c785cfbcbe970b7a4e..328b879c5aab62905fac59e752281a4c05cefc44 100644 --- a/python/paddle/jit/dy2static/convert_operators.py +++ b/python/paddle/jit/dy2static/convert_operators.py @@ -42,10 +42,12 @@ def convert_attr(x, attr): def indexable(x, code=None): if isinstance(x, Variable): return x - if hasattr(x, '__len__') and hasattr(x, '__getitem__'): - return x - if hasattr(x, '__iter__'): + elif hasattr(x, '__iter__'): return [i for i in x] + elif hasattr(x, '__len__') and hasattr( + x, '__getitem__' + ): # used for customed type and non-iterable type. + return x else: raise RuntimeError("X can't be convert into indexable.")