Singleton technique (Re: metaclasses vs. inheritance)

Greg Ewing see_reply_address at something.invalid
Wed Jul 3 01:14:07 EDT 2002


> "Ian McMeans" <imcmeans at home.com> wrote:
>>Can someone give an example of a problem that is solved with metaclasses,


I came up with an idea today for making practical use of the
funky ability in 2.2 for a "class" statement to create
something other than a class.

Here's an example of how it's used:

 >>> from singleton import singleton

# First let's define an ordinary class:

 >>> class C:
...  def spam(self):
...   print "spam:", self
...

# Now here's a singleton which inherits from it:

 >>> class s(singleton, C):
...  def grail(self):
...   print "grail:", self
...

# At this point, s is *not* a class, it's an
# *instance* of an anonymous class which inherits
# from C.

 >>> s
<singleton.s instance at 0x1dbf60>
 >>> s.spam()
spam: <singleton.s instance at 0x1dbf60>
 >>> s.grail()
grail: <singleton.s instance at 0x1dbf60>

# (There's a slight problem with the naming of the
# singleton's class at the moment -- it should really
# be called "__main__.s", not "singleton.s"! Suggestions
# on how to fix this are welcome.)


#-----------------------------------------------------
#
#   singleton.py
#
#-----------------------------------------------------

import types

class SingletonMaker(object):
   pass

   def __new__(self, name = None, bases = None, dict = None):
     if not name: # for bootstrapping
       return object.__new__(self)
     bases = bases[1:] # discard bases[0] == singleton
     if bases:
       metaclass = type(bases[0])
     else:
       metaclass = types.ClassType
     return metaclass(name, bases, dict)()

singleton = SingletonMaker()

#-----------------------------------------------------
#
#   End of singleton.py
#
#-----------------------------------------------------

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list