473,396 Members | 2,140 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Singleton Class Exception

Hello List,

I would like to make a singleton class in python 2.4.3, I found this
pattern in the web:

class Singleton:
__single = None
def __init__( self ):
if Singleton.__single:
raise Singleton.__single
Singleton.__single = self
the line "raise Singleton.__single" invokes in my class the following
error:

exceptions must be classes, instances, or strings (deprecated), not
PurchaseRequisitionController

Greetings, Dennis

Nov 13 '06 #1
3 2940
dischdennis wrote:
Hello List,

I would like to make a singleton class in python 2.4.3, I found this
pattern in the web:

class Singleton:
__single = None
def __init__( self ):
if Singleton.__single:
raise Singleton.__single
Singleton.__single = self
the line "raise Singleton.__single" invokes in my class the following
error:

exceptions must be classes, instances, or strings (deprecated), not
PurchaseRequisitionController

Greetings, Dennis
The problem is that you yoinked a bad example of a singleton. The
error is correct, only exceptions derived from the Exception class and
strings are supported. (Strings are supported for historical usage,
and a deprecated.)

Why exactly do you need a singleton? Do you want only one instance of
a class? Often, you really want something that shares state: all are
one. This pattern is known as a borg. Please see
"http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531" to see
how the Borg Pattern works.

If you absolutely gotta have a singleton, there are other ways of
implementing it. I can think of only one reason: You want the
singleton's destructor to be called only if there are no remaining
instances in existance. (For the Borg pattern, the deconstructor can
be called once per instance created.)

The problem with this reason is that Python doesn't guarantee when the
destructors will be called for instances (and some instances will never
have their destructors called). Although C-Python implements usually
destroys an instance when its ref-count drops to 0, IronPython and
Jython may do things very differently. (I have no experience with
either of those, so I cannot tell you how they differ.)

Still, if you're dead set on a Singleton class, I'll post one in a
little bit.

--Jason

Nov 13 '06 #2
dischdennis wrote:
the line "raise Singleton.__single" invokes in my class the following
error:

exceptions must be classes, instances, or strings (deprecated), not
PurchaseRequisitionController
Denis,
Jason's explanation is correct! You are trying to use the Singleton
instance as the exception, which is not only confusing but illegal.
The argument of raise should be an instance of a class derived from
Exception. You should define some kind of informative Exception class,
e.g.:

class SingletonException(Exception):
pass

class Singleton:
__single = None
def __init__( self ):
if Singleton.__single:
raise SingletonException()
Singleton.__single = self

foo = Singleton() # works
bar = Singleton() # raises SingletonException

Dan

Nov 13 '06 #3
I threw together two different singleton classes. They both ensure
that the initializers and destructors can be called at most once. (The
ImmortalSingleton won't ever have its destructor called unless the
programmer manually forces things.)

I haven't extensively tested these things, so handle this code like a
rabid wildebeest. Observe that Python may not call your destructors
when you expect. IAnd again, you probably want the Borg pattern.

Still, this was an interesting exercise to do.

--- Code Starts ---
class MortalSingleton(object):
"""This class implements a 'mortal' singleton pattern. Classes
derived
from this class cannot be directly instantiated or take arguments in
their
initializers.

The GetSingleton() class method returns a reference to a single
instance,
or creates a single instance as needed.

This class only keeps a weak reference to the single instance. This
means
that, if all hard references are destroyed, the instance can be
destroyed
by Python (and the __del__ method *could* be called, depending on
implementation). Thus, the single-ton is mortal.

This could be used as a mix-in class, assuming that the other classes
do not over-ride the __new__() method (which prevents willy-nilly
instantiation).

Note that if you need all instances to share state, you probably want
to use the Borg pattern.

Comments on this travesty are appreciated. *grin*
"""
def __new__(cls, *args, **keyargs):
# Raise a run-time error preventing direct instantiation
raise RuntimeError(
'Do not instantiate %s directly. Use the
%s.GetSingleton()'
'class method.' % (cls.__name__, cls.__name__)
)

@classmethod
def GetSingleton(cls):
from weakref import ref

retObject = getattr(cls, '_instance', lambda : None)()
if retObject is None:
# Create a new object with the given class
retObject = object.__new__(cls)

# The initializer must be manually called in this case
retObject.__init__()
cls._instance = ref(retObject)
return retObject

class ImmortalSingleton(object):
"""This class implements a classic 'immortal' singleton pattern.
Classes derived from this class will allow only one instance to exist.

Since the class caches a hard reference to the single pattern, it
doesn't die unless the programmer gets rid of all references and
manually
deletes the cache reference.

Note that you probably want to use a variant of the Borg class rather
than
this."""
def __new__(cls, *args, **keyargs):
# Raise a run-time error preventing direct instantiation

raise RuntimeError(
'Do not instantiate %s directly. Use the
%s.GetSingleton()'
'class method.' % (cls.__name__, cls.__name__)
)

@classmethod
def GetSingleton(cls):
retObject = getattr(cls, '_instance', lambda : None)()
if retObject is None:
# Create a new object with the given class
retObject = object.__new__(cls)

# The initializer must be manually called in this case
retObject.__init__()
cls._instance = retObject
return retObject

Nov 13 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Simon | last post by:
Hi. I don't have a problem per se, I was just wondering if anyone can offer some opinions about the best way to go about creating and disposing of a Singleton class. I have a class (handling...
7
by: Stephen Brown | last post by:
I have some strange behavior on my web server that seems to point to garbage collection. I have a singleton that tracks web activity on my web site. The singleton works great, except that it...
18
by: David | last post by:
Hello, I'm writing a C# class library that may be called by non-.Net applications. The main class of this class libray is a ServicedComponent so that non-.Net application can call this class as a...
14
by: Paul Bromley | last post by:
Forgive my ignorance on this one as I am trying to use a Singleton class. I need to use this to have one instance of my Class running and I think I understand how to do this. My question however is...
7
by: PMarino | last post by:
Hi all - I've taken some code from MSDN and made a Generic singleton, so that I don't have to write this code in many places: public class Singleton<TEntity> where TEntity : class, new() {...
2
by: Michel van den Berg | last post by:
Hello, I tried to implement the GoF Singleton Pattern. What do you think? Public MustInherit Class Singleton(Of T As New) Public Sub New() If SingletonCreator.Creating = False Then Throw...
9
by: Marcel Hug | last post by:
Hallo NG ! I Have a little question about inheritance of a singleton class. In my application i have a Database-Connection Lib, in which I would ¨like to connect different databases of the same...
7
by: Adam Duszenko | last post by:
I'm trying to create and use Java singleton inside Java UDF just as Mr Knut Stolze described in http://www-128.ibm.com/developerworks/db2/library/techarticle/dm-0404stolze/index.html .. But I've...
2
by: juscruise | last post by:
Could someone help me with this, the error reads ' Singleton is not defined ' using VB.NET Web design Imports Logix Partial Class _Default Inherits System.Web.UI.Page '...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.