473,686 Members | 2,162 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

singletons

Hey, forgive me for just diving in, but I have a question I was
thinking of asking on another list but it really is a general question
so let me ask it here. It's about how to approach making singletons.
Background: I've been programming in python seriously for about a year
now, maybe a little longer depending how you count, and the system I
am making is sophisticated enough that I've had to enter into a few
idioms which were beyond my knowledge of python, and I had to do quick
research and test my ideas with test code (which of course can miss
subtle problems). Otoh, I have decades of programming experience now
and wasn't totally without footing. I think I have a solution I like
for creating something to act as a singleton but I'm curious what
other's think.

I have several classes in our system which need to act like
singletons, they are libraries of data classifications , and other such
libraries of configurations for the system which need to be global.

The first thing I found searching for singleton, early in this
project, trying to be a good citizen and find a decent idiom from the
python community itself, knowing someone had mentioned "singleton" and
"python" together at some point, was a recommendation to do this:

(option 1)

class TehLibrary(obje ct):
__single = None
def __init__(self):
if (TehLibrary.__s ingle):
raise AlreadyExistsEx ception # or whatever

This sucks because that means creation of the object has to be in a
try block as a matter of course, something I promptly hid in a factory
function, but still.

But the way this worked made me realize that the Class itself is a
full fledged object, quite instance-like from my C++ addled (I love
you C++) perspective and it's single. If I can store that instance, I
can make a class that shares member at the class level. The class
doesn't even have to be a singleton exactly.

(option 2)
Therefore option two is a family of options where class level members
can be used to share whatever needs to be shared, though strictly the
class is not a singleton since multiple instances are created which
merely share the data that should be single (say a big dictionary of
configuration information the class manages).

(option 3)
I still wanted actual singletons and realized that since I had to
create a factory function even in option 1, that I could use module
level variables to control the behavior of those factories, which led
me to realize I'm basically just using the module itself as a
singleton. And this is sort of where I have arrived... when I import
the modules it runs code to build up it's basic services, much like an
object construction. It only runs once no matter how many times it's
imported. When client code asks for the library that should be a
singleton, it gets a singleton which has been stored in a module level
variable.

Anyone have any comments? Is there anything wrong, evil, or ugly
about using a module this way, or am I correct to think that actually,
this is a common approach in python.

Is it pythonic?
Jul 16 '08 #1
12 1418
On Jul 16, 5:20*pm, Craig Allen <callen...@gmai l.comwrote:
Hey, forgive me for just diving in, but I have a question I was
thinking of asking on another list but it really is a general question
so let me ask it here. *It's about how to approach making singletons.
Background: I've been programming in python seriously for about a year
now, maybe a little longer depending how you count, and the system I
am making is sophisticated enough that I've had to enter into a few
idioms which were beyond my knowledge of python, and I had to do quick
research and test my ideas with test code (which of course can miss
subtle problems). *Otoh, I have decades of programming experience now
and wasn't totally without footing. *I think I have a solution I like
for creating something to act as a singleton but I'm curious what
other's think.

I have several classes in our system which need to act like
singletons, they are libraries of data classifications , and other such
libraries of configurations for the system which need to be global.

The first thing I found searching for singleton, early in this
project, trying to be a good citizen and find a decent idiom from the
python community itself, knowing someone had mentioned "singleton" and
"python" together at some point, was a recommendation to do this:

(option 1)

class TehLibrary(obje ct):
* *__single = None
* *def __init__(self):
* * * if (TehLibrary.__s ingle):
* * * * *raise AlreadyExistsEx ception # or whatever

This sucks because that means creation of the object has to be in a
try block as a matter of course, something I promptly hid in a factory
function, but still.

But the way this worked made me realize that the Class itself is a
full fledged object, quite instance-like from my C++ addled (I love
you C++) perspective and it's single. *If I can store that instance, I
can make a class that shares member at the class level. The class
doesn't even have to be a singleton exactly.

(option 2)
Therefore option two is a family of options where class level members
can be used to share whatever needs to be shared, though strictly the
class is not a singleton since multiple instances are created which
merely share the data that should be single (say a big dictionary of
configuration information the class manages).

