python 2.1 singleton

A

Alexiev Nikolay

I need a simple implementation of singleton that will work on python 2.1. I
havn't got idea how to creat without staticmethod. Can you give me a
solution ??? 10x in advance
 
D

Duncan Booth

I need a simple implementation of singleton that will work on python
2.1. I havn't got idea how to creat without staticmethod. Can you give
me a solution ??? 10x in advance

The simplest singleton implementation, which works for any version of
Python is simply to use a module as your singleton instead of a class. You
can get hold of the singleton object from anywhere simply by importing it.
All functions defined in a module are effectively static methods on the
module object.
 
A

Alex Martelli

Duncan said:
The simplest singleton implementation, which works for any version of
Python is simply to use a module as your singleton instead of a class. You
can get hold of the singleton object from anywhere simply by importing it.
All functions defined in a module are effectively static methods on the
module object.

Amen, Hallelujah. This will be optimal any time you don't need some of the
capabilities that classes have over modules -- basically, inheritance and
special methods. When you DO need to expose a class, I still suggest the
Borg nonpattern, http://www.aleax.it/5ep.html -- even though Guido hates
it with a vengeance, I'm still convinced it's superior to Singleton.

If you _do_ perversely want the Singleton DP no matter what, you don't
need static methods -- you can use a toplevel function just as well.

If you _do_ perversely want static methods in 2.1 no matter what,

class staticmethod:
def __init__(self, thefunc): self.f = thefunc
def __call__(self, *a, **k): return self.f(*a, **k)

and just use this staticmethod instead of 2.2's builtin one.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

PyPy3 2.1 beta 1 released 0
Singleton class in C++ 4
Help with Singleton SafeConfigParser 4
Singleton 12
ANN: Albow 2.1 0
Monkeypatching a staticmethod? 2
python destructor 1
Java singletonMap in Python 5

Members online

Forum statistics

Threads
474,167
Messages
2,570,911
Members
47,453
Latest member
MadelinePh

Latest Threads

Top