CS FundamentalsVery hardProduct-company placement · Python interview

What does this Singleton implemented with a metaclass print?

What does this Singleton implemented with a metaclass print?
class Meta(type):
    _inst = {}
    def __call__(cls, *a, **k):
        if cls not in cls._inst:
            cls._inst[cls] = super().__call__(*a, **k)
        return cls._inst[cls]
class Config(metaclass=Meta):
    def __init__(self, env="dev"):
        self.env = env
x = Config("prod")
y = Config("test")
print(x is y, y.env)
  1. A. True test
  2. B. True prod
  3. C. False test
  4. D. False prod

Correct answer: B. True prod

The metaclass intercepts construction: the first call creates and caches the instance, and later calls return it without running __init__ again. So y is x and env stays 'prod' - a classic surprise when a Singleton silently ignores new arguments.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic