利用werkzeug實現執行緒隔離的全域性變數
阿新 • • 發佈:2021-12-19
1. 需求
編碼過程中,當函式的呼叫層級很深時,如果從上層一級級把引數傳遞進去,往往顯得繁瑣而且醜陋,所以希望換種方式
2. 目錄結構
$ ls
local_var.py test.py
3. 程式碼
# local_var.py from werkzeug import Local _local = Local() class _Local: def __init__(self, key, value): self._local = _local self._key = key self._value = value def __enter__(self): setattr(self._local, self._key, self._value) def __exit__(self, *args): delattr(self._local, self._key) def get_var(name): return getattr(_local, name, None) def exec_with_var(name, value, func, *args, **kwargs): with _Local(name, value): return func(*args, **kwargs)
# test.py
import local_var
def func():
value = local_var.get_var('test')
if value is None:
print(':bad:', value)
else:
print(':good:', value)
if __name__ == "__main__":
func()
local_var.exec_with_var('test', 'test-value', func)
func()
4. 測試
$ python test.py :bad: None :good: test-value :bad: None