Generic singleton

David Bolen at
Thu Mar 4 20:21:58 CET 2010

Duncan Booth <duncan.booth at invalid.invalid> writes:

> It is also *everywhere* in the Python world. Unlike Java and C++, Python 
> even has its own built-in type for singletons.
> If you want a singleton in Python use a module.
> So the OP's original examples become:
> --- file ---
> foo = {}
> bar = []
> --- ---
> from singleton import foo as s1
> from singleton import foo as s2
> from singleton import bar as s3
> from singleton import bar as s4
> ... and then use them as you wish.

In the event you do use a module as a singleton container, I would
advocate sticking with fully qualified names, avoiding the use of
"from" imports or any other local namespace caching of references.

Other code sharing the module may not update things as expected, e.g.:

    import singleton = {}

at which point you've got two objects around - one in the
module namespace, and the s1/s2 referenced object in

If you're confident of the usage pattern of all the using code, it may
not be critical.  But consistently using "" (or an import
alias like is a bit more robust, sticking with only one
namespace to reach the singleton.

-- David

More information about the Python-list mailing list