PythonUtil.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  1. import types
  2. import string
  3. import re
  4. import math
  5. import operator
  6. import inspect
  7. import os
  8. import sys
  9. import random
  10. if __debug__:
  11. import traceback
  12. from direct.directutil import Verify
  13. ScalarTypes = (types.FloatType, types.IntType, types.LongType)
  14. # NOTE: ifAbsentPut has been replaced with Python's dictionary's builtin setdefault
  15. # before:
  16. # ifAbsentPut(dict, key, defaultValue)
  17. # after:
  18. # dict.setdefault(key, defaultValue)
  19. # Please use setdefault instead -- Joe
  20. def enumerate(L):
  21. """Returns (0, L[0]), (1, L[1]), etc., allowing this syntax:
  22. for i, item in enumerate(L):
  23. ...
  24. enumerate is a built-in feature in Python 2.3, which implements it
  25. using an iterator. For now, we can use this quick & dirty
  26. implementation that returns a list of tuples that is completely
  27. constructed every time enumerate() is called.
  28. """
  29. return zip(xrange(len(L)), L)
  30. import __builtin__
  31. if hasattr(__builtin__, 'enumerate'):
  32. print 'enumerate is already present in __builtin__'
  33. else:
  34. __builtin__.enumerate = enumerate
  35. def unique(L1, L2):
  36. """Return a list containing all items in 'L1' that are not in 'L2'"""
  37. L2 = dict([(k,None) for k in L2])
  38. return [item for item in L1 if item not in L2]
  39. def indent(stream, numIndents, str):
  40. """
  41. Write str to stream with numIndents in front of it
  42. """
  43. # To match emacs, instead of a tab character we will use 4 spaces
  44. stream.write(' ' * numIndents + str)
  45. def writeFsmTree(instance, indent = 0):
  46. if hasattr(instance, 'parentFSM'):
  47. writeFsmTree(instance.parentFSM, indent-2)
  48. elif hasattr(instance, 'fsm'):
  49. name = ''
  50. if hasattr(instance.fsm, 'state'):
  51. name = instance.fsm.state.name
  52. print "%s: %s"%(instance.fsm.name, name)
  53. if __debug__:
  54. class StackTrace:
  55. def __init__(self, label="", start=0, limit=None):
  56. """
  57. label is a string (or anything that be be a string)
  58. that is printed as part of the trace back.
  59. This is just to make it easier to tell what the
  60. stack trace is referring to.
  61. start is an integer number of stack frames back
  62. from the most recent. (This is automatically
  63. bumped up by one to skip the __init__ call
  64. to the StackTrace).
  65. limit is an integer number of stack frames
  66. to record (or None for unlimited).
  67. """
  68. self.label = label
  69. if limit is not None:
  70. self.trace = traceback.extract_stack(sys._getframe(1+start),
  71. limit=limit)
  72. else:
  73. self.trace = traceback.extract_stack(sys._getframe(1+start))
  74. def __str__(self):
  75. r = "Debug stack trace of %s (back %s frames):\n"%(
  76. self.label, len(self.trace),)
  77. for i in traceback.format_list(self.trace):
  78. r+=i
  79. return r
  80. def traceFunctionCall(frame):
  81. """
  82. return a string that shows the call frame with calling arguments.
  83. e.g.
  84. foo(x=234, y=135)
  85. """
  86. f = frame
  87. co = f.f_code
  88. dict = f.f_locals
  89. n = co.co_argcount
  90. if co.co_flags & 4: n = n+1
  91. if co.co_flags & 8: n = n+1
  92. r=''
  93. if dict.has_key('self'):
  94. r = '%s.'%(dict['self'].__class__.__name__, )
  95. r+="%s("%(f.f_code.co_name, )
  96. comma=0 # formatting, whether we should type a comma.
  97. for i in range(n):
  98. name = co.co_varnames[i]
  99. if name=='self':
  100. continue
  101. if comma:
  102. r+=', '
  103. else:
  104. # ok, we skipped the first one, the rest get commas:
  105. comma=1
  106. r+=name
  107. r+='='
  108. if dict.has_key(name):
  109. v=str(dict[name])
  110. if len(v)>200:
  111. r+="<too big for debug>"
  112. else:
  113. r+=str(dict[name])
  114. else: r+="*** undefined ***"
  115. return r+')'
  116. def traceParentCall():
  117. return traceFunctionCall(sys._getframe(2))
  118. def printThisCall():
  119. print traceFunctionCall(sys._getframe(1))
  120. return 1 # to allow "assert printThisCall()"
  121. if __debug__:
  122. def lineage(obj, verbose=0, indent=0):
  123. """
  124. return instance or class name in as a multiline string.
  125. Usage: print lineage(foo)
  126. (Based on getClassLineage())
  127. """
  128. r=""
  129. if type(obj) == types.ListType:
  130. r+=(" "*indent)+"python list\n"
  131. elif type(obj) == types.DictionaryType:
  132. r+=(" "*indent)+"python dictionary\n"
  133. elif type(obj) == types.ModuleType:
  134. r+=(" "*indent)+str(obj)+"\n"
  135. elif type(obj) == types.InstanceType:
  136. r+=lineage(obj.__class__, verbose, indent)
  137. elif type(obj) == types.ClassType:
  138. r+=(" "*indent)
  139. if verbose:
  140. r+=obj.__module__+"."
  141. r+=obj.__name__+"\n"
  142. for c in obj.__bases__:
  143. r+=lineage(c, verbose, indent+2)
  144. return r
  145. def tron():
  146. sys.settrace(trace)
  147. def trace(frame, event, arg):
  148. if event == 'line':
  149. pass
  150. elif event == 'call':
  151. print traceFunctionCall(sys._getframe(1))
  152. elif event == 'return':
  153. print "returning"
  154. elif event == 'exception':
  155. print "exception"
  156. return trace
  157. def troff():
  158. sys.settrace(None)
  159. def apropos(obj, *args):
  160. """
  161. Obsolete, use pdir
  162. """
  163. print 'Use pdir instead'
  164. def getClassLineage(obj):
  165. """
  166. print object inheritance list
  167. """
  168. if type(obj) == types.DictionaryType:
  169. # Just a dictionary, return dictionary
  170. return [obj]
  171. elif type(obj) == types.InstanceType:
  172. # Instance, make a list with the instance and its class interitance
  173. return [obj] + getClassLineage(obj.__class__)
  174. elif type(obj) == types.ClassType:
  175. # Class, see what it derives from
  176. lineage = [obj]
  177. for c in obj.__bases__:
  178. lineage = lineage + getClassLineage(c)
  179. return lineage
  180. else:
  181. # Not what I'm looking for
  182. return []
  183. def pdir(obj, str = None, fOverloaded = 0, width = None,
  184. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  185. # Remove redundant class entries
  186. uniqueLineage = []
  187. for l in getClassLineage(obj):
  188. if type(l) == types.ClassType:
  189. if l in uniqueLineage:
  190. break
  191. uniqueLineage.append(l)
  192. # Pretty print out directory info
  193. uniqueLineage.reverse()
  194. for obj in uniqueLineage:
  195. _pdir(obj, str, fOverloaded, width, fTruncate, lineWidth, wantPrivate)
  196. print
  197. def _pdir(obj, str = None, fOverloaded = 0, width = None,
  198. fTruncate = 1, lineWidth = 75, wantPrivate = 0):
  199. """
  200. Print out a formatted list of members and methods of an instance or class
  201. """
  202. def printHeader(name):
  203. name = ' ' + name + ' '
  204. length = len(name)
  205. if length < 70:
  206. padBefore = int((70 - length)/2.0)
  207. padAfter = max(0,70 - length - padBefore)
  208. header = '*' * padBefore + name + '*' * padAfter
  209. print header
  210. print
  211. def printInstanceHeader(i, printHeader = printHeader):
  212. printHeader(i.__class__.__name__ + ' INSTANCE INFO')
  213. def printClassHeader(c, printHeader = printHeader):
  214. printHeader(c.__name__ + ' CLASS INFO')
  215. def printDictionaryHeader(d, printHeader = printHeader):
  216. printHeader('DICTIONARY INFO')
  217. # Print Header
  218. if type(obj) == types.InstanceType:
  219. printInstanceHeader(obj)
  220. elif type(obj) == types.ClassType:
  221. printClassHeader(obj)
  222. elif type (obj) == types.DictionaryType:
  223. printDictionaryHeader(obj)
  224. # Get dict
  225. if type(obj) == types.DictionaryType:
  226. dict = obj
  227. else:
  228. dict = obj.__dict__
  229. # Adjust width
  230. if width:
  231. maxWidth = width
  232. else:
  233. maxWidth = 10
  234. keyWidth = 0
  235. aproposKeys = []
  236. privateKeys = []
  237. remainingKeys = []
  238. for key in dict.keys():
  239. if not width:
  240. keyWidth = len(key)
  241. if str:
  242. if re.search(str, key, re.I):
  243. aproposKeys.append(key)
  244. if (not width) and (keyWidth > maxWidth):
  245. maxWidth = keyWidth
  246. else:
  247. if key[:1] == '_':
  248. if wantPrivate:
  249. privateKeys.append(key)
  250. if (not width) and (keyWidth > maxWidth):
  251. maxWidth = keyWidth
  252. else:
  253. remainingKeys.append(key)
  254. if (not width) and (keyWidth > maxWidth):
  255. maxWidth = keyWidth
  256. # Sort appropriate keys
  257. if str:
  258. aproposKeys.sort()
  259. else:
  260. privateKeys.sort()
  261. remainingKeys.sort()
  262. # Print out results
  263. if wantPrivate:
  264. keys = aproposKeys + privateKeys + remainingKeys
  265. else:
  266. keys = aproposKeys + remainingKeys
  267. format = '%-' + `maxWidth` + 's'
  268. for key in keys:
  269. value = dict[key]
  270. if callable(value):
  271. strvalue = `Signature(value)`
  272. else:
  273. strvalue = `value`
  274. if fTruncate:
  275. # Cut off line (keeping at least 1 char)
  276. strvalue = strvalue[:max(1,lineWidth - maxWidth)]
  277. print (format % key)[:maxWidth] + '\t' + strvalue
  278. # Magic numbers: These are the bit masks in func_code.co_flags that
  279. # reveal whether or not the function has a *arg or **kw argument.
  280. _POS_LIST = 4
  281. _KEY_DICT = 8
  282. def _is_variadic(function):
  283. return function.func_code.co_flags & _POS_LIST
  284. def _has_keywordargs(function):
  285. return function.func_code.co_flags & _KEY_DICT
  286. def _varnames(function):
  287. return function.func_code.co_varnames
  288. def _getcode(f):
  289. """
  290. _getcode(f)
  291. This function returns the name and function object of a callable
  292. object.
  293. """
  294. def method_get(f):
  295. return f.__name__, f.im_func
  296. def function_get(f):
  297. return f.__name__, f
  298. def instance_get(f):
  299. if hasattr(f, '__call__'):
  300. method = f.__call__
  301. if (type(method) == types.MethodType):
  302. func = method.im_func
  303. else:
  304. func = method
  305. return ("%s%s" % (f.__class__.__name__, '__call__'), func)
  306. else:
  307. s = ("Instance %s of class %s does not have a __call__ method" %
  308. (f, f.__class__.__name__))
  309. raise TypeError, s
  310. def class_get(f):
  311. if hasattr(f, '__init__'):
  312. return f.__name__, f.__init__.im_func
  313. else:
  314. return f.__name__, lambda: None
  315. codedict = { types.UnboundMethodType: method_get,
  316. types.MethodType : method_get,
  317. types.FunctionType : function_get,
  318. types.InstanceType : instance_get,
  319. types.ClassType : class_get,
  320. }
  321. try:
  322. return codedict[type(f)](f)
  323. except KeyError:
  324. if callable(f): # eg, built-in functions and methods
  325. # raise ValueError, "type %s not supported yet." % type(f)
  326. return f.__name__, None
  327. else:
  328. raise TypeError, ("object %s of type %s is not callable." %
  329. (f, type(f)))
  330. class Signature:
  331. def __init__(self, func):
  332. self.type = type(func)
  333. self.name, self.func = _getcode(func)
  334. def ordinary_args(self):
  335. n = self.func.func_code.co_argcount
  336. return _varnames(self.func)[0:n]
  337. def special_args(self):
  338. n = self.func.func_code.co_argcount
  339. x = {}
  340. #
  341. if _is_variadic(self.func):
  342. x['positional'] = _varnames(self.func)[n]
  343. if _has_keywordargs(self.func):
  344. x['keyword'] = _varnames(self.func)[n+1]
  345. elif _has_keywordargs(self.func):
  346. x['keyword'] = _varnames(self.func)[n]
  347. else:
  348. pass
  349. return x
  350. def full_arglist(self):
  351. base = list(self.ordinary_args())
  352. x = self.special_args()
  353. if x.has_key('positional'):
  354. base.append(x['positional'])
  355. if x.has_key('keyword'):
  356. base.append(x['keyword'])
  357. return base
  358. def defaults(self):
  359. defargs = self.func.func_defaults
  360. args = self.ordinary_args()
  361. mapping = {}
  362. if defargs is not None:
  363. for i in range(-1, -(len(defargs)+1), -1):
  364. mapping[args[i]] = defargs[i]
  365. else:
  366. pass
  367. return mapping
  368. def __repr__(self):
  369. if self.func:
  370. defaults = self.defaults()
  371. specials = self.special_args()
  372. l = []
  373. for arg in self.ordinary_args():
  374. if defaults.has_key(arg):
  375. l.append( arg + '=' + str(defaults[arg]) )
  376. else:
  377. l.append( arg )
  378. if specials.has_key('positional'):
  379. l.append( '*' + specials['positional'] )
  380. if specials.has_key('keyword'):
  381. l.append( '**' + specials['keyword'] )
  382. return "%s(%s)" % (self.name, string.join(l, ', '))
  383. else:
  384. return "%s(?)" % self.name
  385. def aproposAll(obj):
  386. """
  387. Print out a list of all members and methods (including overloaded methods)
  388. of an instance or class
  389. """
  390. apropos(obj, fOverloaded = 1, fTruncate = 0)
  391. def doc(obj):
  392. if (isinstance(obj, types.MethodType)) or \
  393. (isinstance(obj, types.FunctionType)):
  394. print obj.__doc__
  395. def adjust(command = None, dim = 1, parent = None, **kw):
  396. """
  397. adjust(command = None, parent = None, **kw)
  398. Popup and entry scale to adjust a parameter
  399. Accepts any Slider keyword argument. Typical arguments include:
  400. command: The one argument command to execute
  401. min: The min value of the slider
  402. max: The max value of the slider
  403. resolution: The resolution of the slider
  404. text: The label on the slider
  405. These values can be accessed and/or changed after the fact
  406. >>> vg = adjust()
  407. >>> vg['min']
  408. 0.0
  409. >>> vg['min'] = 10.0
  410. >>> vg['min']
  411. 10.0
  412. """
  413. # Make sure we enable Tk
  414. from direct.tkwidgets import Valuator
  415. # Set command if specified
  416. if command:
  417. kw['command'] = lambda x: apply(command, x)
  418. if parent is None:
  419. kw['title'] = command.__name__
  420. kw['dim'] = dim
  421. # Create toplevel if needed
  422. if not parent:
  423. vg = apply(Valuator.ValuatorGroupPanel, (parent,), kw)
  424. else:
  425. vg = apply(Valuator.ValuatorGroup,(parent,), kw)
  426. vg.pack(expand = 1, fill = 'x')
  427. return vg
  428. def intersection(a, b):
  429. """
  430. intersection(list, list):
  431. """
  432. if not a: return []
  433. if not b: return []
  434. d = []
  435. for i in a:
  436. if (i in b) and (i not in d):
  437. d.append(i)
  438. for i in b:
  439. if (i in a) and (i not in d):
  440. d.append(i)
  441. return d
  442. def union(a, b):
  443. """
  444. union(list, list):
  445. """
  446. # Copy a
  447. c = a[:]
  448. for i in b:
  449. if (i not in c):
  450. c.append(i)
  451. return c
  452. def sameElements(a, b):
  453. if len(a) != len(b):
  454. return 0
  455. for elem in a:
  456. if elem not in b:
  457. return 0
  458. for elem in b:
  459. if elem not in a:
  460. return 0
  461. return 1
  462. def list2dict(L, value=None):
  463. """creates dict using elements of list, all assigned to same value"""
  464. return dict([(k,value) for k in L])
  465. def invertDict(D):
  466. """creates a dictionary by 'inverting' D; keys are placed in the new
  467. dictionary under their corresponding value in the old dictionary.
  468. Data will be lost if D contains any duplicate values.
  469. >>> old = {'key1':1, 'key2':2}
  470. >>> invertDict(old)
  471. {1: 'key1', 2: 'key2'}
  472. """
  473. n = {}
  474. for key, value in D.items():
  475. n[value] = key
  476. return n
  477. def invertDictLossless(D):
  478. """similar to invertDict, but values of new dict are lists of keys from
  479. old dict. No information is lost.
  480. >>> old = {'key1':1, 'key2':2, 'keyA':2}
  481. >>> invertDictLossless(old)
  482. {1: ['key1'], 2: ['key2', 'keyA']}
  483. """
  484. n = {}
  485. for key, value in D.items():
  486. n.setdefault(value, [])
  487. n[value].append(key)
  488. return n
  489. def uniqueElements(L):
  490. """are all elements of list unique?"""
  491. return len(L) == len(list2dict(L))
  492. def disjoint(L1, L2):
  493. """returns non-zero if L1 and L2 have no common elements"""
  494. used = dict([(k,None) for k in L1])
  495. for k in L2:
  496. if k in used:
  497. return 0
  498. return 1
  499. def contains(whole, sub):
  500. """
  501. Return 1 if whole contains sub, 0 otherwise
  502. """
  503. if (whole == sub):
  504. return 1
  505. for elem in sub:
  506. # The first item you find not in whole, return 0
  507. if elem not in whole:
  508. return 0
  509. # If you got here, whole must contain sub
  510. return 1
  511. def replace(list, old, new, all=0):
  512. """
  513. replace 'old' with 'new' in 'list'
  514. if all == 0, replace first occurrence
  515. otherwise replace all occurrences
  516. returns the number of items replaced
  517. """
  518. if old not in list:
  519. return 0
  520. if not all:
  521. i = list.index(old)
  522. list[i] = new
  523. return 1
  524. else:
  525. numReplaced = 0
  526. for i in xrange(len(list)):
  527. if list[i] == old:
  528. numReplaced += 1
  529. list[i] = new
  530. return numReplaced
  531. def reduceAngle(deg):
  532. """
  533. Reduces an angle (in degrees) to a value in [-180..180)
  534. """
  535. return (((deg + 180.) % 360.) - 180.)
  536. def fitSrcAngle2Dest(src, dest):
  537. """
  538. given a src and destination angle, returns an equivalent src angle
  539. that is within [-180..180) of dest
  540. examples:
  541. fitSrcAngle2Dest(30,60) == 30
  542. fitSrcAngle2Dest(60,30) == 60
  543. fitSrcAngle2Dest(0,180) == 0
  544. fitSrcAngle2Dest(-1,180) == 359
  545. fitSrcAngle2Dest(-180,180) == 180
  546. """
  547. return dest + reduceAngle(src - dest)
  548. def fitDestAngle2Src(src, dest):
  549. """
  550. given a src and destination angle, returns an equivalent dest angle
  551. that is within [-180..180) of src
  552. examples:
  553. fitDestAngle2Src(30,60) == 60
  554. fitDestAngle2Src(60,30) == 30
  555. fitDestAngle2Src(0,180) == -180
  556. fitDestAngle2Src(1,180) == 180
  557. """
  558. return src + (reduceAngle(dest - src))
  559. def closestDestAngle2(src, dest):
  560. # The function above didn't seem to do what I wanted. So I hacked
  561. # this one together. I can't really say I understand it. It's more
  562. # from impirical observation... GRW
  563. diff = src - dest
  564. if diff > 180:
  565. # if the difference is greater that 180 it's shorter to go the other way
  566. return dest - 360
  567. elif diff < -180:
  568. # or perhaps the OTHER other way...
  569. return dest + 360
  570. else:
  571. # otherwise just go to the original destination
  572. return dest
  573. def closestDestAngle(src, dest):
  574. # The function above didn't seem to do what I wanted. So I hacked
  575. # this one together. I can't really say I understand it. It's more
  576. # from impirical observation... GRW
  577. diff = src - dest
  578. if diff > 180:
  579. # if the difference is greater that 180 it's shorter to go the other way
  580. return src - (diff - 360)
  581. elif diff < -180:
  582. # or perhaps the OTHER other way...
  583. return src - (360 + diff)
  584. else:
  585. # otherwise just go to the original destination
  586. return dest
  587. def binaryRepr(number, max_length = 32):
  588. # This will only work reliably for relatively small numbers.
  589. # Increase the value of max_length if you think you're going
  590. # to use long integers
  591. assert number < 2L << max_length
  592. shifts = map (operator.rshift, max_length * [number], \
  593. range (max_length - 1, -1, -1))
  594. digits = map (operator.mod, shifts, max_length * [2])
  595. if not digits.count (1): return 0
  596. digits = digits [digits.index (1):]
  597. return string.join (map (repr, digits), '')
  598. # constant profile defaults
  599. PyUtilProfileDefaultFilename = 'profiledata'
  600. PyUtilProfileDefaultLines = 80
  601. PyUtilProfileDefaultSorts = ['cumulative', 'time', 'calls']
  602. # call this from the prompt, and break back out to the prompt
  603. # to stop profiling
  604. #
  605. # OR to do inline profiling, you must make a globally-visible
  606. # function to be profiled, i.e. to profile 'self.load()', do
  607. # something like this:
  608. #
  609. # def func(self=self):
  610. # self.load()
  611. # import __builtin__
  612. # __builtin__.func = func
  613. # PythonUtil.startProfile(cmd='func()', filename='profileData')
  614. # del __builtin__.func
  615. #
  616. def startProfile(filename=PyUtilProfileDefaultFilename,
  617. lines=PyUtilProfileDefaultLines,
  618. sorts=PyUtilProfileDefaultSorts,
  619. silent=0,
  620. callInfo=1,
  621. cmd='run()'):
  622. import profile
  623. profile.run(cmd, filename)
  624. if not silent:
  625. printProfile(filename, lines, sorts, callInfo)
  626. # call this to see the results again
  627. def printProfile(filename=PyUtilProfileDefaultFilename,
  628. lines=PyUtilProfileDefaultLines,
  629. sorts=PyUtilProfileDefaultSorts,
  630. callInfo=1):
  631. import pstats
  632. s = pstats.Stats(filename)
  633. s.strip_dirs()
  634. for sort in sorts:
  635. s.sort_stats(sort)
  636. s.print_stats(lines)
  637. if callInfo:
  638. s.print_callees(lines)
  639. s.print_callers(lines)
  640. def getSetterName(valueName, prefix='set'):
  641. # getSetterName('color') -> 'setColor'
  642. # getSetterName('color', 'get') -> 'getColor'
  643. return '%s%s%s' % (prefix, string.upper(valueName[0]), valueName[1:])
  644. def getSetter(targetObj, valueName, prefix='set'):
  645. # getSetter(smiley, 'pos') -> smiley.setPos
  646. return getattr(targetObj, getSetterName(valueName, prefix))
  647. class Functor:
  648. def __init__(self, function, *args, **kargs):
  649. assert callable(function), "function should be a callable obj"
  650. self._function = function
  651. self._args = args
  652. self._kargs = kargs
  653. self.__name__ = 'Functor: %s' % self._function.__name__
  654. self.__doc__ = self._function.__doc__
  655. def __call__(self, *args, **kargs):
  656. """call function"""
  657. _args = list(self._args)
  658. _args.extend(args)
  659. _kargs = self._kargs.copy()
  660. _kargs.update(kargs)
  661. return apply(self._function,_args,_kargs)
  662. class ParamSet:
  663. # abstract base class for container of parameter values for a ParamObj
  664. # (see below)
  665. # specifies default values for every parameter
  666. # dict of params and their default values
  667. # derived classes should define their own additional params and default
  668. # values in the same way
  669. Params = {
  670. # base class does not define any parameters, but they would appear as
  671. # 'name': value,
  672. }
  673. def __init__(self, *args, **kwArgs):
  674. ParamSet._compileDefaultParams()
  675. if len(args) == 1 and len(kwArgs) == 0:
  676. # extract our params from an existing ParamObj instance
  677. obj = args[0]
  678. self.paramVals = {}
  679. for param in self.getParams():
  680. self.paramVals[param] = getSetter(obj, param, 'get')()
  681. else:
  682. assert len(args) == 0
  683. if __debug__:
  684. for arg in kwArgs.keys():
  685. assert arg in self.getParams()
  686. self.paramVals = dict(kwArgs)
  687. def getValue(self, param):
  688. if param in self.paramVals:
  689. return self.paramVals[param]
  690. return self._Params[param]
  691. def applyTo(self, obj):
  692. # Apply our entire set of params to a ParamObj
  693. obj.lockParams()
  694. for param in self.getParams():
  695. getSetter(obj, param)(self.getValue(param))
  696. obj.unlockParams()
  697. # CLASS METHODS
  698. def getParams(cls):
  699. # returns safely-mutable list of param names
  700. cls._compileDefaultParams()
  701. return cls._Params.keys()
  702. getParams = classmethod(getParams)
  703. def getDefaultValue(cls, param):
  704. cls._compileDefaultParams()
  705. return cls._Params[param]
  706. getDefaultValue = classmethod(getDefaultValue)
  707. def _compileDefaultParams(cls):
  708. if cls.__dict__.has_key('_Params'):
  709. # we've already compiled the defaults for this class
  710. return
  711. bases = list(cls.__bases__)
  712. # bring less-derived classes to the front
  713. mostDerivedLast(bases)
  714. cls._Params = {}
  715. for c in (bases + [cls]):
  716. # make sure this base has its dict of param defaults
  717. c._compileDefaultParams()
  718. if c.__dict__.has_key('Params'):
  719. # apply this class' default param values to our dict
  720. cls._Params.update(c.Params)
  721. _compileDefaultParams = classmethod(_compileDefaultParams)
  722. class ParamObj:
  723. # abstract base for classes that want to support a formal parameter
  724. # set whose values may be queried, changed, 'bulk' changed, and
  725. # extracted/stored/applied all at once (see ParamSet above)
  726. # for each param, ParamObj must define getter, setter, and applyer
  727. # for each parameter
  728. # (replace 'Param' with the name of the parameter):
  729. #
  730. # getParam() returns current value,
  731. # setParam(value) sets current value,
  732. # applyParam() (OPTIONAL) tells object to react to newly-set value
  733. # inside applyParam, previous value of param is avaliable
  734. # as self.getPriorValue()
  735. # to do a bulk change:
  736. # obj.lockParams()
  737. # obj.setX('foo')
  738. # obj.setY(34)
  739. # ...
  740. # obj.unlockParams()
  741. # derived class must override this to be the appropriate ParamSet subclass
  742. ParamClass = ParamSet
  743. def __init__(self):
  744. self._paramLockRefCount = 0
  745. def setterStub(param, value, self=self):
  746. # should we apply the value now or should we wait?
  747. # if this obj's params are locked, we track which values have
  748. # been set, and on unlock, we'll call the applyers for those
  749. # values
  750. if self._paramLockRefCount > 0:
  751. # set the new value; make sure we're not calling ourselves
  752. # recursively
  753. getSetter(self.__class__, param)(self, value)
  754. if param not in self._priorValues:
  755. try:
  756. priorValue = getSetter(self, param, 'get')()
  757. except:
  758. priorValue = None
  759. self._priorValues[param] = priorValue
  760. self._paramsSet[param] = None
  761. else:
  762. # prepare for call to getPriorValue
  763. self._oneShotPriorVal = getSetter(self, param, 'get')()
  764. # set the new value; make sure we're not calling ourselves
  765. # recursively
  766. getSetter(self.__class__, param)(self, value)
  767. # call the applier, if there is one
  768. applier = getattr(self, getSetterName(param, 'apply'), None)
  769. if applier is not None:
  770. applier()
  771. del self._oneShotPriorVal
  772. # insert stub funcs for param setters
  773. for param in self.ParamClass.getParams():
  774. # if the setter is a direct member of self, move the setter
  775. # aside
  776. setterName = getSetterName(param)
  777. if setterName in self.__dict__:
  778. self.__dict__[setterName + '_MOVED'] = self.__dict__[setterName]
  779. # and replace it with a stub that will a) call the setter and
  780. # then the applier, or b) call the setter and queue the applier,
  781. # depending on whether our params are locked
  782. self.__dict__[setterName] = Functor(setterStub, param)
  783. def setDefaultParams(self):
  784. # set all the default parameters on ourself
  785. self.ParamClass().applyTo(self)
  786. def lockParams(self):
  787. self._paramLockRefCount += 1
  788. if self._paramLockRefCount == 1:
  789. self._handleLockParams()
  790. def unlockParams(self):
  791. if self._paramLockRefCount > 0:
  792. self._paramLockRefCount -= 1
  793. if self._paramLockRefCount == 0:
  794. self._handleUnlockParams()
  795. def _handleLockParams(self):
  796. # this will store the names of the parameters that are modified
  797. self._paramsSet = {}
  798. # this will store the values of modified params (from prior to
  799. # the lock).
  800. self._priorValues = {}
  801. def _handleUnlockParams(self):
  802. self.__curParam = None
  803. for param in self._paramsSet:
  804. # call the applier, if there is one
  805. applier = getattr(self, getSetterName(param, 'apply'), None)
  806. if applier is not None:
  807. self.__curParam = param
  808. applier()
  809. del self.__curParam
  810. del self._priorValues
  811. del self._paramsSet
  812. def paramsLocked(self):
  813. return self._paramLockRefCount > 0
  814. def getPriorValue(self):
  815. # call this within an apply function to find out what the prior value
  816. # of a param was before the set call(s) corresponding to the call
  817. # to apply
  818. if hasattr(self, '_oneShotPriorVal'):
  819. return self._oneShotPriorVal
  820. return self._priorValues[self.__curParam]
  821. def bound(value, bound1, bound2):
  822. """
  823. returns value if value is between bound1 and bound2
  824. otherwise returns bound that is closer to value
  825. """
  826. if bound1 > bound2:
  827. return min(max(value, bound2), bound1)
  828. else:
  829. return min(max(value, bound1), bound2)
  830. def lerp(v0, v1, t):
  831. """
  832. returns a value lerped between v0 and v1, according to t
  833. t == 0 maps to v0, t == 1 maps to v1
  834. """
  835. return v0 + (t * (v1 - v0))
  836. def average(*args):
  837. """ returns simple average of list of values """
  838. val = 0.
  839. for arg in args:
  840. val += arg
  841. return val / len(args)
  842. def addListsByValue(a, b):
  843. """
  844. returns a new array containing the sums of the two array arguments
  845. (c[0] = a[0 + b[0], etc.)
  846. """
  847. c = []
  848. for x, y in zip(a, b):
  849. c.append(x + y)
  850. return c
  851. def boolEqual(a, b):
  852. """
  853. returns true if a and b are both true or both false.
  854. returns false otherwise
  855. (a.k.a. xnor -- eXclusive Not OR).
  856. """
  857. return (a and b) or not (a or b)
  858. def lineupPos(i, num, spacing):
  859. """
  860. use to line up a series of 'num' objects, in one dimension,
  861. centered around zero
  862. 'i' is the index of the object in the lineup
  863. 'spacing' is the amount of space between objects in the lineup
  864. """
  865. assert num >= 1
  866. assert i >= 0 and i < num
  867. pos = float(i) * spacing
  868. return pos - ((float(spacing) * (num-1))/2.)
  869. def formatElapsedSeconds(seconds):
  870. """
  871. Returns a string of the form "mm:ss" or "hh:mm:ss" or "n days",
  872. representing the indicated elapsed time in seconds.
  873. """
  874. sign = ''
  875. if seconds < 0:
  876. seconds = -seconds
  877. sign = '-'
  878. # We use math.floor() instead of casting to an int, so we avoid
  879. # problems with numbers that are too large to represent as
  880. # type int.
  881. seconds = math.floor(seconds)
  882. hours = math.floor(seconds / (60 * 60))
  883. if hours > 36:
  884. days = math.floor((hours + 12) / 24)
  885. return "%s%d days" % (sign, days)
  886. seconds -= hours * (60 * 60)
  887. minutes = (int)(seconds / 60)
  888. seconds -= minutes * 60
  889. if hours != 0:
  890. return "%s%d:%02d:%02d" % (sign, hours, minutes, seconds)
  891. else:
  892. return "%s%d:%02d" % (sign, minutes, seconds)
  893. def solveQuadratic(a, b, c):
  894. # quadratic equation: ax^2 + bx + c = 0
  895. # quadratic formula: x = [-b +/- sqrt(b^2 - 4ac)] / 2a
  896. # returns None, root, or [root1, root2]
  897. # a cannot be zero.
  898. if a == 0.:
  899. return None
  900. # calculate the determinant (b^2 - 4ac)
  901. D = (b * b) - (4. * a * c)
  902. if D < 0:
  903. # there are no solutions (sqrt(negative number) is undefined)
  904. return None
  905. elif D == 0:
  906. # only one root
  907. return (-b) / (2. * a)
  908. else:
  909. # OK, there are two roots
  910. sqrtD = math.sqrt(D)
  911. twoA = 2. * a
  912. root1 = ((-b) - sqrtD) / twoA
  913. root2 = ((-b) + sqrtD) / twoA
  914. return [root1, root2]
  915. def stackEntryInfo(depth=0, baseFileName=1):
  916. """
  917. returns the sourcefilename, line number, and function name of
  918. an entry in the stack.
  919. 'depth' is how far back to go in the stack; 0 is the caller of this
  920. function, 1 is the function that called the caller of this function, etc.
  921. by default, strips off the path of the filename; override with baseFileName
  922. returns (fileName, lineNum, funcName) --> (string, int, string)
  923. returns (None, None, None) on error
  924. """
  925. try:
  926. stack = None
  927. frame = None
  928. try:
  929. stack = inspect.stack()
  930. # add one to skip the frame associated with this function
  931. frame = stack[depth+1]
  932. filename = frame[1]
  933. if baseFileName:
  934. filename = os.path.basename(filename)
  935. lineNum = frame[2]
  936. funcName = frame[3]
  937. result = (filename, lineNum, funcName)
  938. finally:
  939. del stack
  940. del frame
  941. except:
  942. result = (None, None, None)
  943. return result
  944. def lineInfo(baseFileName=1):
  945. """
  946. returns the sourcefilename, line number, and function name of the
  947. code that called this function
  948. (answers the question: 'hey lineInfo, where am I in the codebase?')
  949. see stackEntryInfo, above, for info on 'baseFileName' and return types
  950. """
  951. return stackEntryInfo(1)
  952. def callerInfo(baseFileName=1):
  953. """
  954. returns the sourcefilename, line number, and function name of the
  955. caller of the function that called this function
  956. (answers the question: 'hey callerInfo, who called me?')
  957. see stackEntryInfo, above, for info on 'baseFileName' and return types
  958. """
  959. return stackEntryInfo(2)
  960. def lineTag(baseFileName=1, verbose=0, separator=':'):
  961. """
  962. returns a string containing the sourcefilename and line number
  963. of the code that called this function
  964. (equivalent to lineInfo, above, with different return type)
  965. see stackEntryInfo, above, for info on 'baseFileName'
  966. if 'verbose' is false, returns a compact string of the form
  967. 'fileName:lineNum:funcName'
  968. if 'verbose' is true, returns a longer string that matches the
  969. format of Python stack trace dumps
  970. returns empty string on error
  971. """
  972. fileName, lineNum, funcName = callerInfo()
  973. if fileName is None:
  974. return ''
  975. if verbose:
  976. return 'File "%s", line %s, in %s' % (fileName, lineNum, funcName)
  977. else:
  978. return '%s%s%s%s%s' % (fileName, separator, lineNum, separator,
  979. funcName)
  980. def findPythonModule(module):
  981. # Look along the python load path for the indicated filename.
  982. # Returns the located pathname, or None if the filename is not
  983. # found.
  984. filename = module + '.py'
  985. for dir in sys.path:
  986. pathname = os.path.join(dir, filename)
  987. if os.path.exists(pathname):
  988. return pathname
  989. return None
  990. def describeException(backTrace = 4):
  991. # When called in an exception handler, returns a string describing
  992. # the current exception.
  993. def byteOffsetToLineno(code, byte):
  994. # Returns the source line number corresponding to the given byte
  995. # offset into the indicated Python code module.
  996. import array
  997. lnotab = array.array('B', code.co_lnotab)
  998. line = code.co_firstlineno
  999. for i in range(0, len(lnotab),2):
  1000. byte -= lnotab[i]
  1001. if byte <= 0:
  1002. return line
  1003. line += lnotab[i+1]
  1004. return line
  1005. infoArr = sys.exc_info()
  1006. exception = infoArr[0]
  1007. exceptionName = getattr(exception, '__name__', None)
  1008. extraInfo = infoArr[1]
  1009. trace = infoArr[2]
  1010. stack = []
  1011. while trace.tb_next:
  1012. # We need to call byteOffsetToLineno to determine the true
  1013. # line number at which the exception occurred, even though we
  1014. # have both trace.tb_lineno and frame.f_lineno, which return
  1015. # the correct line number only in non-optimized mode.
  1016. frame = trace.tb_frame
  1017. module = frame.f_globals.get('__name__', None)
  1018. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1019. stack.append("%s:%s, " % (module, lineno))
  1020. trace = trace.tb_next
  1021. frame = trace.tb_frame
  1022. module = frame.f_globals.get('__name__', None)
  1023. lineno = byteOffsetToLineno(frame.f_code, frame.f_lasti)
  1024. stack.append("%s:%s, " % (module, lineno))
  1025. description = ""
  1026. for i in range(len(stack) - 1, max(len(stack) - backTrace, 0) - 1, -1):
  1027. description += stack[i]
  1028. description += "%s: %s" % (exceptionName, extraInfo)
  1029. return description
  1030. def mostDerivedLast(classList):
  1031. """pass in list of classes. sorts list in-place, with derived classes
  1032. appearing after their bases"""
  1033. def compare(a,b):
  1034. if issubclass(a,b):
  1035. result=1
  1036. elif issubclass(b,a):
  1037. result=-1
  1038. else:
  1039. result=0
  1040. #print a,b,result
  1041. return result
  1042. classList.sort(compare)
  1043. def clampScalar(value, a, b):
  1044. # calling this ought to be faster than calling both min and max
  1045. if a < b:
  1046. if value < a:
  1047. return a
  1048. elif value > b:
  1049. return b
  1050. else:
  1051. return value
  1052. else:
  1053. if value < b:
  1054. return b
  1055. elif value > a:
  1056. return a
  1057. else:
  1058. return value
  1059. def weightedChoice(choiceList, rng=random.random, sum=None):
  1060. """given a list of (weight,item) pairs, chooses an item based on the
  1061. weights. rng must return 0..1. if you happen to have the sum of the
  1062. weights, pass it in 'sum'."""
  1063. # TODO: add support for dicts
  1064. if sum is None:
  1065. sum = 0.
  1066. for weight, item in choiceList:
  1067. sum += weight
  1068. rand = rng()
  1069. accum = rand * sum
  1070. for weight, item in choiceList:
  1071. accum -= weight
  1072. if accum <= 0.:
  1073. return item
  1074. # rand is ~1., and floating-point error prevented accum from hitting 0.
  1075. # Or you passed in a 'sum' that was was too large.
  1076. # Return the last item.
  1077. return item
  1078. def randFloat(a, b=0., rng=random.random):
  1079. """returns a random float in [a,b]
  1080. call with single argument to generate random float between arg and zero
  1081. """
  1082. return lerp(a,b,rng())
  1083. def normalDistrib(a, b, gauss=random.gauss):
  1084. """
  1085. NOTE: assumes a < b
  1086. Returns random number between a and b, using gaussian distribution, with
  1087. mean=avg(a,b), and a standard deviation that fits ~99.7% of the curve
  1088. between a and b. Outlying results are clipped to a and b.
  1089. ------------------------------------------------------------------------
  1090. http://www-stat.stanford.edu/~naras/jsm/NormalDensity/NormalDensity.html
  1091. The 68-95-99.7% Rule
  1092. ====================
  1093. All normal density curves satisfy the following property which is often
  1094. referred to as the Empirical Rule:
  1095. 68% of the observations fall within 1 standard deviation of the mean.
  1096. 95% of the observations fall within 2 standard deviations of the mean.
  1097. 99.7% of the observations fall within 3 standard deviations of the mean.
  1098. Thus, for a normal distribution, almost all values lie within 3 standard
  1099. deviations of the mean.
  1100. ------------------------------------------------------------------------
  1101. In calculating our standard deviation, we divide (b-a) by 6, since the
  1102. 99.7% figure includes 3 standard deviations _on_either_side_ of the mean.
  1103. """
  1104. return max(a, min(b, gauss((a+b)*.5, (b-a)/6.)))
  1105. def weightedRand(valDict, rng=random.random):
  1106. """
  1107. pass in a dictionary with a selection -> weight mapping. Eg.
  1108. {"Choice 1" : 10,
  1109. "Choice 2" : 30,
  1110. "bear" : 100}
  1111. -Weights need not add up to any particular value.
  1112. -The actual selection will be returned.
  1113. """
  1114. selections = valDict.keys()
  1115. weights = valDict.values()
  1116. totalWeight = 0
  1117. for weight in weights:
  1118. totalWeight += weight
  1119. # get a random value between 0 and the total of the weights
  1120. randomWeight = rng() * totalWeight
  1121. # find the index that corresponds with this weight
  1122. for i in range(len(weights)):
  1123. totalWeight -= weights[i]
  1124. if totalWeight <= randomWeight:
  1125. return selections[i]
  1126. assert(True, "Should never get here")
  1127. return selections[-1]
  1128. def randUint31(rng=random.random):
  1129. """returns a random integer in [0..2^31).
  1130. rng must return float in [0..1]"""
  1131. return int(rng() * 0x7FFFFFFF)
  1132. def randInt32(rng=random.random):
  1133. """returns a random integer in [-2147483648..2147483647].
  1134. rng must return float in [0..1]
  1135. """
  1136. i = int(rng() * 0x7FFFFFFF)
  1137. if rng() < .5:
  1138. i *= -1
  1139. return i
  1140. class Enum:
  1141. """Pass in list of strings or string of comma-separated strings.
  1142. Items are accessible as instance.item, and are assigned unique,
  1143. increasing integer values. Pass in integer for 'start' to override
  1144. starting value.
  1145. Example:
  1146. >>> colors = Enum('red, green, blue')
  1147. >>> colors.red
  1148. 0
  1149. >>> colors.green
  1150. 1
  1151. >>> colors.blue
  1152. 2
  1153. >>> colors.getString(colors.red)
  1154. 'red'
  1155. """
  1156. if __debug__:
  1157. # chars that cannot appear within an item string.
  1158. InvalidChars = string.whitespace
  1159. def _checkValidIdentifier(item):
  1160. invalidChars = string.whitespace+string.punctuation
  1161. invalidChars = invalidChars.replace('_','')
  1162. invalidFirstChars = invalidChars+string.digits
  1163. if item[0] in invalidFirstChars:
  1164. raise SyntaxError, ("Enum '%s' contains invalid first char" %
  1165. item)
  1166. if not disjoint(item, invalidChars):
  1167. for char in item:
  1168. if char in invalidChars:
  1169. raise SyntaxError, (
  1170. "Enum\n'%s'\ncontains illegal char '%s'" %
  1171. (item, char))
  1172. return 1
  1173. _checkValidIdentifier = staticmethod(_checkValidIdentifier)
  1174. def __init__(self, items, start=0):
  1175. if type(items) == types.StringType:
  1176. items = items.split(',')
  1177. self._stringTable = {}
  1178. # make sure we don't overwrite an existing element of the class
  1179. assert(self._checkExistingMembers(items))
  1180. assert(uniqueElements(items))
  1181. i = start
  1182. for item in items:
  1183. # remove leading/trailing whitespace
  1184. item = string.strip(item)
  1185. # is there anything left?
  1186. if len(item) == 0:
  1187. continue
  1188. # make sure there are no invalid characters
  1189. assert(Enum._checkValidIdentifier(item))
  1190. self.__dict__[item] = i
  1191. self._stringTable[i] = item
  1192. i += 1
  1193. def getString(self, value):
  1194. return self._stringTable[value]
  1195. def __contains__(self, value):
  1196. return value in self._stringTable
  1197. def __len__(self):
  1198. return len(self._stringTable)
  1199. if __debug__:
  1200. def _checkExistingMembers(self, items):
  1201. for item in items:
  1202. if hasattr(self, item):
  1203. return 0
  1204. return 1
  1205. ############################################################
  1206. # class: Singleton
  1207. # Purpose: This provides a base metaclass for all classes
  1208. # that require one and only one instance.
  1209. #
  1210. # Example: class mySingleton:
  1211. # __metaclass__ = PythonUtil.Singleton
  1212. # def __init__(self,...):
  1213. # ...
  1214. #
  1215. # Note: This class is based on Python's New-Style Class
  1216. # design. An error will occur if a defined class
  1217. # attemps to inherit from a Classic-Style Class only,
  1218. # ie: class myClassX:
  1219. # def __init__(self, ...):
  1220. # ...
  1221. #
  1222. # class myNewClassX(myClassX):
  1223. # __metaclass__ = PythonUtil.Singleton
  1224. # def __init__(self, ...):
  1225. # myClassX.__init__(self, ...)
  1226. # ...
  1227. #
  1228. # This causes problems because myNewClassX is a
  1229. # New-Style class that inherits from only a
  1230. # Classic-Style base class. There are two ways
  1231. # simple ways to resolve this issue.
  1232. #
  1233. # First, if possible, make myClassX a
  1234. # New-Style class by inheriting from object
  1235. # object. IE: class myClassX(object):
  1236. #
  1237. # If for some reason that is not an option, make
  1238. # myNewClassX inherit from object and myClassX.
  1239. # IE: class myNewClassX(object, myClassX):
  1240. ############################################################
  1241. class Singleton(type):
  1242. def __init__(cls,name,bases,dic):
  1243. super(Singleton,cls).__init__(name,bases,dic)
  1244. cls.instance=None
  1245. def __call__(cls,*args,**kw):
  1246. if cls.instance is None:
  1247. cls.instance=super(Singleton,cls).__call__(*args,**kw)
  1248. return cls.instance
  1249. class SingletonError(ValueError):
  1250. """ Used to indicate an inappropriate value for a Singleton."""