From bedcf074a2c497afeb057cb8a1ecfaa3eb39a7dd Mon Sep 17 00:00:00 2001 From: Yu Yang Date: Mon, 9 Oct 2017 10:37:31 -0700 Subject: [PATCH] Implementation singleton --- python/paddle/v2/framework/graph.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/python/paddle/v2/framework/graph.py b/python/paddle/v2/framework/graph.py index 5211b0f16..746827943 100644 --- a/python/paddle/v2/framework/graph.py +++ b/python/paddle/v2/framework/graph.py @@ -18,9 +18,18 @@ class Block(object): class Program(object): + @classmethod + def instance(cls): + # From https://stackoverflow.com/questions/8212053 + # Making Program as a Singleton class. + if not hasattr(cls, '_instance'): + cls._instance = cls() + return cls._instance + def __init__(self): + assert not hasattr(self.__class__, + '_instance'), 'Do not call constructor directly!' self.proto = core.ProgramDesc.instance() - assert self.proto.num_blocks() == 1 self.blocks = [Block(self, 0)] self.current_block_idx = 0 @@ -42,4 +51,4 @@ class Program(object): # program is a global instance. -g_program = Program() +g_program = Program.instance() -- GitLab