How to inherit Base class with singleton in python
<p>I have base class which is singleton, i need to inherit that in my another class but i get error message as 
TypeError: Error when calling the metaclass bases
    function() argument 1 must be code, not str</p>

<p>Can someone help with this.
Below is sample code.</p>

<pre><code>def singleton(cls):
  instances = {}
  def getinstance():
    if cls not in instances:
      instances[cls] = cls()
    return instances[cls]
  return getinstance

@singleton
class ClassOne(object):

  def methodOne(self):
    print "Method One"

  def methodTwo(self):
    print "Method Two"


class ClassTwo(ClassOne):
  pass
</code></pre>

<p>You must make the <code>singleton</code> a class instead of a function for derivation to work. Here is an example that has been tested on both Python 2.7 and 3.5:</p>

<pre><code>class singleton(object):
    instances = {}
    def __new__(cls, clz = None):
        if clz is None:
            # print ("Creating object for", cls)
            if not cls.__name__ in singleton.instances:
                singleton.instances[cls.__name__] = \
                    object.__new__(cls)
            return singleton.instances[cls.__name__]
        # print (cls.__name__, "creating", clz.__name__)
        singleton.instances[clz.__name__] = clz()
        singleton.first = clz
        return type(clz.__name__, (singleton,), dict(clz.__dict__))
</code></pre>

<p>If you use this with your example classes:</p>

<pre><code>@singleton
class ClassOne(object):

  def methodOne(self):
    print "Method One"

  def methodTwo(self):
    print "Method Two"


class ClassTwo(ClassOne):
  pass
</code></pre>

<p>classes <code>A</code> and <code>B</code> will both be singletons</p>

<p>Beware, it is uncommon to inherit from a singleton class.</p>

python python-2.7