Best Python code snippet using lisa_python
lexical_scope_symbol_table.py
Source:lexical_scope_symbol_table.py  
...36        """37         Returns the offset of the direct parent scope38        """39        return self.upper_scope_offset40    def get_symbol_table(self):41        """42         Returns the collection of symbols43        """44        return self.symbols45    def set_upper_scope_offset(self, offset):46        """47         Sets the direct parent scope offset48        """49        self.upper_scope_offset = offset50    def set_offset_scope(self, offset):51        """52         Sets the current scope offset53        """54        self.offset_scope = offset55    def set_symbol_table(self, symbol_table):56        """57         Sets the value of the symbol table58        """59        self.symbols = symbol_table60class LexicalScopeSymbolTable(object):61    """62     Contains the implementation of the tracking of symbols and their values per scope level63    """64    level_scope = list(list())65    current_level = 066    def __init__(self):67        self.initialize_scope()68    def debug_level(self):69        """70         Prints the number of scope level and prints the number of symbols per scope71        """72        print "DEBUG_LEVEL: Number of level => " + str(self.get_size_level())73        for scope_collection in self.level_scope:74            print "Debug_level: " + str(len(scope_collection))75    def dump_level(self, level):76        """77         Prints the content of each scope level78        """79        collection_scope = self.level_scope[level]80        print "#" * 35 + "Dump_Level" + "#" * 3581        for scope_offset in collection_scope:82            symbol_table = scope_offset.get_symbol_table()83            i = scope_offset.get_offset_scope()84            for k, value in symbol_table.iteritems():85                print "Scope(%s:%s) -> id: %s, value=%s, addr=%s, addr_table=%s"\86                    % (str(level), str(i), str(k)87                       , str(value.n), str(value), str(hex(id(symbol_table))))88    def add_new_scope(self):89        """90         Creates and append a new scope to the current level of the EntrySymbolTable91         A scope contains:92          offset: offset of the new scope93          upper_scope: level of the direct parent scope94          dictionnary: contains symbol as key associated with a value95        """96        # upper_offset = self.get_offset_last_dominant()97        self.level_scope.append([EntrySymbolTable(self.current_level, -1, -1, dict())])98        addr_table = hex(id(self.level_scope[self.current_level][-1].get_symbol_table()))99        print "Add_new_scope: %s:%s - addr_table=%s" % ("x", "x", addr_table)100    def add_new_offset(self, index_level):101        """102         Adds an offset of a scope level103        """104        # offset = len(self.level_scope[index_level])105        self.level_scope[index_level].append(EntrySymbolTable(index_level, -1, -1, dict()))106        addr_table = hex(id(self.level_scope[self.current_level][-1].get_symbol_table()))107        print "Add_new_offset: %s:%s - addr_table=%s" % ("x", "x", addr_table)108    def set_offset_new_scope(self):109        """110         Sets the direct parent offset and the current offset of a scope level111        """112        # offset = -1113        upper_offset = self.get_offset_last_dominant()114        if self.get_offset_current_level() == -1:115            offset = self.get_size_offset(self.get_current_level()) - 1116        else:117            offset = self.level_scope[self.get_current_level()][-1].get_offset_scope() + 1118        self.level_scope[self.get_current_level()][-1].set_offset_scope(offset)119        self.level_scope[self.get_current_level()][-1].set_upper_scope_offset(upper_offset)120    def initialize_scope(self):121        """122         Initialize a scope123        """124        index_level = self.get_current_level()125        if index_level >= self.get_size_level():126            self.add_new_scope()127        else:128            self.add_new_offset(index_level)129        # upper_offset = self.get_offset_last_dominant()130        current_offset = self.get_offset_current_level()131        self.set_offset_new_scope()132        self.print_scope_initialization(current_offset)133        self.current_level += 1134    def bind_symbol(self, symbol, value, index_level, offset):135        """136         Sets the state of a symbol, according to its scope level137        """138        symbol_table = self.get_symbol_table(index_level, offset)139        symbol_table[symbol] = value140        print "Bind_scope: %s:%s - addr_table=%s" \141            % (str(index_level), offset, str(hex(id(symbol_table))))142    def lookup_symbol(self, symbol):143        """144         Returns the value associated to a symbol145        """146        index_level = self.get_current_level() - 1147        if index_level < 0:148            print "ERROR(lexicalScopeSymbolTable.lookup_symbol): index level must be positive"149            return None150        offset = self.get_offset_by_level(index_level)151        symbol_table = self.get_symbol_table(index_level, offset)152        if symbol in symbol_table.keys():153            value = symbol_table[symbol]154            return value155        print "Lookup_symbol: Not found - " + str(symbol)156        return self.lookup_dominant_scope(symbol, index_level, offset)157    def lookup_dominant_scope(self, symbol, index_level, offset):158        """159         Returns the value of a symbol of a direct dominant scope160        """161        dominant_level = index_level - 1162        upper_offset = self.level_scope[index_level][offset].get_upper_offset()163        if self.level_scope[dominant_level][upper_offset]:164            symbol_table = self.get_symbol_table(dominant_level, upper_offset)165            if symbol in symbol_table.keys():166                print "Lookup_dominant_scope: found %s=%s" \167                    % (symbol, symbol_table[symbol])168                return symbol_table[symbol]169        print "Lookup_dominant_scope: Not found - %s; upper_level=%s, upper_offset=%s" \170            % (str(symbol), dominant_level, upper_offset)171        return None172    def finalize_scope(self):173        """174         Close a scope level, decrement the current level175        """176        self.current_level -= 1177        print "===== -> Finalize Scope %s =====" % (str(self.current_level))178    def get_offset_last_dominant(self):179        """180         Returns the offset of the last dominant scope181        """182        if self.get_current_level() == 0:183            return 0184        return self.level_scope[self.get_current_level() - 1][-1].get_offset_scope()185    def get_last_offset_level(self, index_level):186        """187         Returns the last valid offset of a specific scope188        """189        return len(self.level_scope[index_level]) - 1190    def get_offset_current_level(self):191        """192         Returns the offset of the current level193        """194        return self.level_scope[self.current_level][-1].get_offset_scope()195    def get_offset_by_level(self, index_level):196        """197         Returns the offset of a specified level198        """199        return self.level_scope[index_level][-1].get_offset_scope()200    def get_size_offset(self, index_level):201        """202         Returns the number of symbol in a specified scope level203        """204        return len(self.level_scope[index_level])205    def get_last_offset(self, index_level):206        """207         Returns the last valid offset of a scope level208        """209        return self.level_scope[index_level][-1].get_offset_scope()210    def get_size_level(self):211        """212         Returns the size of level_scope213        """214        return len(self.level_scope)215    def get_scope(self, offset):216        """217         Returns a scope by offset218        """219        return self.level_scope[self.get_current_level()][offset]220    def get_current_level(self):221        """222         Returns the value of the current scope level223        """224        return self.current_level225    def get_symbol_table(self, index_level, offset):226        """227         Returns the symbol table228        """229        symbol_table = self.level_scope[index_level][offset].get_symbol_table()230        print "Get_symbol_table(Scope %s:%s)" % (str(index_level), offset)231        return symbol_table232    def print_scope_initialization(self, offset):233        """234         Prints debug informations:235          - current_level: current scope level236          - offset: current scope offset237          - upper_offset: direct parent scope offset238        """239        print "===== -> Initialize Scope %s:%s - %s ====="\240            % (str(self.current_level)241               , self.get_scope(offset).get_offset_scope()...stack.py
Source:stack.py  
...32        # the implementation of chain map does things this way33        yield from set().union(self.locals, self.globals)34    def __len__(self):35        return len(set().union(self.locals, self.globals))36def get_symbol_table(37        decorators: tp.Optional[tp.Sequence[inspect.FrameInfo]] = None,38        copy_locals: bool = False39        ) -> SymbolTable:40    exec(_SKIP_FRAME_DEBUG_STMT)41    locals = ChainMap()42    globals = ChainMap()43    if decorators is None:44        decorators = set()45    else:46        decorators = {f.__code__ for f in decorators}47    decorators.add(get_symbol_table.__code__)48    stack = inspect.stack()49    for i in range(len(stack) - 1, 0, -1):50        frame = stack[i]51        if frame.frame.f_code in decorators:52            continue53        debug_check = frame.frame.f_locals.get(_SKIP_FRAME_DEBUG_NAME, None)54        if debug_check == _SKIP_FRAME_DEBUG_VALUE:55            if _SKIP_FRAME_DEBUG_FAIL:56                raise RuntimeError(f'{frame.function} @ {frame.filename}:{frame.lineno} might be leaking names')57            else:58                logging.debug(f'{frame.function} @ {frame.filename}:{frame.lineno} might be leaking names')59        f_locals = stack[i].frame.f_locals60        if copy_locals:61            f_locals = copy.copy(f_locals)62        locals = locals.new_child(f_locals)63        globals = globals.new_child(stack[i].frame.f_globals)64    return SymbolTable(locals=locals, globals=dict(globals))65def inspect_symbol_table(66        fn: tp.Callable, # tp.Callable[[SymbolTable, ...], tp.Any],67        *,68        decorators: tp.Optional[tp.Sequence[inspect.FrameInfo]] = None,69        ) -> tp.Callable:70    exec(_SKIP_FRAME_DEBUG_STMT)71    if decorators is None:72        decorators = ()73    @functools.wraps(fn)74    def wrapped_0(*args, **kwargs):75        exec(_SKIP_FRAME_DEBUG_STMT)76        st = get_symbol_table(list(itertools.chain(decorators, [wrapped_0])))77        return fn(st, *args, **kwargs)78    return wrapped_079# mostly equivelent to magma.ast_utils.inspect_enclosing_env80def inspect_enclosing_env(81        fn: tp.Callable, # tp.Callable[[tp.Dict[str, tp.Any], ...], tp.Any],82        *,83        decorators: tp.Optional[tp.Sequence[inspect.FrameInfo]] = None,84        st: tp.Optional[SymbolTable] = None) -> tp.Callable:85    exec(_SKIP_FRAME_DEBUG_STMT)86    if decorators is None:87        decorators = ()88    @functools.wraps(fn)89    def wrapped_0(*args, **kwargs):90        exec(_SKIP_FRAME_DEBUG_STMT)91        _st = get_symbol_table(list(itertools.chain(decorators, [wrapped_0])))92        if st is not None:93            _st.locals.update(st)94        env = dict(_st.globals)95        env.update(_st.locals)96        return fn(env, *args, **kwargs)...test_stack.py
Source:test_stack.py  
1import pytest2from ast_tools import stack3MAGIC = 'foo'4def test_get_symbol_table():5    MAGIC = 'bar'6    st = stack.get_symbol_table()7    assert st.globals['MAGIC'] == 'foo'8    assert st.locals['MAGIC'] == 'bar'9def test_inspect_symbol_table():10    MAGIC = 'bar'11    @stack.inspect_symbol_table12    def test(st):13        assert st.globals['MAGIC'] == 'foo'14        assert st.locals['MAGIC'] == 'bar'15    test()16    @stack.inspect_symbol_table17    def test(st):18        assert st.locals[stack._SKIP_FRAME_DEBUG_NAME] == 0xdeadbeaf19    stack._SKIP_FRAME_DEBUG_FAIL = True20    exec(stack._SKIP_FRAME_DEBUG_STMT)21    with pytest.raises(RuntimeError):22        test()23    stack._SKIP_FRAME_DEBUG_FAIL = False24    test()25def test_inspect_enclosing_env():26    MAGIC = 'bar'27    @stack.inspect_enclosing_env28    def test(env):29        assert env['MAGIC'] == 'bar'30    test()31    @stack.inspect_enclosing_env32    def test(env):33        assert env[stack._SKIP_FRAME_DEBUG_NAME] == 0xdeadbeaf34    stack._SKIP_FRAME_DEBUG_FAIL = True35    exec(stack._SKIP_FRAME_DEBUG_STMT)36    with pytest.raises(RuntimeError):37        test()38    stack._SKIP_FRAME_DEBUG_FAIL = False39    test()40def test_custom_env():41    MAGIC1 = 'foo'42    def test(env):43        assert env['MAGIC1'] == 'foo'44        assert env['MAGIC2'] == 'bar'45    st = stack.SymbolTable(locals={},globals={'MAGIC2':'bar'})46    test = stack.inspect_enclosing_env(test, st=st)47    test()48def test_get_symbol_table_copy_frames():49    non_copy_sts = []50    copy_sts = []51    for i in range(5):52        non_copy_sts.append(stack.get_symbol_table())53        copy_sts.append(stack.get_symbol_table(copy_locals=True))54    for j in range(5):55        assert non_copy_sts[j].locals["i"] == 4...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
