<p>此实现解决了我的问题:</p>
<pre><code>import threading
_INDENT = ' '
_threadlocal = threading.local()
_defaults = dict(depth=0, prefix='')
class ThreadLocal:
_initialized = False # This allows us to set / get attributes during __init__
def __init__(self, thread_data, defaults=None):
self._thread_data = thread_data
self._defaults = defaults or {}
self._initialized = True
def __setattr__(self, key, value):
if self._initialized:
setattr(self._thread_data, key, value)
else:
# Allow setting attributes in __init__
self.__dict__[key] = value
def __getattr__(self, item):
if self._initialized:
return getattr(self._thread_data, item, _defaults.get(item))
else:
# Allow getting attributes in __init__
return self.__dict__[item]
threadlocal = ThreadLocal(_threadlocal, _defaults)
def _increase_depth():
threadlocal.depth += 1
threadlocal.prefix = _INDENT * threadlocal.depth
def _decrease_depth():
threadlocal.depth -= 1
threadlocal.prefix = _INDENT * threadlocal.depth
</code></pre>