d6fbf12989
Remove all trailing spaces and tabs in every file in the project. People have editors configured to do this, which causes them to accidentally make little whitespace changes in unrelated commits, which makes those commits harder to review. Better to fix them all at once. Change-Id: I17d89f55f41d8599e0ab1a31f646cd161289703e
37 lines
1.1 KiB
Python
37 lines
1.1 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
|
|
class KeyedInstance(object):
|
|
"""A class whose instances have a unique identifier of some sort
|
|
No two instances with the same unique ID should exist - if we try to create
|
|
a second instance, the first should be returned.
|
|
"""
|
|
|
|
_instances = dict()
|
|
|
|
def __new__(cls, *p, **k):
|
|
instances = cls._instances
|
|
clskey = str(cls)
|
|
if clskey not in instances:
|
|
instances[clskey] = dict()
|
|
instances = instances[clskey]
|
|
|
|
key = cls._key(*p, **k)
|
|
if key not in instances:
|
|
instances[key] = super(KeyedInstance, cls).__new__(cls)
|
|
return instances[key]
|
|
|
|
@classmethod
|
|
def _key(cls, *p, **k):
|
|
"""Given a unique identifier, return a dictionary key
|
|
This should be overridden by child classes, to specify which parameters
|
|
should determine an object's uniqueness
|
|
"""
|
|
raise NotImplementedError()
|
|
|
|
@classmethod
|
|
def clear(cls):
|
|
# Allow cls.clear() as well as uniqueInstance.clear(cls)
|
|
if str(cls) in cls._instances:
|
|
del cls._instances[str(cls)]
|