from direct.showbase.PythonUtil import AlphabetCounter, Averager, Default, DelayedCall, DelayedFunctor, FrameDelayedCall, Functor, GoldenRectangle, HierarchyException, MiniLog, MiniLogSentry, PStatScope, PriorityCallbacks, Queue, ScratchPad, SerialMaskedGen, SerialNumGen, Singleton, SingletonError, Stack, StackTrace, StdoutCapture, StdoutPassthrough, SubframeCall, Sync, addListsByValue, adjust, appendStr, average, boolEqual, bound, callerInfo, clampScalar, closestDestAngle, closestDestAngle2, configIsToday, contains, convertTree, deeptype, difference, disjoint, doc, endSuperLog, exceptionLogged, extractProfile, fastRepr, findPythonModule, fitDestAngle2Src, fitSrcAngle2Dest, flywheel, formatElapsedSeconds, formatTimeCompact, formatTimeExact, getAnnounceGenerateTime, getBase, getNumberedTypedSortedString, getNumberedTypedString, getProfileResultString, getRepository, getSetter, getSetterName, getShortestRotation, getTotalAnnounceTime, histogramDict, indent, intersection, invertDict, invertDictLossless, isDefaultValue, itype, lerp, lineInfo, lineTag, lineupPos, list2dict, listToIndex2item, listToItem2index, logBlock, loopGen, makeFlywheelGen, makeList, makeTuple, mostDerivedLast, normalDistrib, nullGen, pretty_print, printListEnum, printListEnumGen, printNumberedTyped, printNumberedTypes, printNumberedTypesGen, printProfile, printReverseStack, printStack, printThisCall, printVerboseStack, profileFunc, profiled, pstatcollect, quickProfile, r_convertTree, r_pretty_print, randFloat, randInt32, randUint31, reduceAngle, replace, report, safeRepr, safeReprTypeOnFail, safeTypeName, sameElements, serialNum, solveQuadratic, stackEntryInfo, startProfile, startSuperLog, traceFunctionCall, traceParentCall, typeName, unescapeHtmlString, union, uniqueElements, uniqueName, weightedChoice, weightedRand

Contains miscellaneous utility functions and classes.

Inheritance diagram

Inheritance diagram of direct.showbase.PythonUtil

class AlphabetCounter[source]

Bases: object

class Averager(name)[source]

Bases: object

__init__(self, name)[source]
addValue(self, value)[source]
class Default[source]

Bases: object

class DelayedCall(func, name=None, delay=None)[source]

Bases: object

calls a func after a specified delay

__init__(self, func, name=None, delay=None)[source]
class DelayedFunctor(functor, name=None, delay=None)[source]

Bases: object

Waits for this object to be called, then calls supplied functor after a delay. Effectively inserts a time delay between the caller and the functor.

__init__(self, functor, name=None, delay=None)[source]
class FrameDelayedCall(name, callback, frames=None, cancelFunc=None)[source]

Bases: object

calls a func after N frames

__init__(self, name, callback, frames=None, cancelFunc=None)[source]
class Functor(function, *args, **kargs)[source]

Bases: object

__init__(self, function, *args, **kargs)[source]
class GoldenRectangle[source]

Bases: object

class HierarchyException(owner, description)[source]

Bases: Exception

__init__(self, owner, description)[source]
class MiniLog(name)[source]

Bases: object

__init__(self, name)[source]
appendFunctionCall(self, line)[source]
appendLine(self, line)[source]
enterFunction(self, funcName, *args, **kw)[source]
class MiniLogSentry(log, funcName, *args, **kw)[source]

Bases: object

__init__(self, log, funcName, *args, **kw)[source]
class PStatScope(level=None)[source]

Bases: object

__init__(self, level=None)[source]
collectors = {}
copy(self, push=None)[source]
push(self, level)[source]
start(self, push=None)[source]
stop(self, pop=False)[source]
class PriorityCallbacks[source]

Bases: object

manage a set of prioritized callbacks, and allow them to be invoked in order of priority

add(self, callback, priority=None)[source]
remove(self, item)[source]
class Queue[source]

Bases: object

push(self, item)[source]
class ScratchPad(**kArgs)[source]

Bases: object

empty class to stick values onto

__init__(self, **kArgs)[source]
add(self, **kArgs)[source]
get(self, itemName, default=None)[source]
class SerialMaskedGen(mask, start=None)[source]

