flashburn flashburn - 2 months ago 33
Python Question

singleton, metaclass and error during instantiation

I needed to create a singleton in for my code. So I followed these instructions, method 3.

Here is the code that I have:

class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]

def MyCfg(object):
__metaclass__ = Singleton
def __init__(self, p1 = 1, p2 = 2):
# Some code

my_cfg = MyCfg()

However whenI run this code, I get a following error:

TypeError: MyCfg() takes exactly 1 argument (0 given)

I'm not new to
and programming but I never worked at with
at this level. I've been trying to understand what exactly happens in
class but I can't figure out.

Would anyone be able to explain why this code generates an error?


You have:

def MyCfg(object)

I am pretty sure you mean:

class MyCfg(object)

The error you are seeing (TypeError: MyCfg() takes exactly 1 argument (0 given)) is because with your current code, you are defining a function called MyCfg that takes a single argument (which you are not providing).