Python ast.SetComp() Examples
The following are 12
code examples of ast.SetComp().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ast
, or try the search function
.
Example #1
Source File: eval.py From vnpy_crypto with MIT License | 6 votes |
def ast_names(code): """Iterator that yields all the (ast) names in a Python expression. :arg code: A string containing a Python expression. """ # Syntax that allows new name bindings to be introduced is tricky to # handle here, so we just refuse to do so. disallowed_ast_nodes = (ast.Lambda, ast.ListComp, ast.GeneratorExp) if sys.version_info >= (2, 7): disallowed_ast_nodes += (ast.DictComp, ast.SetComp) for node in ast.walk(ast.parse(code)): if isinstance(node, disallowed_ast_nodes): raise PatsyError("Lambda, list/dict/set comprehension, generator " "expression in patsy formula not currently supported.") if isinstance(node, ast.Name): yield node.id
Example #2
Source File: eval.py From Splunking-Crime with GNU Affero General Public License v3.0 | 6 votes |
def ast_names(code): """Iterator that yields all the (ast) names in a Python expression. :arg code: A string containing a Python expression. """ # Syntax that allows new name bindings to be introduced is tricky to # handle here, so we just refuse to do so. disallowed_ast_nodes = (ast.Lambda, ast.ListComp, ast.GeneratorExp) if sys.version_info >= (2, 7): disallowed_ast_nodes += (ast.DictComp, ast.SetComp) for node in ast.walk(ast.parse(code)): if isinstance(node, disallowed_ast_nodes): raise PatsyError("Lambda, list/dict/set comprehension, generator " "expression in patsy formula not currently supported.") if isinstance(node, ast.Name): yield node.id
Example #3
Source File: backend.py From thonny with MIT License | 6 votes |
def _should_instrument_as_expression(self, node): return ( isinstance(node, _ast.expr) and hasattr(node, "end_lineno") and hasattr(node, "end_col_offset") and not getattr(node, "incorrect_range", False) and "ignore" not in node.tags and (not hasattr(node, "ctx") or isinstance(node.ctx, ast.Load)) # TODO: repeatedly evaluated subexpressions of comprehensions # can be supported (but it requires some redesign both in backend and GUI) and "ListComp.elt" not in node.tags and "SetComp.elt" not in node.tags and "DictComp.key" not in node.tags and "DictComp.value" not in node.tags and "comprehension.if" not in node.tags )
Example #4
Source File: test_ast.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def test_setcomp(self): self._simple_comp(ast.SetComp)
Example #5
Source File: test_ast.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_setcomp(self): self._simple_comp(ast.SetComp)
Example #6
Source File: _recompute.py From icontract with MIT License | 5 votes |
def _execute_comprehension(self, node: Union[ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp]) -> Any: """Compile the generator or comprehension from the node and execute the compiled code.""" args = [ast.arg(arg=name) for name in sorted(self._name_to_value.keys())] if platform.python_version_tuple() < ('3', ): raise NotImplementedError("Python versions below not supported, got: {}".format(platform.python_version())) if platform.python_version_tuple() < ('3', '8'): func_def_node = ast.FunctionDef( name="generator_expr", args=ast.arguments(args=args, kwonlyargs=[], kw_defaults=[], defaults=[]), decorator_list=[], body=[ast.Return(node)]) module_node = ast.Module(body=[func_def_node]) else: func_def_node = ast.FunctionDef( name="generator_expr", args=ast.arguments(args=args, posonlyargs=[], kwonlyargs=[], kw_defaults=[], defaults=[]), decorator_list=[], body=[ast.Return(node)]) module_node = ast.Module(body=[func_def_node], type_ignores=[]) ast.fix_missing_locations(module_node) code = compile(source=module_node, filename='<ast>', mode='exec') module_locals = {} # type: Dict[str, Any] module_globals = {} # type: Dict[str, Any] exec(code, module_globals, module_locals) # pylint: disable=exec-used generator_expr_func = module_locals["generator_expr"] return generator_expr_func(**self._name_to_value)
Example #7
Source File: _recompute.py From icontract with MIT License | 5 votes |
def visit_SetComp(self, node: ast.SetComp) -> Any: """Compile the set comprehension as a function and call it.""" result = self._execute_comprehension(node=node) for generator in node.generators: self.visit(generator.iter) self.recomputed_values[node] = result return result
Example #8
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_atom_7(p): '''atom : LBRACE dictorsetmaker RBRACE''' # 1 2 3 if isinstance(p[2], (ast.SetComp, ast.DictComp)): p[0] = p[2] p[0].alt = p[1][1] else: keys, values = p[2] if keys is None: p[0] = ast.Set(values, rule=inspect.currentframe().f_code.co_name, **p[1][1]) else: p[0] = ast.Dict(keys, values, rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #9
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_dictorsetmaker_6(p): '''dictorsetmaker : test comp_for''' # 1 2 p[0] = ast.SetComp(p[1], p[2], rule=inspect.currentframe().f_code.co_name) inherit_lineno(p[0], p[1])
Example #10
Source File: test_ast.py From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 | 5 votes |
def test_setcomp(self): self._simple_comp(ast.SetComp)
Example #11
Source File: debug.py From python-devtools with MIT License | 4 votes |
def _process_args(self, func_ast, code_lines, args, kwargs) -> 'Generator[DebugArgument, None, None]': # noqa: C901 import ast complex_nodes = ( ast.Call, ast.Attribute, ast.Subscript, ast.IfExp, ast.BoolOp, ast.BinOp, ast.Compare, ast.DictComp, ast.ListComp, ast.SetComp, ast.GeneratorExp, ) arg_offsets = list(self._get_offsets(func_ast)) for i, arg in enumerate(args): try: ast_node = func_ast.args[i] except IndexError: # pragma: no cover # happens when code has been commented out and there are fewer func_ast args than real args yield self.output_class.arg_class(arg) continue if isinstance(ast_node, ast.Name): yield self.output_class.arg_class(arg, name=ast_node.id) elif isinstance(ast_node, complex_nodes): # TODO replace this hack with astor when it get's round to a new release start_line, start_col = arg_offsets[i] if i + 1 < len(arg_offsets): end_line, end_col = arg_offsets[i + 1] else: end_line, end_col = len(code_lines) - 1, None name_lines = [] for l_ in range(start_line, end_line + 1): start_ = start_col if l_ == start_line else 0 end_ = end_col if l_ == end_line else None name_lines.append(code_lines[l_][start_:end_].strip(' ')) yield self.output_class.arg_class(arg, name=' '.join(name_lines).strip(' ,')) else: yield self.output_class.arg_class(arg) kw_arg_names = {} for kw in func_ast.keywords: if isinstance(kw.value, ast.Name): kw_arg_names[kw.arg] = kw.value.id for name, value in kwargs.items(): yield self.output_class.arg_class(value, name=name, variable=kw_arg_names.get(name))
Example #12
Source File: tracer.py From executing with MIT License | 4 votes |
def loops(node): # type: (ast.AST) -> Tuple[Loop, ...] """ Return all the 'enclosing loops' of a node, up to the innermost class or function definition. This also includes the 'for in' clauses in list/dict/set/generator comprehensions. So for example, in this code: for x in ...: def foo(): while True: print([z for y in ...]) The loops enclosing the node 'z' are 'while True' and 'for y in ...', in that order. """ result = [] while True: try: parent = node.parent except AttributeError: break if isinstance(parent, ast.FunctionDef): break is_containing_loop = (((isinstance(parent, ast.For) and parent.iter is not node or isinstance(parent, ast.While)) and node not in parent.orelse) or (isinstance(parent, ast.comprehension) and node in parent.ifs)) if is_containing_loop: result.append(parent) elif isinstance(parent, (ast.ListComp, ast.GeneratorExp, ast.DictComp, ast.SetComp)): generators = parent.generators if node in generators: generators = list(takewhile(lambda n: n != node, generators)) result.extend(reversed(generators)) node = parent result.reverse() return tuple(result)