How to use visit_listcomp method in Kiwi

Best Python code snippet using Kiwi_python

nast.py

Source:nast.py Github

copy

Full Screen

1from ast import Attribute, Subscript, Load2from .compat import PY23from .scope import FuncScope, Flow, SourceScope, ClassScope4from .name import AssignedName, ImportedName5from .util import (np, get_expr_end, get_indexes_for_target, visitor, get_any_marked_name)6if PY2:7 UNSUPPORTED_ASSIGMENTS = Subscript8else:9 from ast import Starred10 UNSUPPORTED_ASSIGMENTS = Subscript, Starred11def extract_scope(source, project):12 scope = SourceScope(source)13 extract(source.tree, scope.flow)14 scope.resolve_star_imports(project)15 return scope16def marked_flow(scope):17 name = get_any_marked_name(scope.source.tree)18 if name and hasattr(name, 'flow'):19 marked_id = name._orig.id20 for n in name.flow._names:21 if n.name == marked_id:22 n.name = name.id23 if marked_id in name.flow.scope.locals:24 name.flow.scope.locals.remove(marked_id)25 name.flow.scope.locals.add(name.id)26 return name.flow27@visitor28class extract(object):29 def process(self, tree, flow):30 self.top = flow.scope.top31 self.flow = flow32 self.generic_visit(tree)33 return flow34 def make_flow(self, hint, parents):35 return self.top.add_flow(Flow(hint, self.flow.scope, parents))36 def visit_in_flow(self, nodes, flow):37 cur = self.flow38 self.flow = flow39 if nodes:40 if type(nodes) == list:41 for n in nodes:42 self.visit(n)43 else:44 self.visit(nodes)45 result = self.flow46 self.flow = cur47 return result48 def visit_Assign(self, node):49 eend = get_expr_end(node.value)50 for targets in node.targets:51 for name, _ in get_indexes_for_target(targets, [], []):52 if isinstance(name, Attribute):53 self.top.add_attr_assign(self.flow.scope, name, node.value)54 elif isinstance(name, UNSUPPORTED_ASSIGMENTS):55 continue56 else:57 name.flow = self.flow58 self.flow.add_name(AssignedName(name.id, eend, np(name), node.value))59 self.generic_visit(node)60 def visit_If(self, node):61 self.visit(node.test)62 cur = self.flow63 body = self.visit_in_flow(node.body, self.make_flow('if', [cur]))64 orelse = self.visit_in_flow(node.orelse, self.make_flow('else', [cur]))65 self.flow = self.make_flow('join', [body, orelse])66 self.flow.scope.flow = self.flow67 def visit_For(self, node):68 self.visit(node.iter)69 cur = self.flow70 body_start = self.make_flow('for', [cur])71 for nn, _idx in get_indexes_for_target(node.target, [], []):72 body_start.add_name(AssignedName(nn.id, np(node.body[0]), np(nn), node.iter))73 body = self.visit_in_flow(node.body, body_start)74 body_start.loop(body)75 orelse = self.visit_in_flow(node.orelse, self.make_flow('for-else', [cur, body]))76 self.flow = self.make_flow('join', [orelse])77 self.flow.scope.flow = self.flow78 visit_AsyncFor = visit_For79 def visit_While(self, node):80 self.visit(node.test)81 cur = self.flow82 body_start = self.make_flow('while', [cur])83 body = self.visit_in_flow(node.body, body_start)84 body_start.loop(body)85 orelse = self.visit_in_flow(node.orelse,86 self.make_flow('while-else', [cur, body]))87 self.flow = self.make_flow('join', [orelse])88 self.flow.scope.flow = self.flow89 def visit_Import(self, node):90 loc = get_expr_end(node)91 start = np(node)92 for a in node.names:93 qualified = False94 if a.asname:95 name = a.asname96 iname = a.name97 else:98 name, sep, _ = a.name.partition('.')99 qualified = bool(sep)100 iname = name101 self.top._imports.append(a.name)102 declared_at = self.top.find_id_loc(name, start)103 self.flow.add_name(ImportedName(name, loc, declared_at, iname, None,104 qualified=qualified))105 def visit_ImportFrom(self, node):106 loc = get_expr_end(node)107 start = np(node)108 for a in node.names:109 name = a.asname or a.name110 declared_at = self.top.find_id_loc(name, start)111 module = '.' * node.level + (node.module or '')112 if name == '*':113 self.top._star_imports.append((loc, declared_at, module, self.flow))114 else:115 self.flow.add_name(ImportedName(name, loc, declared_at, module, a.name))116 def visit_TryExcept(self, node):117 cur = self.flow118 body = self.visit_in_flow(node.body, self.make_flow('try', [cur]))119 handlers = []120 for h in node.handlers:121 fh = self.make_flow('except', [cur, body])122 if h.name:123 if PY2:124 fh.add_name(AssignedName(h.name.id, np(h.body[0]), np(h), h.type))125 else:126 fh.add_name(AssignedName(h.name, np(h.body[0]), np(h), h.type))127 if h.type:128 self.visit(h.type)129 handlers.append(self.visit_in_flow(h.body, fh))130 orelse = self.visit_in_flow(node.orelse,131 self.make_flow('try-else', [body]))132 self.flow = self.make_flow('join', [orelse] + handlers)133 self.flow.scope.flow = self.flow134 if hasattr(node, 'finalbody'):135 self.visit_in_flow(node.finalbody, self.flow)136 visit_Try = visit_TryExcept137 def visit_FunctionDef(self, node):138 for d in node.decorator_list:139 self.visit(d)140 for a in node.args.defaults:141 self.visit(a)142 if not PY2:143 for a in node.args.args:144 a.annotation and self.visit(a.annotation)145 for a in node.args.kwonlyargs:146 a.annotation and self.visit(a.annotation)147 node.returns and self.visit(node.returns)148 cur = self.flow149 scope = FuncScope(cur.scope, node, top=self.top)150 cur.add_name(scope)151 self.visit_in_flow(node.body, scope.flow)152 self.flow = cur153 visit_AsyncFunctionDef = visit_FunctionDef154 def visit_Lambda(self, node):155 for a in node.args.defaults:156 self.visit(a)157 if not PY2:158 for a in node.args.args:159 a.annotation and self.visit(a.annotation)160 for a in node.args.kwonlyargs:161 a.annotation and self.visit(a.annotation)162 cur = self.flow163 scope = FuncScope(cur.scope, node, True, top=self.top)164 self.visit_in_flow(node.body, scope.flow)165 def visit_ClassDef(self, node):166 cur = self.flow167 self.visit_in_flow(node.decorator_list, cur)168 self.visit_in_flow(node.bases, cur)169 scope = ClassScope(cur.scope, node, top=self.top)170 cur.add_name(scope)171 self.visit_in_flow(node.body, scope.flow)172 self.flow = cur173 def visit_Return(self, node):174 self.flow.scope.returns.append(node.value)175 self.generic_visit(node)176 def visit_ListComp(self, node):177 p = cur = self.flow178 for g in node.generators:179 self.visit_in_flow(g.iter, p)180 pp = p181 p = self.make_flow('comp', [p])182 for nn, _idx in get_indexes_for_target(g.target, [], []):183 nn.flow = pp184 p.add_name(AssignedName(nn.id, np(node), np(nn), g.iter))185 if g.ifs:186 for inode in g.ifs:187 self.visit_in_flow(inode, p)188 elt = getattr(node, 'elt', None) or node.value189 self.visit_in_flow(elt, p)190 if hasattr(node, 'key'):191 self.visit_in_flow(node.key, p)192 self.flow = self.make_flow('comp-join', [cur, p])193 self.flow.scope.flow = self.flow194 visit_GeneratorExp = visit_ListComp195 visit_DictComp = visit_ListComp196 visit_SetComp = visit_ListComp197 def visit_With(self, node):198 if PY2:199 items = [node]200 else:201 items = node.items202 for it in items:203 if it.optional_vars:204 for nn, _idx in get_indexes_for_target(it.optional_vars, [], []):205 self.flow.add_name(AssignedName(nn.id, np(node.body[0]), np(nn), node))206 self.generic_visit(node)207 visit_AsyncWith = visit_With208 def visit_Global(self, node):209 self.flow.scope.globals.update(node.names)210 def visit_Name(self, node):211 if type(node.ctx) is Load:...

