From bb8c6f8e3e9c7e0f46992739f1f2ffe41ba0bc43 Mon Sep 17 00:00:00 2001 From: BioBootloader Date: Sat, 22 Apr 2023 17:24:47 -0700 Subject: [PATCH] switch singleton example to have a bug in singleton implementation --- examples/buggy_script_2.py | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/examples/buggy_script_2.py b/examples/buggy_script_2.py index d36cff5..0cf9128 100644 --- a/examples/buggy_script_2.py +++ b/examples/buggy_script_2.py @@ -2,27 +2,26 @@ import fire """ -Run With: with `wolverine examples/buggy_script_2.py "return_2"` +Run With: with `python wolverine.py examples/buggy_script_2.py` Purpose: Fix singleton code bug in Python """ class SingletonClass(object): - def __new__(cls): - if not hasattr(cls, 'instance'): - cls.instance = super(SingletonClass, cls).__new__(cls) - return cls.instance - -def return_2(): - """ - Always returns 2 - """ - singleton = SingletonClass() - new_singleton = SingletonClass() - singleton.a = 1 - new_singleton.a = 2 - would_be_2 = (singleton.a + singleton.a) - assert would_be_2 == 2 - return would_be_2 + def __new__(cls): + cls.instance = super(SingletonClass, cls).__new__(cls) + return cls.instance + +def check_singleton_works(): + """ + check that singleton pattern is working + """ + singleton = SingletonClass() + new_singleton = SingletonClass() + singleton.a = 1 + new_singleton.a = 2 + should_be_4 = (singleton.a + new_singleton.a) + assert should_be_4 == 4 if __name__=="__main__": - fire.Fire() + fire.Fire(check_singleton_works) +