default_scope_funcs.py 1.8 KB
Newer Older
Y
Yu Yang 已提交
1 2 3
"""
Default scope function.

4 5 6
`Paddle` manages Scope as programming language's scope.  It just a
thread-local stack of Scope. Top of that stack is current scope, the bottom
of that stack is all scopes' parent.
Y
Yu Yang 已提交
7

8 9 10
Invoking `var/find_var`  can `new/find` variable in current scope.
Invoking `enter_local_scope/leave_local_scope` can create or destroy local
scope.
Y
Yu Yang 已提交
11

12 13
A `scoped_function` will take a `function` as input. That function will be
invoked in a new local scope.
Y
Yu Yang 已提交
14 15
"""

Q
Qiao Longfei 已提交
16
import paddle.v2.fluid.core
Y
Yu Yang 已提交
17 18 19 20 21
import threading

__tl_scope__ = threading.local()

__all__ = [
22 23 24 25 26 27
    'get_cur_scope',
    'enter_local_scope',
    'leave_local_scope',
    'var',
    'find_var',
    'scoped_function',
Y
Yu Yang 已提交
28 29 30 31 32 33
]


def get_cur_scope():
    """
    Get current scope.
Q
Qiao Longfei 已提交
34
    :rtype: paddle.v2.fluid.core.Scope
Y
Yu Yang 已提交
35 36 37 38 39
    """
    cur_scope_stack = getattr(__tl_scope__, 'cur_scope', None)
    if cur_scope_stack is None:
        __tl_scope__.cur_scope = list()
    if len(__tl_scope__.cur_scope) == 0:
Q
Qiao Longfei 已提交
40
        __tl_scope__.cur_scope.append(paddle.v2.fluid.core.Scope())
Y
Yu Yang 已提交
41 42 43 44 45 46 47 48
    return __tl_scope__.cur_scope[-1]


def enter_local_scope():
    """
    Enter a new local scope
    """
    cur_scope = get_cur_scope()
Y
Yu Yang 已提交
49
    new_scope = cur_scope.new_scope()
Y
Yu Yang 已提交
50 51 52 53 54 55 56 57
    __tl_scope__.cur_scope.append(new_scope)


def leave_local_scope():
    """
    Leave local scope
    """
    __tl_scope__.cur_scope.pop()
Y
Yu Yang 已提交
58
    get_cur_scope().drop_kids()
Y
Yu Yang 已提交
59 60


D
dongzhihong 已提交
61
def var(name):
Y
Yu Yang 已提交
62 63 64
    """
    create variable in current scope.
    """
D
dongzhihong 已提交
65
    return get_cur_scope().var(name)
Y
Yu Yang 已提交
66 67


Y
Yu Yang 已提交
68
def find_var(name):
Y
Yu Yang 已提交
69 70 71
    """
    get variable in current scope.
    """
Y
Yu Yang 已提交
72
    return get_cur_scope().find_var(name)
Y
Yu Yang 已提交
73 74 75 76 77


def scoped_function(func):
    """
    invoke `func` in new scope.
78

Y
Yu Yang 已提交
79 80 81 82 83 84 85 86 87 88
    :param func: a callable function that will be run in new scope.
    :type func: callable
    """
    enter_local_scope()
    try:
        func()
    except:
        raise
    finally:
        leave_local_scope()