Bases: SerialNumGen

__init__(self, mask, start=None)[source]
class SerialNumGen(start=None)[source]

Bases: object

generates serial numbers

__init__(self, start=None)[source]
class Singleton(name, bases, dic)[source]

Bases: type

__init__(cls, name, bases, dic)[source]
class SingletonError[source]

Bases: ValueError

Used to indicate an inappropriate value for a Singleton.

class Stack[source]

Bases: object

push(self, item)[source]
class StackTrace(label='', start=0, limit=None)[source]

Bases: object

__init__(self, label='', start=0, limit=None)[source]

label is a string (or anything that be be a string) that is printed as part of the trace back. This is just to make it easier to tell what the stack trace is referring to. start is an integer number of stack frames back from the most recent. (This is automatically bumped up by one to skip the __init__ call to the StackTrace). limit is an integer number of stack frames to record (or None for unlimited).

class StdoutCapture[source]

Bases: object

write(self, string)[source]
class StdoutPassthrough[source]

Bases: StdoutCapture

write(self, string)[source]
class SubframeCall(functor, taskPriority, name=None)[source]

Bases: object

Calls a callback at a specific time during the frame using the task system

__init__(self, functor, taskPriority, name=None)[source]
class Sync(name, other=None)[source]

Bases: object

__init__(self, name, other=None)[source]
isSynced(self, other)[source]
sync(self, other)[source]
addListsByValue(a, b)[source]

