Coming from Bioinformatics and having to deal with multiple objects with unique properties, like genes, proteins, and many more, I felt the need for a class that would always yield a unique instance based on a chosen identifier. This is because I always wanted the same instances whose attributes were filled with information and track them in various storage classes, like dictionaries, lists, etc. The code for the class lives over on github. Recently, I've added a lot of parallel-processing code so I adapted the pickling behaviour for this class to also yield existing instances. What follows is an example of how to use it and some discussion questions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
>>> import base >>> class UniqueSub(base.UniqueBase): def __init__(self, unique_id, a=1, b=2, **kw_args): super(UniqueSub, self).__init__(unique_id, **kw_args) self.a = a self.b = b >>> first = UniqueSub("item 1") >>> second = UniqueSub("item 2", a=4, b=7) # keyword arguments are required >>> third = UniqueSub("item 1", a=3, b=6) # new argument values are ignored >>> third.a 1 >>> third.b 2 >>> first == third True >>> import pickle >>> with open("/tmp/test.pkl", "wb") as handle: pickle.dump(first, handle, 0) # protocol level zero just to prove that it also works >>> with open("/tmp/test.pkl", "rb") as handle: fourth = pickle.load(handle) >>> fourth == first True
I would like to discuss two parts:
- Comments on the general implementation, particularly with regard to the un-/pickling.
- A catchy name for the design pattern (DP).
Since there exist the Singleton DP (single instance per class) and the Borg DP (shared state among all instances, even potentially with subclasses), I thought of naming this either the Humanity DP (in direct opposition to Borg, since we're all unique in our attributes but maybe share a common set of skills within our class) or the Snowflake DP (in reference to Tyler's monologue, "You are not a beautiful and unique snowflake" in Chuck Palahniuk's, Fight Club).