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 3 2963
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
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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
|
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...
|
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
{
|
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...
|
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
| |
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
|
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...
|
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 =...
|
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
|
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...
|
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,...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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,...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |