I am creating a Python application that includes socket communication with a server. I would like to have a module which can be used throughout my entire application (several other modules). Currently my module look like this:
class SocketCommunication:
def __init__(self):
self.socketIO = SocketIO(settings.ADDRESS, settings.PORT, Namespace)
def emit(self, message, data):
json_data = json.dumps(data.__dict__)
self.socketIO.emit(message, json_data)
class Namespace(BaseNamespace):
def on_connect(self):
print '[Connected]'
def on_disconnect(self):
print "[Disconnected]"
When I use this in other modules I do the following:
import SocketCommunication
self.sc = SocketCommunication()
The problem is that every time I do this, a new connection is created which will be displayed as a new client on the server, and that is undesirable. From what I can read, Singletons should be avoided in Python and therefore I am curious about what is best practice for this type of problem?
Singletons are controversial because they're often used as a way to wrap up global variables. This is why some people advocate for their avoidance. Globals make testing harder, they limit access control, and often lead to strong coupling between variables. (see http://wiki.c2.com/?GlobalVariablesAreBad for more details as to why globals are generally bad practice)
In your particular scenario, using a singleton is most likely appropriate because you are simply trying to stop
SocketCommunication
being initialised multiple times (for good reason), rather than trying to use it as a container for a global state.See Are Singletons really that bad? and What is so bad about singletons? for some discussion on Singletons.
The following are three ways to use singleton in Python. Using
metaclass
anddecorator
to reach the goal.use
__new__
use
__metaclass__
use
decorator
I prefer to use
decorator
.