In article <mailman.6834.1392292646.18130.python-l...@python.org>, Chris Angelico <ros...@gmail.com> wrote:
> On Thu, Feb 13, 2014 at 10:50 PM, Ned Batchelder <n...@nedbatchelder.com> > wrote: > > I still don't see it. To convince me that a singleton class makes sense, > > you'd have to explain why by virtue of the class's very nature, it never > > makes sense for there ever to be more than one of them. > > There's a huge difference, btw, between mutable and immutable > singletons. With immutables like None, True/False, integers, strings, > and tuples thereof, returning a preexisting object is just an > optimization. Do it if you want, don't if you don't, nobody's going to > hugely care. People *depend* on None being a singleton (and are encouraged to do so), when they use "is" as the test-for-Noneness. > With mutables, it's hugely different. A singleton > "database connection" object would, imo, be hugely confusing; you'd > think you created a separate connection object, but no, what you do on > this one affects the other. Except that if you do caching in the database connector, you would certainly want the cache to be shared between all the users. There's no right answer here. Each way has it's advantages and disadvantages. And it would only be confusing if the documentation didn't spell out which way it was doing it, leaving people to make (possibly wrong) assumptions. > Better there to have module-level functions; at least Python > programmers should understand that reimporting a module gives you > back another reference to the same module. Except when it doesn't. Singleton-ness of modules depends on the names under which they were imported. Symlinks, for example, can fool the import machinery. $ ls -l s1 s2 lrwxrwxrwx 1 roy roy 1 Feb 13 10:13 s1 -> s lrwxrwxrwx 1 roy roy 1 Feb 13 10:13 s2 -> s $ ls -l s total 12 -rw-rw-r-- 1 roy roy 0 Feb 13 10:13 __init__.py -rw-rw-r-- 1 roy roy 101 Feb 13 10:14 __init__.pyc -rw-rw-r-- 1 roy roy 9 Feb 13 10:12 singleton.py -rw-rw-r-- 1 roy roy 123 Feb 13 10:14 singleton.pyc >>> import s1.singleton >>> import s2.singleton >>> s1.singleton == s2.singleton False -- https://mail.python.org/mailman/listinfo/python-list