How can I create customized classes that have similar properties as 'str'?

Peter Otten __peter__ at web.de
Sun Nov 25 04:39:38 EST 2007


Steven D'Aprano wrote:

>>>>> store = {}
>>>>> def atom(str):
>> 	global store
>> 	if str not in store:
>> 		store[str] = str
>> 	return store[str]
> 
> Oh lordy, that's really made my day! That's the funniest piece of code 
> I've seen for a long time! Worthy of being submitted to the DailyWTF.

Here's a script to show atom()'s effect on memory footprint:

$ cat atom.py
import sys
data = [1]*1000
items = []
cache = {}
if "-a" in sys.argv:
    def atom(obj):
        try:
            return cache[obj]
        except KeyError:
            cache[obj] = obj
            return obj
else:
    def atom(obj):
        return obj
try:
    while 1:
        items.append(atom(tuple(data)))
except MemoryError:
    print len(items)
$ ulimit -v 5000
$ python atom.py
226
$ python atom.py -a
185742

So if you are going to submit Sam's function make sure to bundle it with
this little demo...

Peter



More information about the Python-list mailing list