locals.pyx 1.78 KB
Newer Older
1 2
# mode: run
# tag: builtins, locals, dir
Stefan Behnel's avatar
Stefan Behnel committed
3

Robert Bradshaw's avatar
Robert Bradshaw committed
4
def get_locals(x, *args, **kwds):
5
    """
6
    >>> sorted( get_locals(1,2,3, k=5).items() )
7 8
    [('args', (2, 3)), ('kwds', {'k': 5}), ('x', 1), ('y', 'hi'), ('z', 5)]
    """
Robert Bradshaw's avatar
Robert Bradshaw committed
9
    cdef int z = 5
Stefan Behnel's avatar
Stefan Behnel committed
10
    y = "hi"
Robert Bradshaw's avatar
Robert Bradshaw committed
11
    return locals()
Stefan Behnel's avatar
Stefan Behnel committed
12

13 14 15 16 17 18 19 20 21
def get_vars(x, *args, **kwds):
    """
    >>> sorted( get_vars(1,2,3, k=5).items() )
    [('args', (2, 3)), ('kwds', {'k': 5}), ('x', 1), ('y', 'hi'), ('z', 5)]
    """
    cdef int z = 5
    y = "hi"
    return vars()

22 23 24 25 26 27 28 29 30
def get_dir(x, *args, **kwds):
    """
    >>> sorted( get_dir(1,2,3, k=5) )
    ['args', 'kwds', 'x', 'y', 'z']
    """
    cdef int z = 5
    y = "hi"
    return dir()

Stefan Behnel's avatar
Stefan Behnel committed
31
def in_locals(x, *args, **kwds):
32 33 34 35 36 37 38 39
    """
    >>> in_locals('z')
    True
    >>> in_locals('args')
    True
    >>> in_locals('X')
    False
    """
Stefan Behnel's avatar
Stefan Behnel committed
40 41 42 43
    cdef int z = 5
    y = "hi"
    return x in locals()

44 45 46 47 48 49 50 51 52 53 54 55 56
def in_dir(x, *args, **kwds):
    """
    >>> in_dir('z')
    True
    >>> in_dir('args')
    True
    >>> in_dir('X')
    False
    """
    cdef int z = 5
    y = "hi"
    return x in dir()

57 58 59 60 61 62 63 64 65 66 67 68 69
def in_vars(x, *args, **kwds):
    """
    >>> in_vars('z')
    True
    >>> in_vars('args')
    True
    >>> in_vars('X')
    False
    """
    cdef int z = 5
    y = "hi"
    return x in vars()

Stefan Behnel's avatar
Stefan Behnel committed
70 71 72 73
def sorted(it):
    l = list(it)
    l.sort()
    return l
74 75 76 77 78 79 80 81

def locals_ctype():
    """
    >>> locals_ctype()
    False
    """
    cdef int *p = NULL
    return 'p' in locals()
82 83 84 85 86 87 88 89 90

def locals_ctype_inferred():
    """
    >>> locals_ctype_inferred()
    False
    """
    cdef int *p = NULL
    b = p
    return 'b' in locals()
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105


def pass_on_locals(f):
    """
    >>> def print_locals(l, **kwargs):
    ...     print(sorted(l))

    >>> pass_on_locals(print_locals)
    ['f']
    ['f']
    ['f']
    """
    f(locals())
    f(l=locals())
    f(l=locals(), a=1)