July 2009
5 posts
1 tag
Flyweighting in Python Redux
I just expanded the Flyweighted Object class to support keyword arguments:
import weakref
import cPickle
class FlyweightedObject(object):
_pool = weakref.WeakValueDictionary()
def __new__(klass, *args, **kwargs):
if not hasattr(klass.__init__, 'im_func'): raise 'cannot flyweight an object which has no python constructor'
arguments = {}
constructor =...
1 tag
Flyweighting in Python
If you are dealing with large static datasets in Python it can be useful to flyweight your objects. With flyweighting, every time you construct a new object you check to see if it already exists. If so, the original object will be returned instead of constructing a duplicate.
Recently I wrote a little bit of code to achieve this in the general case:
import weakref
class...
1 tag
Haml 2.2 Compile Error In Ugly Production Mode
If you were previously using the Haml syntax:
%p= 'string ', method, ' string'
you will need to change it to:
%p= ['string ', method, ' string']
to avoid compilation errors in production mode.
1 tag
Python Slots
I just got clued in by Elf Sternberg’s Blog to a really useful feature in Python that I have never heard about before, slots:
class Foo(object):
__slots__ = ['x']
def __init__(self, n):
self.x = n
From the Python reference manual:
“By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance...
1 tag
JavaScript String format
Here’s a useful snippet of JavaScript I use for inserting arguments into a format string:
String.format = function()
{
var replacements = arguments;
return arguments[0].replace(/\{(\d+)\}/gm, function(string, match) {
return replacements[parseInt(match) + 1];
});
}
And here it is in action:
String.format('http://www.google.com/search?q={0}', escape(searchTerm))