(option 3)
I still wanted actual singletons and realized that since I had to
create a factory function even in option 1, that I could use module
level variables to control the behavior of those factories, which led
me to realize I'm basically just using the module itself as a
singleton. And this is sort of where I have arrived... when I import
the modules it runs code to build up it's basic services, much like an
object construction. *It only runs once no matter how many times it's
imported. When client code asks for the library that should be a
singleton, it gets a singleton which has been stored in a module level
variable.

Anyone have any comments? *Is there anything wrong, evil, or ugly
about using a module this way, or am I correct to think that actually,
this is a common approach in python.

Is it pythonic?
In option 1, you could use the __new__ method, and return the existing
instance if there is one, or, I believe, call __init__ on the
superclass. Alternatively, define your own 'create' method with the
@classmethod decorator, instantiate with ClassA.create( ), and return
any existing instance from there. The catch is you need to rely on
the discipline of not using the default instantiation syntax.

In option 2, you would have to wrap the functions with the
@staticmethod decorator, and all instance methods would act on the
same object.

Each of these have different consequences for inheritance, if that is
on the horizon in your project.
Jul 17 '08 #2
I don't intend to do much subclassing of this, but of course, I'd
rather not second guess the future and it's not hard to imagine we
will come to some point that we need to do just that. Thanks for the
ideas about repairing option one, which I'd given up, though the ideal
is still that

tl = TehLibrary() would always return the same object.

-craig

On Jul 16, 2:00 pm, castironpi <castiro...@gma il.comwrote:
On Jul 16, 5:20 pm, Craig Allen <callen...@gmai l.comwrote:
Hey, forgive me for just diving in, but I have a question I was
thinking of asking on another list but it really is a general question
so let me ask it here. It's about how to approach making singletons.
Background: I've been programming in python seriously for about a year
now, maybe a little longer depending how you count, and the system I
am making is sophisticated enough that I've had to enter into a few
idioms which were beyond my knowledge of python, and I had to do quick
research and test my ideas with test code (which of course can miss
subtle problems). Otoh, I have decades of programming experience now
and wasn't totally without footing. I think I have a solution I like
for creating something to act as a singleton but I'm curious what
other's think.
I have several classes in our system which need to act like
singletons, they are libraries of data classifications , and other such
libraries of configurations for the system which need to be global.
The first thing I found searching for singleton, early in this
project, trying to be a good citizen and find a decent idiom from the
python community itself, knowing someone had mentioned "singleton" and
"python" together at some point, was a recommendation to do this:
(option 1)
class TehLibrary(obje ct):
__single = None
def __init__(self):
if (TehLibrary.__s ingle):
raise AlreadyExistsEx ception # or whatever
This sucks because that means creation of the object has to be in a
try block as a matter of course, something I promptly hid in a factory
function, but still.
But the way this worked made me realize that the Class itself is a
full fledged object, quite instance-like from my C++ addled (I love
you C++) perspective and it's single. If I can store that instance, I
can make a class that shares member at the class level. The class
doesn't even have to be a singleton exactly.
(option 2)
Therefore option two is a family of options where class level members
can be used to share whatever needs to be shared, though strictly the
class is not a singleton since multiple instances are created which
merely share the data that should be single (say a big dictionary of
configuration information the class manages).
(option 3)
I still wanted actual singletons and realized that since I had to
create a factory function even in option 1, that I could use module
level variables to control the behavior of those factories, which led
me to realize I'm basically just using the module itself as a
singleton. And this is sort of where I have arrived... when I import
the modules it runs code to build up it's basic services, much like an
object construction. It only runs once no matter how many times it's
imported. When client code asks for the library that should be a
singleton, it gets a singleton which has been stored in a module level
variable.
Anyone have any comments? Is there anything wrong, evil, or ugly
about using a module this way, or am I correct to think that actually,
this is a common approach in python.
Is it pythonic?

In option 1, you could use the __new__ method, and return the existing
instance if there is one, or, I believe, call __init__ on the
superclass. Alternatively, define your own 'create' method with the
@classmethod decorator, instantiate with ClassA.create( ), and return
any existing instance from there. The catch is you need to rely on
the discipline of not using the default instantiation syntax.

In option 2, you would have to wrap the functions with the
@staticmethod decorator, and all instance methods would act on the
same object.

