Hi all!
I was reading through Python Cookbook the Singleton recipe. At this moment
I am a bit puzzled as the example in the book is not working resulting in:
TypeError: type.__new__(Si ngleSpam): SingleSpam is not a subtype of type
(I haven't presented the original code as I am not sure about copyrights).
bests,
../alex
--
..w( the_mindstorm )p. 9 2008
Alex Popescu schrieb:
Hi all!
I was reading through Python Cookbook the Singleton recipe. At this moment
I am a bit puzzled as the example in the book is not working resulting in:
TypeError: type.__new__(Si ngleSpam): SingleSpam is not a subtype of type
(I haven't presented the original code as I am not sure about copyrights).
AFAIK the cookbook is completely found online at ASPN. So no sweat
publishing it here.
And regarding the problem: is it possible that you forgot to subclass
SingleSpam from object?
Diez
"Diez B. Roggisch" <de***@nospam.w eb.dewrote in
news:5g******** *****@mid.uni-berlin.de:
Alex Popescu schrieb:
>Hi all!
I was reading through Python Cookbook the Singleton recipe. At this moment I am a bit puzzled as the example in the book is not working resulting in:
TypeError: type.__new__(Si ngleSpam): SingleSpam is not a subtype of type
(I haven't presented the original code as I am not sure about copyrights).
AFAIK the cookbook is completely found online at ASPN. So no sweat
publishing it here.
And regarding the problem: is it possible that you forgot to subclass
SingleSpam from object?
Diez
The exact code:
class Singleton(objec t):
""" A Pythonic Singleton """
def _ _new_ _(cls, *args, **kwargs):
if '_inst' not in vars(cls):
cls._inst = type._ _new_ _(cls, *args, **kwargs)
return cls._inst
if _ _name_ _ == '_ _main_ _':
class SingleSpam(Sing leton):
def _ _init_ _(self, s): self.s = s
def _ _str_ _(self): return self.s
s1 = SingleSpam('spa m')
print id(s1), s1.spam( )
s2 = SingleSpam('egg s')
print id(s2), s2.spam( )
../alex
--
..w( the_mindstorm )p.
Alex Popescu <no************ *****@gmail.com wrote in
news:Xn******** *************** ***@80.91.229.5 :
"Diez B. Roggisch" <de***@nospam.w eb.dewrote in
news:5g******** *****@mid.uni-berlin.de:
>Alex Popescu schrieb:
>>Hi all!
I was reading through Python Cookbook the Singleton recipe. At this moment I am a bit puzzled as the example in the book is not working resulting in:
TypeError: type.__new__(Si ngleSpam): SingleSpam is not a subtype of type
(I haven't presented the original code as I am not sure about copyrights) .
AFAIK the cookbook is completely found online at ASPN. So no sweat publishing it here.
And regarding the problem: is it possible that you forgot to subclass SingleSpam from object?
Diez
The exact code:
class Singleton(objec t):
""" A Pythonic Singleton """
def _ _new_ _(cls, *args, **kwargs):
if '_inst' not in vars(cls):
cls._inst = type._ _new_ _(cls, *args, **kwargs)
return cls._inst
if _ _name_ _ == '_ _main_ _':
class SingleSpam(Sing leton):
def _ _init_ _(self, s): self.s = s
def _ _str_ _(self): return self.s
s1 = SingleSpam('spa m')
print id(s1), s1.spam( )
s2 = SingleSpam('egg s')
print id(s2), s2.spam( )
./alex
--
.w( the_mindstorm )p.
I got it working in 2 ways:
class Singleton(objec t):
""" A Pythonic Singleton """
def __new__(cls, *args, **kwargs):
if '_singletoninst ance' not in vars(cls):
#variant 1: cls._singletoni nstance = object.__new__( cls, *args,
**kwargs)
#variant 2: cls._singletoni nstance = super(type, cls).__new__(cl s,
*args, **kwargs)
return cls._singletoni nstance
Both of these seem to work.
../alex
--
..w( the_mindstorm )p.
"Diez B. Roggisch" <de***@nospam.w eb.dewrites:
[...]
AFAIK the cookbook is completely found online at ASPN. So no sweat
publishing it here.
[...]
No: the book-form cookbook is edited, and has extra text.
I believe the recipes are under a BSD-style license, though.
John
Alex Popescu <no************ *****@gmail.com writes:
Hi all!
I was reading through Python Cookbook the Singleton recipe. At this moment
I am a bit puzzled as the example in the book is not working resulting in:
TypeError: type.__new__(Si ngleSpam): SingleSpam is not a subtype of type
Haven't looked at that recipe, but take a look at this related one: http://aspn.activestate.com/ASPN/Coo...n/Recipe/66531
John
Alex Popescu wrote:
Alex Popescu <no************ *****@gmail.com wrote in
news:Xn******** *************** ***@80.91.229.5 :
>"Diez B. Roggisch" <de***@nospam.w eb.dewrote in news:5g******* ******@mid.uni-berlin.de:
>>Alex Popescu schrieb: Hi all!
I was reading through Python Cookbook the Singleton recipe. At this moment I am a bit puzzled as the example in the book is not working resulting in:
TypeError: type.__new__(Si ngleSpam): SingleSpam is not a subtype of type
(I haven't presented the original code as I am not sure about copyrights ). AFAIK the cookbook is completely found online at ASPN. So no sweat publishing it here.
And regarding the problem: is it possible that you forgot to subclass SingleSpam from object?
Diez
The exact code: class Singleton(objec t): """ A Pythonic Singleton """ def _ _new_ _(cls, *args, **kwargs): if '_inst' not in vars(cls): cls._inst = type._ _new_ _(cls, *args, **kwargs) return cls._inst
if _ _name_ _ == '_ _main_ _': class SingleSpam(Sing leton): def _ _init_ _(self, s): self.s = s def _ _str_ _(self): return self.s s1 = SingleSpam('spa m') print id(s1), s1.spam( ) s2 = SingleSpam('egg s') print id(s2), s2.spam( )
./alex -- .w( the_mindstorm )p.
I got it working in 2 ways:
class Singleton(objec t):
""" A Pythonic Singleton """
def __new__(cls, *args, **kwargs):
if '_singletoninst ance' not in vars(cls):
#variant 1: cls._singletoni nstance = object.__new__( cls, *args,
**kwargs)
#variant 2: cls._singletoni nstance = super(type, cls).__new__(cl s,
*args, **kwargs)
return cls._singletoni nstance
Both of these seem to work.
If, that is, "work" means "Raise an AttributeError due to the missing
spam() method". This appears to fix that problem:
class Singleton(objec t):
""" A Pythonic Singleton """
def __new__(cls, *args, **kwargs):
if '_inst' not in vars(cls):
cls._inst = object.__new__( cls, *args, **kwargs)
return cls._inst
if __name__ == '__main__':
class SingleSpam(Sing leton):
def __init__(self, s): self.s = s
def __str__(self): return self.s
s1 = SingleSpam('spa m')
print id(s1), s1
s2 = SingleSpam('egg s')
print id(s2), s2
print str(s1)
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------
Alex Popescu a écrit :
Hi all!
I was reading through Python Cookbook the Singleton recipe. At this moment
I am a bit puzzled as the example in the book is not working resulting in:
TypeError: type.__new__(Si ngleSpam): SingleSpam is not a subtype of type
(I haven't presented the original code as I am not sure about copyrights).
I don't have the book, so if you don't post the code, I just give up
trying to guess what the problem can be.
Bruno Desthuilliers <bd************ *****@free.quel quepart.frwrote in
news:46******** *************** @news.free.fr:
Alex Popescu a écrit :
>
[snip...]
I don't have the book, so if you don't post the code, I just give up
trying to guess what the problem can be.
I've sent the original code and 2 different variants a long time ago.
../alex
--
..w( the_mindstorm )p.
Alex Popescu a écrit :
Bruno Desthuilliers <bd************ *****@free.quel quepart.frwrote in
news:46******** *************** @news.free.fr:
>Alex Popescu a écrit :
>[snip...]
I don't have the book, so if you don't post the code, I just give up trying to guess what the problem can be.
I've sent the original code and 2 different variants a long time ago.
You had not sent anything when I answered. But it seems that the machine
I answered with is a bit out of time !-)
./alex
--
.w( the_mindstorm )p.
This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Rajarshi Guha |
last post by:
Hi, I'm having a little problem with understanding the working of a
singleton and borg class. Basically I nedd an class whose state will be
shared across several modules. I found the stuff on the ASPN cookbook but
it does'nt seem to be working for me. I've included some code:
Borg.py:
--------
class Borg:
__shared_state = {}
def __init__(self):
|
by: John J Lee |
last post by:
QOTW: "...simple genexps will work fine anyway almost all the time, so
it doesn't appear to matter much that devious uses will have nightmarish
semantics." -- Tim Peters on Generator Expressions
"It looks like ... a developer's cookbook (eg. the O'Reilly Python
cookbook) but with less Reilly and more "Oh?"."
-- Paul Boddie, on the user-commented PHP documentation
Andrew Bennetts discovers, without realising it, an obscure-but-useful
|
by: Peter Otten |
last post by:
QOTW: "I worry about Python losing its KISS principle. Python 2.2 has been
ported to the Nokia Series 60 platform, which has something like 8-16 MB of
RAM available. I'm sure the footprint growth of Python 2.3 and 2.4 gives
those developers nightmares already when they are thinking of tracking later
versions..." - Guido van Rossum
"Everyone knows that any scripting language shootout that doesn't show
Python as the best language is...
|
by: Neil Zanella |
last post by:
Hello,
I would be very interested in knowing how the following C++ multi-instance
singleton (AKA Borg) design pattern based code snippet can be neatly coded
in Python. While there may be somewhat unusual places where multi-instance
singleton is more useful than plain singleton, it seems to me that the
former leads to less coding, so unless I can somehow package the
singleton pattern in a superclass (so I don't have to code it...
|
by: Alex Martelli |
last post by:
Greetings, fellow Pythonistas!
We (Alex Martelli, David Ascher and Anna Martelli Ravenscroft) are in
the process of selecting recipes for the Second Edition of the Python
Cookbook. Please contribute your recipes (code and discussion), along
with comments on and ratings of existing recipes, to the cookbook site,
http://aspn.activestate.com/ASPN/Cookbook/Python , and do it *now*!
The Python Cookbook is a collaborative collection of your...
| |
by: Simon Brunning |
last post by:
QOTW: "I think my code is clearer, but I wouldn't go so far as to say I'm
violently opposed to your code. I save violent opposition for really
important matters like which text editor you use." - Roy Smith
"You need to recursively subdivide the cake until you have a piece small
enough to fit in your input buffer. Then the atomicity of the cake-ingestion
operation will become apparent." - Scott David Daniels
Various Python Meetup...
|
by: Andre Meyer |
last post by:
While looking for an elegant implementation of the singleton design pattern
I came across the decorator as described in
PEP318<http://www.python.org/dev/peps/pep-0318/>
.
Unfortunately, the following does not work, because decorators only work on
functions or methods, but not on classes.
def singleton(cls):
instances = {}
def getinstance():
|
by: dischdennis |
last post by:
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
|
by: pythoncurious |
last post by:
Hi,
I've been trying to get some sort of singleton working in python, but
I struggle a bit and I thought I'd ask for advice.
The first approach was simply to use a module, and every variable in
it will be seen by all who import the module.
That works in some cases, but not if I have the following structure:
one/
|
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: 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...
|
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: 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();...
|
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...
|
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: 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...
| |