Nov 30
Cool Python Tricks part I
I’ve spent almost five years programming as a hobby, and my first language was Python. Its still one of my favourites for many reasons; simplicity, power, rapid development, and its fun.
Due to its nature, Python is very flexible and very versatile, and over the years, I’ve learned some very very cool and useful python idioms and tricks.
What I will show today is a Design Pattern that fits the ideology of Python well, and delivers a great amount of flexibility and usefulness. Its called the Borg Design Pattern.
I’m sure we’re all familiar with the Singleton design pattern. The Borg DP is almost precisely the opposite. Instead of one instantiated object, and just one, the Borg DP allows you to instantiate any number of the objects, and have them all share the exact same traits, methods, variables.
(assume there is proper formatting for this function)
1| class Borg:
2| _share_state={}
3| def __init__(self, *args, **kwargs):
4| self.__dict__=self._shared_state
Here’s the beauty of the Borg DP: on any of the instantiated objects, if you modify a variable, all of the instantiated objects reflect that modification. Every single one of them. Hence the name, Borg Design Pattern.
The important line here is line two: “__dict__={}” before you declare any methods of variables. When you do this in Python, all instantiated classes have a reference to that single variable and object. And __dict__ is an internal dict of the class, that stores all methods and all variables!
The power of this trick is such that, you can use it for many of the same places you once used a Singleton, but without needing to worry about references, thread safe access, even checking how many objects have been instantiated. It cleans up all associated code, and gives you the confidence to know exactly what is going on with the object.
And thats part one! Stay tuned for more Cool Python Tricks(tm), hopefully one a week!
EDIT: Fixed borg design pattern, small bug.
Comments are off for this post