Each of these have different consequences for inheritance, if that is
on the horizon in your project.
Jul 17 '08 #3
On Jul 17, 8:20 am, Craig Allen <callen...@gmai l.comwrote:
Is it pythonic?
You probably can't get anymore pythonic than something written by the
BDFL. In describing the use of __new__ in <i>Unifying types and
classes in Python 2.2</ihe gives this recipe for a Singleton.
class Singleton(objec t):
def __new__(cls, *args, **kwds):
it = cls.__dict__.ge t("__it__")
if it is not None:
return it
cls.__it__ = it = object.__new__( cls)
it.init(*args, **kwds)
return it
def init(self, *args, **kwds):
pass

You might find this a useful starting point.
Jul 17 '08 #4
In message
<e2************ *************** *******@l42g200 0hsc.googlegrou ps.com>, Craig
Allen wrote:
... the ideal is still that

tl = TehLibrary() would always return the same object.
>class TehLibrary(obje ct) :
.... @classmethod
.... def __new__(self, cls) :
.... return self
>>s = TehLibrary()
s == TehLibrary()
True

Jul 17 '08 #5
On Jul 16, 6:20*pm, Craig Allen <callen...@gmai l.comwrote:
Anyone have any comments? *Is there anything wrong, evil, or ugly
about using a module this way, or am I correct to think that actually,
this is a common approach in python.

Is it pythonic?

The one drawback to this is that it could require lots of globals
definitions. Whereas in a regular class you could do this:

def something(self) :
self.var = 1
self.max = 10

using a module as a singleton you'd be doing this:

def something():
global var
global max
var = 1
max = 10
If you have a lot of "attributes " of your module to redefine, I'd
suggest taking steps to avoid globals. The most straightforward way
is to define a self variable in your module that is bound to the
module itself, and access all "attributes " through that. The
following code should suffice (though it may not work in some corner
cases):

self = sys.modules[__name__]

So then you could rewrite the something method like so:

def something():
self.var = 1
self.max = 10
[Another possibility, and this is what I do, is to use a function
decorator that passes the module in as the first argument. I have
reasons for doing it but it doesn't do anything the above method
does. It would be used like this:

@modmethod
def something(self) :
self.var = 1
self.max = 10

]
Carl Banks
Jul 17 '08 #6
On Jul 16, 7:01 pm, Lawrence D'Oliveiro <l...@geek-
central.gen.new _zealandwrote:
In message
<e2ef1d2c-f39b-43e2-a848-0cb7660fd...@l4 2g2000hsc.googl egroups.com>, Craig

Allen wrote:
... the ideal is still that
tl = TehLibrary() would always return the same object.
class TehLibrary(obje ct) :

... @classmethod
... def __new__(self, cls) :
... return self
>s = TehLibrary()
s == TehLibrary()

True
That's great, I simply didn't find that when looking. Thanks!
Jul 17 '08 #7
On 17 Jul., 00:20, Craig Allen <callen...@gmai l.comwrote:
>
I have several classes in our system which need to act like
singletons, they are libraries of data classifications , and other such
libraries of configurations for the system which need to be global.
...

Is it pythonic?
My approach in this situation is to use the Borg pattern instead
of singeltons. This is really pythonic, very simple and usefull.

Look at http://aspn.activestate.com/ASPN/Coo...n/Recipe/66531
The german wikipedia shows another solution using metaclasse:
http://de.wikipedia.org/wiki/Singlet...s_Borg-Pattern

Greetings, Uwe
Jul 17 '08 #8
On Jul 17, 2:15 am, Uwe Schmitt <rocksportroc.. .@googlemail.co m>
wrote:
On 17 Jul., 00:20, Craig Allen <callen...@gmai l.comwrote:
I have several classes in our system which need to act like
singletons, they are libraries of data classifications , and other such
libraries of configurations for the system which need to be global.
...
Is it pythonic?

My approach in this situation is to use the Borg pattern instead
of singeltons. This is really pythonic, very simple and usefull.

Look athttp://aspn.activestat e.com/ASPN/Cookbook/Python/Recipe/66531
The german wikipedia shows another solution using metaclasse:http://de.wikipedia.org/wiki/Singlet...s_Borg-Pattern

Greetings, Uwe
thanks uwe, doing some searching I ran into the borg pattern this
morning. Definitely relevant.

Thanks again and all for the feedback, I feel much reassured about the
options when this sort of thing is required.
Jul 17 '08 #9
In message
<98************ *************** *******@r66g200 0hsg.googlegrou ps.com>, Craig
Allen wrote:
On Jul 16, 7:01 pm, Lawrence D'Oliveiro <l...@geek-
central.gen.new _zealandwrote:
>>
>>class TehLibrary(obje ct) :

... @classmethod
... def __new__(self, cls) :
... return self
>>s = TehLibrary()
s == TehLibrary()

True

That's great, I simply didn't find that when looking. Thanks!
Also note that

s == TehLibrary

will be true (the instance equals the class). I assume that doesn't matter
for your purposes. :)
Jul 18 '08 #10

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

Similar topics

5
3156
by: stephan beal | last post by:
Good morning, C++ users, i've been hesitating to post this, primarily because i know that most of you here are *way* ahead of me in C++ and i'm a little embarassed about the possibility of some gross errors in what i'll be posting... That said, please go easy on me. :) About 2 weeks ago i wrote a paper, called Context Singletons, where i discuss some of the uses of context-specific Singleton-like objects. During
11
1680
by: Tito | last post by:
I have two questions about the singletons' chapter of Alexei Alexandrescu's "C++ Modern Design". 1. In the beginning of the chapter Alexei states that a "singleton" class implementation made of static member functions has the problem that the functions are not virtual, so that you have to touch the class' code in order to change the behaviour. But, how is a singleton meant to be inherited from? Is not the concrete class of the unique...
3
3152
by: Dominik Rau | last post by:
Hi. I've got the following problem here: In my application, I use a lot of Singletons, that are implemented as described in Gamma et al. (shortened): //.h class Singleton{ public: static Singleton* the(); private: static Singleton* _instance;
8
4440
by: 6tc1 | last post by:
Hi all, I'm having a problem where in my solution that contains multiple projects - I instantiate a singleton class in one assembly and then if another assembly tries to use that singleton class another instance of it is created. Basically: --Assembly 1 (the executable)-- -Main.cs-
11
2356
by: John Fly | last post by:
I'm working on a large project(from scratch). The program is essentially a data file processor, the overall view is this: A data file is read in, validated and stored in a memory structure similar to a database or XML representation. Rules to modify the stored data will be executed, then the data will be transformed into an output format. Think something similar to FormatA -> XML -> Manipulate XML -> FormatB
6
1385
by: Steven Watanabe | last post by:
PEP 8 says, "Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators." I know that "is" is an identity operator, "==" and "!=" are the equality operators, but I'm not sure what other singletons are being referred to here. Also, I've seen code that does things like: if foo is 3: if foo is not '':
5
1488
by: Omega | last post by:
I'm interested in seeing a bit of discussion about using singletons in ASP.NET 2.0. Currently I've designed a singleton that gets a reference to it's single instance stored inside the ASP.NET application object. This is done to persist and make available live information across multiple sessions. I've read a little bit (almost nothing) about how singletons don't play nicely in clustered scenarios and would like to hear more on the
6
10367
by: =?Utf-8?B?R29yZG8=?= | last post by:
Hello everyone, I've been trying for some time now to move to C++/CLI, but I have several large legacy C++ static libraries I need to use. When I set up a simple solution with a C++/CLI Winforms app and a C++ native static library, they work well together _unless_ I have, it seems, any static variables defined in any function in the native library. The libraries I'm trying to use all have Meyers Singletons in them, so they need to have...
7
1804
by: adam.timberlake | last post by:
I was reading an article on TalkPHP (http://www.talkphp.com/ showthread.php?t=1304) about singletons but I'm afraid I don't understand why I need to use them. I understand how to code them perfectly, it's just the theory I'm having some problems with. I did try searching on Wikipedia but it didn't yield any satisfactory reasoning, for me. Could someone explain it to me in basic terms, please. I initially came across singletons when I...
0
8586
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
8936
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8772
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
8780
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
5800
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
4312
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...
0
4536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2208
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1941
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.