[Tutor] Deleting singleton objects

dman dman@dman.ddts.net
Wed, 22 May 2002 23:44:07 -0500


--YZ5djTAD1cGYuMQK
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Thu, May 23, 2002 at 01:15:33PM +0930, BELSEY, Dylan wrote:
=20
| 	BTW is there a more efficient or standard way of implementing a
| singleton in Python, that is a lot "cleaner".

Yeah, normally singletons aren't destroyed at all during the lifetime
of a program.  (see the GoF book)

Here's how it is typically done in Python :


class _single_class :
    # whatever the implementation is
    pass

# make the one and only instance
_single =3D _single_class()

# we don't need the class hanging around to tempt people to misbehave
del _single_class

# a function to hide the fact that the class is a singleton
def single() : return _single


This does 3 things :
    1)  uses underscores to indicate, via convention, private names

    2)  creates the instance at the module level (since modules exist
        in python, though C++ and Java lack them)

    3)  destroys the (easy to get to) handle to the class so that it
        can't be constructed any more

    4)  Uses a function to hide the fact that the class is a
        singleton.  This is another area where Python shines -- in
        C++/Java, instantiating a class does not look like a function
        call, so this sort of thing can't be done transparently.

HTH,
-D

--=20

Come to me, all you who are weary and burdened, and I will give you
rest.  Take my yoke upon you and learn from me, for I am gentle and
humble in heart, and you will find rest for your souls.  For my yoke
is easy and my burden is light.
        Matthew 11:28-30
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--YZ5djTAD1cGYuMQK
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzsc5cACgkQO8l8XBKTpRRtsQCfVtcqTo96SoONo2WZFGB/izAF
1eoAn13sleg5CU1znWilzTn/aBZX/Suz
=70H5
-----END PGP SIGNATURE-----

--YZ5djTAD1cGYuMQK--