returns a new array containing the sums of the two array arguments (c[0] = a[0 + b[0], etc.)

adjust(command=None, parent=None, **kw)[source]

Popup and entry scale to adjust a parameter

Accepts any Slider keyword argument. Typical arguments include: command: The one argument command to execute min: The min value of the slider max: The max value of the slider resolution: The resolution of the slider text: The label on the slider

These values can be accessed and/or changed after the fact >>> vg = adjust() >>> vg[‘min’] 0.0 >>> vg[‘min’] = 10.0 >>> vg[‘min’] 10.0

appendStr(obj, st)[source]

adds a string onto the __str__ output of an instance


returns simple average of list of values

boolEqual(a, b)[source]

returns true if a and b are both true or both false. returns false otherwise (a.k.a. xnor – eXclusive Not OR).

bound(value, bound1, bound2)[source]

returns value if value is between bound1 and bound2 otherwise returns bound that is closer to value

callerInfo(baseFileName=1, howFarBack=0)[source]

returns the sourcefilename, line number, and function name of the caller of the function that called this function (answers the question: ‘hey callerInfo, who called me?’) see stackEntryInfo, above, for info on ‘baseFileName’ and return types

clampScalar(value, a, b)[source]
closestDestAngle(src, dest)[source]
closestDestAngle2(src, dest)[source]
contains(whole, sub)[source]

Return 1 if whole contains sub, 0 otherwise

convertTree(objTree, idList)[source]
deeptype(obj, maxLen=100, _visitedIds=None)[source]
difference(a, b)[source]

difference(list, list):

disjoint(L1, L2)[source]

returns non-zero if L1 and L2 have no common elements


decorator that outputs the function name and all arguments if an exception passes back through the stack frame if append is true, string is appended to the __str__ output of the exception. if append is false, string is printed to the log directly. If the output will take up many lines, it’s recommended to set append to False so that the exception stack is not hidden by the output of this decorator.

extractProfile(*args, **kArgs)[source]
fastRepr(obj, maxLen=200, strFactor=10, _visitedIds=None)[source]

caps the length of iterable types, so very large objects will print faster. also prevents infinite recursion

fitDestAngle2Src(src, dest)[source]

given a src and destination angle, returns an equivalent dest angle that is within [-180..180) of src examples: fitDestAngle2Src(30, 60) == 60 fitDestAngle2Src(60, 30) == 30 fitDestAngle2Src(0, 180) == -180 fitDestAngle2Src(1, 180) == 180

fitSrcAngle2Dest(src, dest)[source]

given a src and destination angle, returns an equivalent src angle that is within [-180..180) of dest examples: fitSrcAngle2Dest(30, 60) == 30 fitSrcAngle2Dest(60, 30) == 60 fitSrcAngle2Dest(0, 180) == 0 fitSrcAngle2Dest(-1, 180) == 359 fitSrcAngle2Dest(-180, 180) == 180

flywheel(*args, **kArgs)[source]
>>> for i in flywheel([1,2,3], countList=[10, 5, 1]):
...   print i,
1 2 3 1 2 1 2 1 2 1 2 1 1 1 1 1

Returns a string of the form “mm:ss” or “hh:mm:ss” or “n days”, representing the indicated elapsed time in seconds.

getNumberedTypedSortedString(items, maxLen=5000, numPrefix='')[source]

get a string that has each item of the list on its own line, the items are stringwise-sorted, and each item is numbered on the left from zero

getNumberedTypedString(items, maxLen=5000, numPrefix='')[source]

get a string that has each item of the list on its own line, and each item is numbered on the left from zero

getSetter(targetObj, valueName, prefix='set')[source]
getSetterName(valueName, prefix='set')[source]
getShortestRotation(start, end)[source]

Given two heading values, return a tuple describing the shortest interval from ‘start’ to ‘end’. This tuple can be used to lerp a camera between two rotations while avoiding the ‘spin’ problem.

indent(stream, numIndents, str)[source]

Write str to stream with numIndents in front of it

intersection(a, b)[source]

intersection(list, list):

invertDict(D, lossy=False)[source]

creates a dictionary by ‘inverting’ D; keys are placed in the new dictionary under their corresponding value in the old dictionary. It is an error if D contains any duplicate values.

>>> old = {'key1':1, 'key2':2}
>>> invertDict(old)
{1: 'key1', 2: 'key2'}

similar to invertDict, but values of new dict are lists of keys from old dict. No information is lost.

>>> old = {'key1':1, 'key2':2, 'keyA':2}
>>> invertDictLossless(old)
{1: ['key1'], 2: ['key2', 'keyA']}
lerp(v0, v1, t)[source]

returns a value lerped between v0 and v1, according to t t == 0 maps to v0, t == 1 maps to v1


returns the sourcefilename, line number, and function name of the code that called this function (answers the question: ‘hey lineInfo, where am I in the codebase?’) see stackEntryInfo, above, for info on ‘baseFileName’ and return types

lineTag(baseFileName=1, verbose=0, separator=':')[source]

returns a string containing the sourcefilename and line number of the code that called this function (equivalent to lineInfo, above, with different return type) see stackEntryInfo, above, for info on ‘baseFileName’

if ‘verbose’ is false, returns a compact string of the form ‘fileName:lineNum:funcName’ if ‘verbose’ is true, returns a longer string that matches the format of Python stack trace dumps

returns empty string on error

lineupPos(i, num, spacing)[source]

use to line up a series of ‘num’ objects, in one dimension, centered around zero ‘i’ is the index of the object in the lineup ‘spacing’ is the amount of space between objects in the lineup

list2dict(L, value=None)[source]

creates dict using elements of list, all assigned to same value


converts list to dict of list index->list item


converts list to dict of list item->list index This is lossy if there are duplicate list items

logBlock(id, msg)[source]
makeFlywheelGen(objects, countList=None, countFunc=None, scale=None)[source]

returns x, converted to a list


returns x, converted to a tuple


pass in list of classes. sorts list in-place, with derived classes appearing after their bases

normalDistrib(a, b, gauss=<bound method Random.gauss of <random.Random object>>)[source]

NOTE: assumes a < b

Returns random number between a and b, using gaussian distribution, with mean=avg(a, b), and a standard deviation that fits ~99.7% of the curve between a and b.

For ease of use, outlying results are re-computed until result is in [a, b] This should fit the remaining .3% of the curve that lies outside [a, b] uniformly onto the curve inside [a, b]

All normal density curves satisfy the following property which is often

referred to as the Empirical Rule:

68% of the observations fall within 1 standard deviation of the mean. 95% of the observations fall within 2 standard deviations of the mean. 99.7% of the observations fall within 3 standard deviations of the mean.

Thus, for a normal distribution, almost all values lie within 3 standard

deviations of the mean.

In calculating our standard deviation, we divide (b-a) by 6, since the 99.7% figure includes 3 standard deviations _on_either_side_ of the mean.

printNumberedTyped(items, maxLen=5000)[source]

print out each item of the list on its own line, with each item numbered on the left from zero

printNumberedTypes(items, maxLen=5000)[source]

print out the type of each item of the list on its own line, with each item numbered on the left from zero

printNumberedTypesGen(items, maxLen=5000)[source]
printProfile(filename='profiledata', lines=80, sorts=['cumulative', 'time', 'calls'], callInfo=1)[source]
profileFunc(callback, name, terse, log=True)[source]
profiled(category=None, terse=False)[source]

decorator for profiling functions turn categories on and off via “want-profile-categoryName 1”


def loadParticles():
want-profile-particles 1
pstatcollect(scope, level=None)[source]
r_convertTree(oldTree, newTree, idList)[source]
r_pretty_print(tree, num)[source]
randFloat(a, b=0.0, rng=<built-in method random of Random object>)[source]

returns a random float in [a, b] call with single argument to generate random float between arg and zero

randInt32(rng=<built-in method random of Random object>)[source]

returns a random integer in [-2147483648..2147483647]. rng must return float in [0..1]

randUint31(rng=<built-in method random of Random object>)[source]

returns a random integer in [0..2^31). rng must return float in [0..1]


Reduces an angle (in degrees) to a value in [-180..180)

replace(list, old, new, all=0)[source]

replace ‘old’ with ‘new’ in ‘list’ if all == 0, replace first occurrence otherwise replace all occurrences returns the number of items replaced

report(types=[], prefix='', xform=None, notifyFunc=None, dConfigParam=[])[source]

This is a decorator generating function. Use is similar to a @decorator, except you must be sure to call it as a function. It actually returns the decorator which is then used to transform your decorated function. Confusing at first, I know.

Decoration occurs at function definition time.

If __dev__ is not defined, or resolves to False, this function has no effect and no wrapping/transform occurs. So in production, it’s as if the report has been asserted out.

  • types

    A subset list of [‘timeStamp’, ‘frameCount’, ‘avLocation’] This allows you to specify certain useful bits of info:

    • module: Prints the module that this report statement can be found in.

    • args: Prints the arguments as they were passed to this function.

    • timeStamp: Adds the current frame time to the output.

    • deltaStamp: Adds the current AI synched frame time to the output

    • frameCount: Adds the current frame count to the output. Usually cleaner than the timeStamp output.

    • avLocation: Adds the localAvatar’s network location to the output. Useful for interest debugging.

    • interests: Prints the current interest state after the report.

    • stackTrace: Prints a stack trace after the report.

  • prefix – Optional string to prepend to output, just before the function. Allows for easy grepping and is useful when merging AI/Client reports into a single file.

  • xform – Optional callback that accepts a single parameter: argument 0 to the decorated function. (assumed to be ‘self’) It should return a value to be inserted into the report output string.

  • notifyFunc – A notify function such as info, debug, warning, etc. By default the report will be printed to stdout. This will allow you send the report to a designated ‘notify’ output.

  • dConfigParam – A list of Config.prc string variables. By default the report will always print. If you specify this param, it will only print if one of the specified config strings resolve to True.

sameElements(a, b)[source]
solveQuadratic(a, b, c)[source]
stackEntryInfo(depth=0, baseFileName=1)[source]

returns the sourcefilename, line number, and function name of an entry in the stack. ‘depth’ is how far back to go in the stack; 0 is the caller of this function, 1 is the function that called the caller of this function, etc. by default, strips off the path of the filename; override with baseFileName returns (fileName, lineNum, funcName) –> (string, int, string) returns (None, None, None) on error

startProfile(filename='profiledata', lines=80, sorts=['cumulative', 'time', 'calls'], silent=0, callInfo=1, useDisk=False, cmd='run()')[source]

return a string that shows the call frame with calling arguments. e.g. foo(x=234, y=135)

union(a, b)[source]

union(list, list):


are all elements of list unique?

weightedChoice(choiceList, rng=<built-in method random of Random object>, sum=None)[source]

given a list of (weight, item) pairs, chooses an item based on the weights. rng must return 0..1. if you happen to have the sum of the weights, pass it in ‘sum’.

weightedRand(valDict, rng=<built-in method random of Random object>)[source]

pass in a dictionary with a selection -> weight mapping. E.g.:

{"Choice 1": 10,
 "Choice 2": 30,
 "bear":     100}
  • Weights need not add up to any particular value.

  • The actual selection will be returned.