pytorch
1
2
3
4import contextlib
5import copy
6import threading
7
8_threadlocal_scope = threading.local()
9
10
11@contextlib.contextmanager
12def arg_scope(single_helper_or_list, **kwargs):
13global _threadlocal_scope
14if not isinstance(single_helper_or_list, list):
15assert callable(single_helper_or_list), \
16"arg_scope is only supporting single or a list of helper functions."
17single_helper_or_list = [single_helper_or_list]
18old_scope = copy.deepcopy(get_current_scope())
19for helper in single_helper_or_list:
20assert callable(helper), \
21"arg_scope is only supporting a list of callable helper functions."
22helper_key = helper.__name__
23if helper_key not in old_scope:
24_threadlocal_scope.current_scope[helper_key] = {}
25_threadlocal_scope.current_scope[helper_key].update(kwargs)
26
27yield
28_threadlocal_scope.current_scope = old_scope
29
30
31def get_current_scope():
32global _threadlocal_scope
33if not hasattr(_threadlocal_scope, "current_scope"):
34_threadlocal_scope.current_scope = {}
35return _threadlocal_scope.current_scope
36