Full Screen

Full Screen

astglobals.py

Source:astglobals.py Github

copy

Full Screen

1import ast2import collections3import unittest4import warnings5from contextlib import contextmanager6from cached_property import cached_property7__all__ = ['find_globals', 'FindFreeVariablesClassWarning']8class FindFreeVariablesClassWarning(UserWarning):9 pass10class FindFreeVariables(ast.NodeVisitor):11 ''' use the `find_globals` utility function '''12 @cached_property13 def ffv_scope(self):14 return collections.ChainMap()15 @cached_property16 def ffv_globals(self):17 return set()18 # possible scopes: local, global, force_global19 @property20 def ffv_new_scope(self):21 scope = self.ffv_scope22 @contextmanager23 def context():24 scope.maps.insert(0, dict())25 yield26 fglobals = self.ffv_globals27 for name, var_scope in scope.maps[0].items():28 if var_scope != 'local':29 fglobals.add(name)30 del scope.maps[0]31 return context32 def ffv_binding(self, name, state='local'):33 d = self.ffv_scope34 cur = d.get(name, 'global')35 if cur != 'force_global':36 if not (cur == 'local' and state == 'global'):37 d[name] = state38 def visit_ListComp(self, node):39 with self.ffv_new_scope():40 super().generic_visit(node)41 def visit_SetComp(self, node):42 self.visit_ListComp(node)43 def visit_DictComp(self, node):44 self.visit_ListComp(node)45 def visit_GeneratorExp(self, node):46 self.visit_ListComp(node)47 def visit_Name(self, node):48 if isinstance(node.ctx, ast.Store): # establish new binding49 self.ffv_binding(node.id)50 elif isinstance(node.ctx, ast.Load):51 self.ffv_binding(node.id, state='global')52 super().generic_visit(node)53 def visit_FunctionDef(self, node):54 with self.ffv_new_scope():55 args = node.args56 for a in args.args:57 self.ffv_binding(a.arg)58 for a in args.kwonlyargs:59 self.ffv_binding(a.arg)60 if args.vararg:61 self.ffv_binding(args.vararg.arg)62 if args.kwarg:63 self.ffv_binding(args.kwarg.arg)64 super().generic_visit(node)65 name = getattr(node, 'name', None)66 if name: self.ffv_binding(node.name)67 def visit_AsyncFunctionDef(self, node):68 self.visit_FunctionDef(node)69 def visit_Lambda(self, node):70 self.visit_FunctionDef(node)71 def visit_ClassDef(self, node):72 warnings.warn(FindFreeVariablesClassWarning(73 "Global variable detection is not fully implemented for Python "74 "classes. This may lead to false dependencies being established "75 "in the caching system."))76 super().generic_visit(node)77 def visit_ExceptHandler(self, node):78 if node.name:79 self.ffv_binding(node.name)80 super().generic_visit(node)81 def visit_Import(self, node):82 for alias in node.names:83 self.ffv_binding(alias.asname)84 super().generic_visit(node)85 def visit_ImportFrom(self, node):86 self.visit_Import(node)87 def visit_Global(self, node):88 for name in node.names:89 self.ffv_binding(name, 'force_global')90 super().generic_visit(node)91 def visit_With(self, node):92 super().generic_visit(node)93def find_globals(ast_tree):94 '''95Returns a set of all global variable names referenced in the code.96Warning: does not yet work properly on classes.'''97 ffv = FindFreeVariables()98 ffv.visit(ast_tree)99 return ffv.ffv_globals100class UnitTest(unittest.TestCase):101 def test_me(self):102 codes = [('''\103def f(a, b):104 l1 = a + b105 g1(g2, l1)106''', 'g1 g2'),107 ('''\108def f(a):109 l1, g1.abc, l2 = a + g2110 if a:111 l3 = g3(l2, name=l1, *l3, **g4)112 g5.A2[l3] = g6.A1[l2]113''', 'g1 g2 g3 g4 g5 g6'),114('''\115def f(a):116 for i in a:117 g1(a, i)118 l1 = g2[g3(i)]119 with g4(l1) as l2:120 g1(l1, l2)121 def h(b, arg=g5):122 g6(l1, l2, i)123 k = lambda b, arg=g7: g8(l1, b)124''', 'g1 g2 g3 g4 g5 g6 g7 g8'),125 ('''\126def f(a):127 try:128 l1 = g1()129 except g4 as l2:130 l1 = g2(l2)131 finally:132 g3()133''', 'g1 g2 g3 g4'),134 ('''\135def f(a):136 import abc as l1137 from abc import xyz as l2138 g1(l1, l2)139''', 'g1'),140 ('''\141def f(a):142 global g1143 g1, l1 = a144''', 'g1'),145 ('''\146def f(a):147 with g1(a, g2) as l1:148 g2(l1)149 g3(l1, a)150''', 'g1 g2 g3'),151 ('''\152def f(a):153 g1(l1+g2 for l1 in a+g3)154 g4([l2+g5 for l2 in a+g6])155''', 'g1 g2 g3 g4 g5 g6'),156 ('''\157def f(a):158 def l1():159 return a160 return l1161''', ''),162 ('''\163def f1(g1):164 def f2():165 global g1166 def f3():167 g1()168''', 'g1'),169]170 for code, gs in codes:171 c = ast.parse(code)172 self.assertEqual(set(gs.split()), find_globals(c))173 def test_raises_warning(self):174 c = ast.parse('''175def f(a):176 class l1(g1, metaclass=g2):177 l2 = a178 g3 = a # here it's local to the class179 def method(self):180 g3() # here this is actually a global!181''')182 with warnings.catch_warnings(record=True) as w:183 warnings.simplefilter("always")184 find_globals(c)185 self.assertEqual(len(w), 1)186 self.assertTrue(issubclass(...

Full Screen

Full Screen

analysis.py

Source:analysis.py Github

copy

Full Screen

1class CodeVisitor(TutorialNodeVisitor):2 def __init__(self):3 super().__init__()4 self.uses_comprehension = False5 self.uses_if_comprehension = False6 def visit_ListComp(self, node):7 super().visit_ListComp(node)8 self.uses_comprehension = True9 if node.generators[0].ifs != []:10 self.uses_if_comprehension = True11class Analyser(CodeAnalyser):12 def _analyse(self):13 if not self.visitor.functions['square_odds'].is_defined:14 self.add_error('You need to define square_odds')15 elif len(self.visitor.functions['square_odds'].args) != 1:16 self.add_error('square_odds should accept exactly one arg')17 else:18 if not self.visitor.uses_comprehension:19 self.add_error('You need to use list comprehension')20 if not self.visitor.uses_if_comprehension:21 self.add_error('You need to use if inside list comprehension')...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kiwi automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful