473,396 Members | 1,972 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.

Brain Dead Singleton

I looked on this newsgroup, and saw all the problems with making a
Singleton class with Python.

I don't really care about 'returning the single shared instance' in
the constructor and all, I just want to avoid being inefficient... so
I implemented this (code fragment follows):

class Whatever:
_singleton = 0
def __init__(self):
self.__class__._singleton += 1
if self.__class__._singleton > 1:
raise Exception("Singleton!")

There. I've got it trussed up to where I can't create more than one
without raising an exception, which works good enough for my purposes.

--Kamilche
Jul 18 '05 #1
10 1263
"Kamilche" <kl*******@home.com> wrote in message
news:88**************************@posting.google.c om...
I looked on this newsgroup, and saw all the problems with making a
Singleton class with Python.


Whenever I want a singleton "class", I just use a module with functions and
global variables. Modules only import once.

Colin Brown
PyNZ

Jul 18 '05 #2
Colin Brown wrote:
"Kamilche" <kl*******@home.com> wrote in message
news:88**************************@posting.google.c om...
I looked on this newsgroup, and saw all the problems with making a
Singleton class with Python.

Whenever I want a singleton "class", I just use a module with functions and
global variables. Modules only import once.

Colin Brown
PyNZ

should often work, but this illustrates how it can go wrong

##################
f=open('my_singleton_module.py','w')
f.write('''a=0
def incr(i):
global a
oa = a
a+=i
return oa
''')
f.close()

import my_singleton_module as inst0
print inst0.a
inst0.incr(5)
print inst0.a
import sys
del sys.modules['my_singleton_module']
import my_singleton_module as inst1
print inst1.a
##################

so if sys.modules gets interfered with approriately, your singleton can
start breeding.
--
Robin Becker
Jul 18 '05 #3
Robin Becker wrote:
Colin Brown wrote:
Whenever I want a singleton "class", I just use a module with
functions and
global variables. Modules only import once.
should often work, but this illustrates how it can go wrong

[...] del sys.modules['my_singleton_module'] [...] so if sys.modules gets interfered with approriately, your singleton can
start breeding.


We're all adults. How often do you see (or write) code that
goes around deleting modules from sys.modules. Colin's
suggesting is just fine for most sane situations.

-Peter
Jul 18 '05 #4
Peter Hansen wrote:
Robin Becker wrote:
Colin Brown wrote:
Whenever I want a singleton "class", I just use a module with
functions and
global variables. Modules only import once.

should often work, but this illustrates how it can go wrong


[...]
del sys.modules['my_singleton_module']


[...]
so if sys.modules gets interfered with approriately, your singleton
can start breeding.

We're all adults. How often do you see (or write) code that
goes around deleting modules from sys.modules. Colin's
suggesting is just fine for most sane situations.

-Peter


well I actually have a use case for deleting modules from sys.modules.
In some legacy code for ReportLab documentation, import was used in the form

import chapter1
import chapter2
......

in two different documents causing confusion. An easy fix involved
restoring sys.modules to a pristine state before each document was
generated.
--
Robin Becker
Jul 18 '05 #5
Robin Becker wrote:
Peter Hansen wrote:
Colin's suggesting is just fine for most sane situations.
well I actually have a use case for deleting modules from sys.modules.

[...] An easy fix involved restoring sys.modules to a pristine state
before each document was generated.


I'd argue perhaps that "easy fix" should have read "hack", and
that this doesn't fit my condition of "most sane situations".

Would you say that this "fix" was really an elegant solution,
or just a quick hack? I don't think deleting things from
sys.modules has defined, guaranteed behaviour, so I'm uncertain
whether anyone should rely on it working. I still think
Colin's approach is a generally okay one.

-Peter
Jul 18 '05 #6
Peter Hansen wrote:

.......
> An easy fix involved restoring sys.modules to a pristine state
> before each document was generated.
I'd argue perhaps that "easy fix" should have read "hack", and
that this doesn't fit my condition of "most sane situations".


I think I would agree that this is a hack. Probably the correct fix
would have been to packagize each document folder and the containing
folder and then change all the imports to be absolute, but that would
have meant changing far more lines of code and introducing packages
which are not really packages.
Would you say that this "fix" was really an elegant solution,
or just a quick hack? I don't think deleting things from
sys.modules has defined, guaranteed behaviour, so I'm uncertain
whether anyone should rely on it working. I still think
Colin's approach is a generally okay one.

-Peter


If sys.modules isn't intended to be a modifiable cache, perhaps we
shouldn't be given access to it.

The docs for 2.3 say
"modules
This is a dictionary that maps module names to modules which have
already been loaded. This can be manipulated to force reloading of
modules and other tricks. Note that removing a module from this
dictionary is not the same as calling reload() on the corresponding
module object."

So the Gods call call this a trick :)
--
Robin Becker
Jul 18 '05 #7
Robin Becker wrote:
Peter Hansen wrote:
I don't think deleting things from
sys.modules has defined, guaranteed behaviour, so I'm uncertain
whether anyone should rely on it working.


If sys.modules isn't intended to be a modifiable cache, perhaps we
shouldn't be given access to it.

The docs for 2.3 say
"modules
This is a dictionary that maps module names to modules which have
already been loaded. This can be manipulated to force reloading of
modules and other tricks.... "


Hmmm... I'd be more inclined to think it was an approval
if it didn't use the term "trick" to describe it.

Anyway, this now leads me to wonder whether any singleton
pattern which doesn't involve manipulating __builtin__ is
safe from deletion of items in sys.modules...

-Peter
Jul 18 '05 #8
Peter Hansen wrote:
.......
The docs for 2.3 say
"modules
This is a dictionary that maps module names to modules which have
already been loaded. This can be manipulated to force reloading of
modules and other tricks.... "

Hmmm... I'd be more inclined to think it was an approval
if it didn't use the term "trick" to describe it.

Anyway, this now leads me to wonder whether any singleton
pattern which doesn't involve manipulating __builtin__ is
safe from deletion of items in sys.modules...


.....

If you hold onto an instance then I think it's safe, I guess the problem
is when the class code (from a module) gets violently changed in some
way. When you next get an instance even from a borg type pattern it
needn't be the same as the last instance. Of course modules, classes etc
are not normally read only so they can be subverted just by writing into
them.
-Peter

--
Robin Becker
Jul 18 '05 #9
Well, to cop a phrase from 'Brother Where Art Thou?', "I'm with you
fellers."

You both are much more experienced than I, so much so that I don't
even know what you're talking about, yet. :-o
Jul 18 '05 #10
Robin Becker wrote:
Peter Hansen wrote:


[...]
Anyway, this now leads me to wonder whether any singleton
pattern which doesn't involve manipulating __builtin__ is
safe from deletion of items in sys.modules...


....

If you hold onto an instance then I think it's safe, I guess the problem


The same is true for modules. If you keep a reference of a module and refer
only to that instead of doing an import every time you need to access your
singleton - well nothing will break that. However, you have now reduced the
original pattern to a mere "please do not rebind that name" convention.

Peter

Jul 18 '05 #11

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

Similar topics

2
by: johnchampion | last post by:
hi, my brain is mush right now but i'm trying to remember how to create a php script that opens a text file, appends text to it, then closes it. i just cannot remember this simple task to save...
10
by: E. Robert Tisdale | last post by:
Could somebody please help me with the definition of a singleton? > cat singleton.cc class { private: // representation int A; int B; public: //functions
3
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic...
3
by: One Handed Man \( OHM - Terry Burns \) | last post by:
Yes, my brain is once again dead ( this is my mind writing using a supernatural force ). I'm trying to validate an xml file against its schema, I have a very simple example where price is a...
7
by: One Handed Man \( OHM - Terry Burns \) | last post by:
I've been battling with this stupid problem for hours now. WebApp: Trying to do a simple transformation using XSLT to a Web Page, but it just failes without an error message ( In other words,...
3
by: Joachim Klassen | last post by:
Hi all, if I accidentally use a TAKEOVER command with BY FORCE clause while primary and standby are in peer state I'll end up with two primary's (at least with FP10 and Windows). Is this works ...
3
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That...
1
by: Microsoft Newsserver | last post by:
I know I know the answer to this, but my brain has gone to sleep.... I set up the selected styles for my meny whocjh is in the master page. Unforntuynately, as soon as I put in a navigate URL to...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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.