<s> """<STR_LIT>""" <EOL> try : <EOL> from threading import local <EOL> except ImportError : <EOL> local = None <EOL> from twisted . python import threadable <EOL> defaultContextDict = { } <EOL> setDefault = defaultContextDict . __setitem__ <EOL> class ContextTracker : <EOL> def __init__ ( self ) : <EOL> self . contexts = [ defaultContextDict ] <EOL> def callWithContext ( self , ctx , func , * args , ** kw ) : <EOL> newContext = self . contexts [ - <NUM_LIT:1> ] . copy ( ) <EOL> newContext . update ( ctx ) <EOL> self . contexts . append ( newContext ) <EOL> try : <EOL> return func ( * args , ** kw ) <EOL> finally : <EOL> self . contexts . pop ( ) <EOL> def getContext ( self , key , default = None ) : <EOL> return self . contexts [ - <NUM_LIT:1> ] . get ( key , default ) <EOL> class _ThreadedContextTracker : <EOL> def __init__ ( self ) : <EOL> self . threadId = threadable . getThreadID <EOL> self . contextPerThread = { } <EOL> def currentContext ( self ) : <EOL> tkey = self . threadId ( ) <EOL> try : <EOL> return self . contextPerThread [ tkey ] <EOL> except KeyError : <EOL> ct = self . contextPerThread [ tkey ] = ContextTracker ( ) <EOL> return ct <EOL> def callWithContext ( self , ctx , func , * args , ** kw ) : <EOL> return self . currentContext ( ) . callWithContext ( ctx , func , * args , ** kw ) <EOL> def getContext ( self , key , default = None ) : <EOL> return self . currentContext ( ) . getContext ( key , default ) <EOL> class _TLSContextTracker ( _ThreadedContextTracker ) : <EOL> def __init__ ( self ) : <EOL> self . storage = local ( ) <EOL> def currentContext ( self ) : <EOL> try : <EOL> return self . storage . ct <EOL> except AttributeError : <EOL> ct = self . storage . ct = ContextTracker ( ) <EOL> return ct <EOL> if local is None : <EOL> ThreadedContextTracker = _ThreadedContextTracker <EOL> else : <EOL> ThreadedContextTracker = _TLSContextTracker <EOL> def installContextTracker ( ctr ) : <EOL> global theContextTracker <EOL> global call <EOL> global get <EOL> theContextTracker = ctr <EOL> call = theContextTracker . callWithContext <EOL> get = theContextTracker . getContext <EOL> installContextTracker ( ThreadedContextTracker ( ) ) </s>
