/timm's /charming /python /tricks
Download
base.py.
Read more on How to be Charming (in Python).
01: import sys 02: sys.dont_write_bytecode=True # no .pyc files 03: import random 04: 05: #---- Cool Classes ---------------------------- 06: 07: class Charmed: 08: "Our objects are charming." 09: def __repr__(i): 10: """ 11: This Charmed object knows how to print 12: all their slots, except for the private ones 13: (those that start with "_"). 14: """ 15: args = [] 16: for key,val in vars(i).items(): 17: if key[0] != "_": 18: args += ['%s=%s'% (key,val)] 19: what = i.__class__.__name__ 20: return '%s(%s)' % (what, ', '.join(args)) 21: 22: class Thing(Charmed): 23: """Norvig's shortcut for creating objects that 24: that holds data in several fields.""" 25: def __init__(self, **entries): 26: self.__dict__.update(entries) 27: 28: class Sample(Charmed): 29: "Keep a random sample of stuff seen so far." 30: def __init__(i,size=64): 31: i._cache, i.size, i.n = [],size, 0.0 32: i._ordered=False 33: def sorted(i): 34: if not i._ordered: 35: i._cache = sorted(i._cache) 36: i._ordered=True 37: return i._cache 38: def seen(i,x): 39: i.n += 1 40: if len(i._cache) < i.size : 41: i._cache += [x] 42: i._ordered=False 43: else: 44: if random.random() <= i.size/i.n: 45: i._cache[int(random.random()*i.size)] = x 46: i._ordered=False 47:
This file is part of Timm's charming Python tricks.
© 2014, Tim Menzies:
tim.menzies@gmail.com,
http://menzies.us.
Timm's charming Python tricks are free software: you can redistribute it and/or modify it under the terms of the GNU Lesser Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Timm's charming Python tricks are distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU Lesser Public License along with Foobar. If not, see http://www.gnu.org/licenses.