Bird
0
0

What is the problem with this Flask Singleton pattern implementation?

medium📝 Debug Q6 of 15
Flask - Ecosystem and Patterns
What is the problem with this Flask Singleton pattern implementation? ```python class Config: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance config1 = Config() config2 = Config() print(config1 is config2) ```
AThe _instance variable should be defined inside __init__, not at class level
BThe __new__ method should return a new object every time, not the same instance
CThe Singleton pattern is correctly implemented; both instances are the same
DThe print statement will raise an error because 'is' cannot compare objects
Step-by-Step Solution
Solution:
  1. Step 1: Review Singleton pattern

    Singleton ensures only one instance of a class exists.
  2. Step 2: Analyze code

    The __new__ method checks if _instance is None and creates it once, returning the same instance thereafter.
  3. Step 3: Check print output

    config1 and config2 refer to the same object, so 'config1 is config2' prints True.
  4. Final Answer:

    The Singleton pattern is correctly implemented; both instances are the same -> Option C
  5. Quick Check:

    Singleton returns same instance every time [OK]
Quick Trick: Singleton returns same instance on multiple calls [OK]
Common Mistakes:
MISTAKES
  • Thinking __new__ should always create new objects
  • Placing _instance inside __init__ instead of class level
  • Believing 'is' cannot compare objects

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes