473,837 Members | 1,616 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.__sin gle:
raise Singleton.__sin gle
Singleton.__sin gle = self
the line "raise Singleton.__sin gle" invokes in my class the following
error:

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

Greetings, Dennis

Nov 13 '06 #1
3 2969
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.__sin gle:
raise Singleton.__sin gle
Singleton.__sin gle = self
the line "raise Singleton.__sin gle" invokes in my class the following
error:

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

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.activestat e.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.__sin gle" invokes in my class the following
error:

exceptions must be classes, instances, or strings (deprecated), not
PurchaseRequisi tionController
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 SingletonExcept ion(Exception):
pass

class Singleton:
__single = None
def __init__( self ):
if Singleton.__sin gle:
raise SingletonExcept ion()
Singleton.__sin gle = self

foo = Singleton() # works
bar = Singleton() # raises SingletonExcept ion

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
ImmortalSinglet on 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(cl s):
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.__ini t__()
cls._instance = ref(retObject)
return retObject

class ImmortalSinglet on(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(cl s):
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.__ini t__()
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
2725
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 DB connections) which I have defined as a singleton, using the following pattern (VB.net code) Private Shared mInstance As clsConnection = Nothing
7
3620
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 restarts periodically. The web services have not been restarted and the error log shows no problems. It is the same problem on 2 different servers, but is worse on the most used server. On the most used server, it gets restarted 5 to 10 times a day...
18
6694
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 standard COM+ component. Now, I want that class to be a singleton. Once loaded, the values moslty never change. I tried using this pattern: public sealed class Singleton {
14
3039
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 can a singleton class have a number of paramterised constructors enabling me to pass in parameters or not? I am trying to use the following to send in a parmeter to a constructor, but getting an error with it. I have a feeling that I am not...
7
2716
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() { private static volatile TEntity instance = default(TEntity); private static object syncRoot = new Object(); public static TEntity Instance
2
1277
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 New SingletonException(Of T) End Sub
9
14149
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 project (thats why it is in a lib). For the database A I created a singleton class AProxy and for the database B the same as BProxy. Initializing and connetcing to the Database is the same in both classes (except of the database-path, which is a...
7
2664
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 the problem because each instance of UDF seams to run in separate Java runtime environment and has each it's own singleton instance. For test I created simple java singleton class like this: public class single { private static single instance =...
2
1329
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 ' ************************************* ' * singleton class
0
9852
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9696
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10642
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10288
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9420
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7824
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7014
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5680
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
3128
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.