CS FundamentalsVery hardProduct-company placement · Python interview

This Singleton caches its instance in new. What does it print?

This Singleton caches its instance in __new__. What does it print?
class Settings:
    _instance = None
    def __new__(cls, *args):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    def __init__(self, env):
        self.env = env
x = Settings("prod")
y = Settings("test")
print(x is y, x.env)
  1. A. True prod
  2. B. False prod
  3. C. True test
  4. D. False test

Correct answer: C. True test

__new__ returns the same object, but Python still calls __init__ on it at every construction, overwriting env with 'test'. So x is y, and x.env has silently changed - a common bug in __new__-based singletons.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic