classes
Steven Taschuk
staschuk at telusplanet.net
Mon Jul 21 20:37:01 EDT 2003
Quoth Michele Simionato:
> Steven Taschuk <staschuk at telusplanet.net> wrote in message news:<mailman.1058723911.12956.python-list at python.org>...
[...]
> > _the_instance = None
> > class MySingleton(object):
> > def __new__(self):
> > global _the_instance
> > if _the_instance is None:
> > _the_instance = object.__new__(self)
> > return _the_instance
>
> Why are you using a global here and not [a class attribute]
The memory of that thread a little while back about using __del__
with singletons. If the instance is referenced by a class
attribute, the cyclic reference prevents the __del__ from being
used. If the cycle goes through a module attribute, though, the
zapping of module dicts during shutdown breaks the cycle and lets
the __del__ run. (Whether all this is true depends on the version
of Python, I think, but I don't know the details.)
This might be relevant to the OP, whose example was a singleton
representing the single database connection used by an entire
application -- in such a case, __del__ would be a natural place to
make sure the connection is closed properly.
I should have explained this bit of trickery. :(
[...]
> > Second approach: Use a metaclass. See
> > <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/102187>
>
>
> Unfortunately, I see that this recipe is not very recommendable. I have
> just submitted a fix which seems to work:
[...]
Nice!
--
Steven Taschuk Aral: "Confusion to the enemy, boy."
staschuk at telusplanet.net Mark: "Turn-about is fair play, sir."
-- _Mirror Dance_, Lois McMaster Bujold
More information about the Python-list
mailing list