Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #65995 > unrolled thread

singleton ... again

Started byAsaf Las <roegltd@gmail.com>
First post2014-02-11 20:34 -0800
Last post2014-02-12 15:05 -0700
Articles 20 on this page of 40 — 15 participants

Back to article view | Back to comp.lang.python


Contents

  singleton ... again Asaf Las <roegltd@gmail.com> - 2014-02-11 20:34 -0800
    Re: singleton ... again Asaf Las <roegltd@gmail.com> - 2014-02-11 21:15 -0800
    Re:singleton ... again Dave Angel <davea@davea.name> - 2014-02-12 00:48 -0500
      Re: singleton ... again Roy Smith <roy@panix.com> - 2014-02-12 00:55 -0500
        Re: singleton ... again Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2014-02-12 23:04 +1300
          Re: singleton ... again Ben Finney <ben+python@benfinney.id.au> - 2014-02-12 21:09 +1100
            Re: singleton ... again Roy Smith <roy@panix.com> - 2014-02-12 08:40 -0500
            Re: singleton ... again Piet van Oostrum <piet@vanoostrum.org> - 2014-02-13 10:00 +0100
              Re: singleton ... again Ned Batchelder <ned@nedbatchelder.com> - 2014-02-13 06:50 -0500
              Re: singleton ... again Chris Angelico <rosuav@gmail.com> - 2014-02-13 22:57 +1100
                Re: singleton ... again Roy Smith <roy@panix.com> - 2014-02-13 10:24 -0500
                  Re: singleton ... again Chris Angelico <rosuav@gmail.com> - 2014-02-14 07:03 +1100
                  Re: singleton ... again Robert Kern <robert.kern@gmail.com> - 2014-02-13 21:13 +0000
                  Re: singleton ... again Chris Angelico <rosuav@gmail.com> - 2014-02-14 08:27 +1100
              Re: singleton ... again Ethan Furman <ethan@stoneleaf.us> - 2014-02-13 08:57 -0800
                Re: singleton ... again Roy Smith <roy@panix.com> - 2014-02-13 12:57 -0500
                  Re: singleton ... again Ethan Furman <ethan@stoneleaf.us> - 2014-02-13 10:31 -0800
                    Re: singleton ... again Roy Smith <roy@panix.com> - 2014-02-13 14:03 -0500
                      Re: singleton ... again Chris Angelico <rosuav@gmail.com> - 2014-02-14 06:50 +1100
                      Re: singleton ... again Grant Edwards <invalid@invalid.invalid> - 2014-02-13 22:28 +0000
                Re: singleton ... again Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2014-02-14 18:21 +1300
              Re: singleton ... again Tim Delaney <timothy.c.delaney@gmail.com> - 2014-02-14 06:16 +1100
          Re: singleton ... again Steven D'Aprano <steve@pearwood.info> - 2014-02-13 02:58 +0000
            Re: singleton ... again Ben Finney <ben+python@benfinney.id.au> - 2014-02-13 14:07 +1100
              Re: singleton ... again Steven D'Aprano <steve@pearwood.info> - 2014-02-13 04:24 +0000
                Re: singleton ... again Chris Angelico <rosuav@gmail.com> - 2014-02-13 15:33 +1100
                Re: singleton ... again Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2014-02-14 18:15 +1300
            Re: singleton ... again Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2014-02-14 18:06 +1300
      Re: singleton ... again Asaf Las <roegltd@gmail.com> - 2014-02-12 09:50 -0800
        Re: singleton ... again Asaf Las <roegltd@gmail.com> - 2014-02-12 09:56 -0800
          Re: singleton ... again Asaf Las <roegltd@gmail.com> - 2014-02-12 09:58 -0800
          Re: singleton ... again Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2014-02-13 10:57 +1300
            Re: singleton ... again Asaf Las <roegltd@gmail.com> - 2014-02-12 17:38 -0800
        Re: singleton ... again Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-02-12 18:57 +0000
          Re: singleton ... again Asaf Las <roegltd@gmail.com> - 2014-02-12 17:02 -0800
        Re: singleton ... again Ned Batchelder <ned@nedbatchelder.com> - 2014-02-12 16:34 -0500
          Re: singleton ... again Asaf Las <roegltd@gmail.com> - 2014-02-12 17:34 -0800
        Re: singleton ... again Tim Delaney <timothy.c.delaney@gmail.com> - 2014-02-13 10:08 +1100
        Re: singleton ... again Roy Smith <roy@panix.com> - 2014-02-12 20:57 -0500
    Re: singleton ... again Michael Torrie <torriem@gmail.com> - 2014-02-12 15:05 -0700

Page 2 of 2 — ← Prev page 1 [2]


#66282

FromGregory Ewing <greg.ewing@canterbury.ac.nz>
Date2014-02-14 18:21 +1300
Message-ID<bm5nf6FqdoaU1@mid.individual.net>
In reply to#66194
Ethan Furman wrote:
> Say you have a class that represents serial ports or your computer.  You 
> should get the same object every time you ask for SerialPort(2).

No, you shouldn't ask for SerialPort(2) at all, you should
call get_serial_port(2). Then you won't be fooled into
thinking that you're creating an independent object each
time.

-- 
Greg

[toc] | [prev] | [next] | [standalone]


#66207

FromTim Delaney <timothy.c.delaney@gmail.com>
Date2014-02-14 06:16 +1100
Message-ID<mailman.6856.1392318974.18130.python-list@python.org>
In reply to#66159

[Multipart message — attachments visible in raw view] — view raw

On 13 February 2014 20:00, Piet van Oostrum <piet@vanoostrum.org> wrote:

> Ben Finney <ben+python@benfinney.id.au> writes:
> > Make that “somewhere” a module namespace, and you effectively have a
> > Singleton for all practical purposes. So yes, I see the point of it; but
> > we already have it built in :-)
>
> There is a use case for a singleton class: when creating the singleton
> object takes considerable resources and you don't need it always in your
> program.
>

Then have that resource in its own module, and import that module only when
needed e.g. inside a function. Python already has the machinery - no need
to reinvent the wheel.

Tim Delaney

[toc] | [prev] | [next] | [standalone]


#66140

FromSteven D'Aprano <steve@pearwood.info>
Date2014-02-13 02:58 +0000
Message-ID<52fc34e5$0$11128$c3e8da3@news.astraweb.com>
In reply to#66022
On Wed, 12 Feb 2014 23:04:32 +1300, Gregory Ewing wrote:

> Roy Smith wrote:
>> It looks to me like he's trying to implement a classic Gang of Four
>> singleton pattern.
> 
> Which I've never really seen the point of in Python, or any other
> language for that matter. Just create one instance of the class during
> initialisation, put it in a global somewhere, and use it thereafter.
> 
> If you really want to make sure nobody creates another instance by
> accident, delete the class out of the namespace after instantiating it.

That does not work. It is trivial to get the type from an instance:


py> class Singleton:
...     pass
... 
py> S = Singleton()
py> del Singleton
py> T = type(S)()
py> S
<__main__.Singleton object at 0xb71de9ec>
py> T
<__main__.Singleton object at 0xb71dea2c>




This is not aimed at the original poster, just a general observation. The 
Singleton design pattern is overused because it is probably the only 
design pattern that most programmers really understand.



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#66143

FromBen Finney <ben+python@benfinney.id.au>
Date2014-02-13 14:07 +1100
Message-ID<mailman.6817.1392260888.18130.python-list@python.org>
In reply to#66140
Steven D'Aprano <steve@pearwood.info> writes:

> On Wed, 12 Feb 2014 23:04:32 +1300, Gregory Ewing wrote:
> > If you really want to make sure nobody creates another instance by
> > accident, delete the class out of the namespace after instantiating
> > it.
>
> That does not work. It is trivial to get the type from an instance [by
> calling ‘type(foo)’].

Right, but surely you don't think people would do that “by accident”,
which is what Gregory was addressing.

-- 
 \            Hercules Grytpype-Thynne: “Well, Neddie, I'm going to be |
  `\      frank.”  Ned Seagoon: “Right, I'll be Tom.”  Count Moriarty: |
_o__)           “I'll be Gladys.” *slap* —The Goon Show, _World War I_ |
Ben Finney

[toc] | [prev] | [next] | [standalone]


#66151

FromSteven D'Aprano <steve@pearwood.info>
Date2014-02-13 04:24 +0000
Message-ID<52fc490d$0$11128$c3e8da3@news.astraweb.com>
In reply to#66143
On Thu, 13 Feb 2014 14:07:55 +1100, Ben Finney wrote:

> Steven D'Aprano <steve@pearwood.info> writes:
> 
>> On Wed, 12 Feb 2014 23:04:32 +1300, Gregory Ewing wrote:
>> > If you really want to make sure nobody creates another instance by
>> > accident, delete the class out of the namespace after instantiating
>> > it.
>>
>> That does not work. It is trivial to get the type from an instance [by
>> calling ‘type(foo)’].
> 
> Right, but surely you don't think people would do that “by accident”,
> which is what Gregory was addressing.

Of course it can happen by accident. It's happened to me, where I've 
accidentally called NoneType() (which raises, rather than returning a new 
instance).

The way it happened is I had a bunch of numeric values, all of the same 
type, and wanted to test that summing them with a custom sum function 
would give the same result whether I provided a start parameter or not:

for data in list_of_datas:
    T = type(data[0])
    zero = T()
    assert sum(data) == sum(data, zero)


only somehow one of the data sets ends up containing None due to another 
bug. Now in *this* case, the error was obvious: NoneType() raises an 
exception. If the type happened to be bool(), I would have been okay too, 
because bool() returns the appropriate singleton True instance.

Because I was testing a function with no side-effects, it wouldn't have 
mattered even if I had accidentally created a extra instance of something 
which nominally ought to have been a singleton. But if I were testing a 
function with side-effects, say one which modifies the internal state of 
the singleton, then I could have been in all sorts of strife.

If you're going to have a singleton, you ought to do one of two things:

* calling the constructor returns the same singleton each time; or

* calling the constructor (apart from the very first time) raises an
  exception.


I prefer the first case.



-- 
Steven

[toc] | [prev] | [next] | [standalone]


#66153

FromChris Angelico <rosuav@gmail.com>
Date2014-02-13 15:33 +1100
Message-ID<mailman.6825.1392265995.18130.python-list@python.org>
In reply to#66151
On Thu, Feb 13, 2014 at 3:24 PM, Steven D'Aprano <steve@pearwood.info> wrote:
> Of course it can happen by accident. It's happened to me, where I've
> accidentally called NoneType() (which raises, rather than returning a new
> instance).

It does in 2.7, yes, but not in 3.4:

>>> type(None)() is None
True

Definitely prefer returning the singleton to raising.

ChrisA

[toc] | [prev] | [next] | [standalone]


#66281

FromGregory Ewing <greg.ewing@canterbury.ac.nz>
Date2014-02-14 18:15 +1300
Message-ID<bm5n3bFqbmfU1@mid.individual.net>
In reply to#66151
Steven D'Aprano wrote:
> Of course it can happen by accident. It's happened to me, where I've 
> accidentally called NoneType() (which raises, rather than returning a new 
> instance).

Well, "unlikely to happen by accident", then.

-- 
Greg

[toc] | [prev] | [next] | [standalone]


#66280

FromGregory Ewing <greg.ewing@canterbury.ac.nz>
Date2014-02-14 18:06 +1300
Message-ID<bm5mj6Fq8idU1@mid.individual.net>
In reply to#66140
Steven D'Aprano wrote:
> On Wed, 12 Feb 2014 23:04:32 +1300, Gregory Ewing wrote:
> 
>>If you really want to make sure nobody creates another instance by
>>accident, delete the class out of the namespace after instantiating it.
> 
> That does not work. It is trivial to get the type from an instance:

I said *by accident*. Of course it's nearly impossible
to prevent someone who is determined enough from making
another instance, but it will prevent them from doing
so by mistake, if, e.g. they fail to notice the line
in the docs that says "don't try to instantiate this
directly, use the factory function".

-- 
Greg

[toc] | [prev] | [next] | [standalone]


#66062

FromAsaf Las <roegltd@gmail.com>
Date2014-02-12 09:50 -0800
Message-ID<9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com>
In reply to#65999
On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote:
> 
> Perhaps if you would state your actual goal,  we could judge
>  whether this code is an effective way to accomplish
>  it.
> DaveA

Thanks!

There is no specific goal, i am in process of building pattern knowledge 
in python by doing some examples.

[toc] | [prev] | [next] | [standalone]


#66064

FromAsaf Las <roegltd@gmail.com>
Date2014-02-12 09:56 -0800
Message-ID<9b4cd207-5485-43b2-b67a-520ef4a50075@googlegroups.com>
In reply to#66062
There is another one. 
Once object passes through singletonizator 
there wont be any other object than first one. 

Then object constructor can freely be used in every place 
of code. 
Curious if there could be any impact and applicability 
of this to builtin types. 

p.s. learned today that object __init__ member function is bound 
to its class :-)

class singletonizator(object):
    def __new__(cls, *args, **kwargs):
        
        def newnew(cls, *args, **kwargs):
            print("in new new", cls)
            return cls.__dict__['hidden_object'] 

        def newinit(self, *args, **kwargv):
            print("in new init", self) 
            pass

        if not 'hidden_object' in args[0].__class__.__dict__:
            setattr(args[0].__class__, 'hidden_object', args[0])
            args[0].__class__.__new__ = newnew
            args[0].__class__.__init__ = newinit
        return args[0]

class SomeClass:
    def __init__(self, num):
        print("in original init", self)
        self.mynum = num

first_object = singletonizator(SomeClass(1))
print(first_object, first_object.mynum)

second_object = singletonizator(SomeClass(2))
print(second_object, second_object.mynum)

third_one = SomeClass(3)
print(third_one, second_object.mynum)

exit()


in original init <__main__.SomeClass object at 0x0000000002F338D0>
<__main__.SomeClass object at 0x0000000002F338D0> 1
in new new <class '__main__.SomeClass'>
in new init <__main__.SomeClass object at 0x0000000002F338D0>
<__main__.SomeClass object at 0x0000000002F338D0> 1
in new new <class '__main__.SomeClass'>
in new init <__main__.SomeClass object at 0x0000000002F338D0>
<__main__.SomeClass object at 0x0000000002F338D0> 1

[toc] | [prev] | [next] | [standalone]


#66067

FromAsaf Las <roegltd@gmail.com>
Date2014-02-12 09:58 -0800
Message-ID<45df2d21-3141-47ca-a78e-f45d458738ee@googlegroups.com>
In reply to#66064
mistake, object constructor - to class constructor 

[toc] | [prev] | [next] | [standalone]


#66102

FromGregory Ewing <greg.ewing@canterbury.ac.nz>
Date2014-02-13 10:57 +1300
Message-ID<bm291gF4dvqU1@mid.individual.net>
In reply to#66064
Asaf Las wrote:
> There is another one. 
> Once object passes through singletonizator 
> there wont be any other object than first one. 
> 
> Then object constructor can freely be used in every place 
> of code.

You're still making things far more complicated
than they need to be.

*Why* do you want to be able to use the object
constructor, instead of just using the prebuilt
instance?

If you want to hide the distinction between using
call syntax and just accessing a global, then
export a function that returns the global instance.

That function can even lazily create the instance
the first time it's called. That's a pattern that
*is* useful, and I've often used in Python and
other languages.

E.g.

_the_whatsit = None

def get_whatsit():
    if _the_whatsit is None:
       _the_whatsit = Whatsit()
    return _the_whatsit

-- 
Greg

[toc] | [prev] | [next] | [standalone]


#66130

FromAsaf Las <roegltd@gmail.com>
Date2014-02-12 17:38 -0800
Message-ID<c35e5ea3-f523-4638-aeb3-e6c12d2b8006@googlegroups.com>
In reply to#66102
On Wednesday, February 12, 2014 11:57:02 PM UTC+2, Gregory Ewing wrote:
> 
> If you want to hide the distinction between using
> call syntax and just accessing a global, then
> export a function that returns the global instance.
> 
> That function can even lazily create the instance
> the first time it's called. That's a pattern that
> *is* useful, and I've often used in Python and
> other languages.
> E.g.
> _the_whatsit = None
> def get_whatsit():
>     if _the_whatsit is None:
>        _the_whatsit = Whatsit()
>     return _the_whatsit
> Greg

Gregory Ewing and Michael Torrie, yes you are both right, that is how things 
are done in standard Python library. But i am not restricting  myself to that.

Thanks 

/Asaf

[toc] | [prev] | [next] | [standalone]


#66073

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2014-02-12 18:57 +0000
Message-ID<mailman.6777.1392231445.18130.python-list@python.org>
In reply to#66062
On 12/02/2014 17:50, Asaf Las wrote:
> On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote:
>>
>> Perhaps if you would state your actual goal,  we could judge
>>   whether this code is an effective way to accomplish
>>   it.
>> DaveA
>
> Thanks!
>
> There is no specific goal, i am in process of building pattern knowledge
> in python by doing some examples.
>

For more data on python patterns search for 
python+patterns+Alex+Martelli.  He's forgotten more on the subject than 
many people on this list will ever know :)

-- 
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.

Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection is active.
http://www.avast.com

[toc] | [prev] | [next] | [standalone]


#66126

FromAsaf Las <roegltd@gmail.com>
Date2014-02-12 17:02 -0800
Message-ID<d3ea67fc-b1b9-4a3a-980b-d2f7962a9e34@googlegroups.com>
In reply to#66073
On Wednesday, February 12, 2014 8:57:09 PM UTC+2, Mark Lawrence wrote:
> 
> For more data on python patterns search for 
> python+patterns+Alex+Martelli.  He's forgotten more on the subject than 
> many people on this list will ever know :)
> 
> My fellow Pythonistas, ask not what our language can do for you, ask 
> what you can do for our language.
> 
> Mark Lawrence
> 

Oh, thanks, good information.

[toc] | [prev] | [next] | [standalone]


#66095

FromNed Batchelder <ned@nedbatchelder.com>
Date2014-02-12 16:34 -0500
Message-ID<mailman.6792.1392240886.18130.python-list@python.org>
In reply to#66062
On 2/12/14 12:50 PM, Asaf Las wrote:
> On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote:
>>
>> Perhaps if you would state your actual goal,  we could judge
>>   whether this code is an effective way to accomplish
>>   it.
>> DaveA
>
> Thanks!
>
> There is no specific goal, i am in process of building pattern knowledge
> in python by doing some examples.
>

Not all patterns are useful.  Just because it's been enshrined in the 
GoF patterns book doesn't mean that it's good for Python.

I don't understand why you would like a class to pretend to make new 
instances, but actually lie and return the same instance over and over. 
  It makes them impossible to test: your unit tests all act on the same 
object, there's no way to start over with a fresh object.

If you only want one object, create just one, and use it everywhere.

-- 
Ned Batchelder, http://nedbatchelder.com

[toc] | [prev] | [next] | [standalone]


#66129

FromAsaf Las <roegltd@gmail.com>
Date2014-02-12 17:34 -0800
Message-ID<90b35309-2ffb-46b6-98bd-3696124e5935@googlegroups.com>
In reply to#66095
On Wednesday, February 12, 2014 11:34:34 PM UTC+2, Ned Batchelder wrote:
> Not all patterns are useful.  Just because it's been enshrined in the 
> GoF patterns book doesn't mean that it's good for Python.

Yes, i understand up to some extend usefulness of patterns. 
i did not read the GoF book. yet.

> I don't understand why you would like a class to pretend to make new 
> instances, but actually lie and return the same instance over and over. 
>   It makes them impossible to test: your unit tests all act on the same 
> object, there's no way to start over with a fresh object.
> 
> If you only want one object, create just one, and use it everywhere.
> 
> Ned Batchelder, http://nedbatchelder.com

Actually it is not about singleton. Let say if i would like to make set 
of resources with controllable quantity and not for single class but
for let say 10 or 20 classes , so i could read config file at time of program
start and create them accordingly and only when needed.
having unified attribute names within resource classes allows to do more 
more from one place, let say leaving resource recovery to background thread
via proxy methods for failed resources, or scanning of objects in resource 
for timeouts or ticking clocks on them for delayed response.

if there is no unified template - then for every particular class i have to 
put a list within module and count on number of objects created and then supervision and other things have to be handled separately. Though i do not 
defend current approach - it is a bit hack. same can be done via inheritance
from base classes or with a bit more typing via static methods.

Asaf

[toc] | [prev] | [next] | [standalone]


#66115

FromTim Delaney <timothy.c.delaney@gmail.com>
Date2014-02-13 10:08 +1100
Message-ID<mailman.6804.1392246496.18130.python-list@python.org>
In reply to#66062

[Multipart message — attachments visible in raw view] — view raw

On 13 February 2014 08:34, Ned Batchelder <ned@nedbatchelder.com> wrote:

> On 2/12/14 12:50 PM, Asaf Las wrote:
>
>> On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote:
>>
>>>
>>> Perhaps if you would state your actual goal,  we could judge
>>>   whether this code is an effective way to accomplish
>>>   it.
>>> DaveA
>>>
>>
>> Thanks!
>>
>> There is no specific goal, i am in process of building pattern knowledge
>> in python by doing some examples.
>>
>>
> Not all patterns are useful.  Just because it's been enshrined in the GoF
> patterns book doesn't mean that it's good for Python.
>

Speaking of which, my monitor is currently sitting on my copy of "Design
Patterns".

A lot of "Design Patterns" isn't directly relevant to Python, because
Python either already has various patterns implemented, or obviates the
need for them. For example, if you really need a singleton (answer - you
don't) just use a module attribute. Functions as objects and iterators
being so pervasive means that visitor and related patterns are just a
normal style of programming, instead of having to be explicit.

Tim Delaney

[toc] | [prev] | [next] | [standalone]


#66134

FromRoy Smith <roy@panix.com>
Date2014-02-12 20:57 -0500
Message-ID<roy-4E11BD.20575612022014@news.panix.com>
In reply to#66062
In article <9785668d-6bea-4382-8a0c-c1258f2e2693@googlegroups.com>,
 Asaf Las <roegltd@gmail.com> wrote:

> On Wednesday, February 12, 2014 7:48:51 AM UTC+2, Dave Angel wrote:
> > 
> > Perhaps if you would state your actual goal,  we could judge
> >  whether this code is an effective way to accomplish
> >  it.
> > DaveA
> 
> Thanks!
> 
> There is no specific goal, i am in process of building pattern knowledge 
> in python by doing some examples.

That is a worthy goal.  Patterns are interesting, and sometimes useful.  
Sometimes they're useful just as a vocabulary to help you think and talk 
about program structure.

Just be aware that, like so many good things, a whole religion has grown 
up around them.  Understanding the concept without getting sucked into 
the religion is a good goal.

[toc] | [prev] | [next] | [standalone]


#66103

FromMichael Torrie <torriem@gmail.com>
Date2014-02-12 15:05 -0700
Message-ID<mailman.6798.1392242786.18130.python-list@python.org>
In reply to#65995
On 02/11/2014 09:34 PM, Asaf Las wrote:
> playing a bit with subject. 
> 
> pros and cons of this approach? did i create bicycle again? :-)

I always thought sticking an object in a module is the simplest form of
singleton.

[toc] | [prev] | [standalone]


Page 2 of 2 — ← Prev page 1 [2]

Back to top | Article view | comp.lang.python


csiph-web