Python ast.Attribute() Examples
The following are 30
code examples of ast.Attribute().
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: Recording.py From swirlypy with GNU General Public License v3.0 | 8 votes |
def visit_Expr(self, node): newnode = ast.copy_location(ast.Expr( value = ast.Call( func = ast.Attribute( value = ast.Name(id='__swirlypy_recorder__', ctx=ast.Load()), attr="record", ctx=ast.Load()), args=[node.value], keywords=[], starargs=None, kwargs=None ) ), node) ast.fix_missing_locations(newnode) return newnode
Example #2
Source File: expr.py From recruit with Apache License 2.0 | 6 votes |
def visit_Attribute(self, node, **kwargs): attr = node.attr value = node.value ctx = node.ctx if isinstance(ctx, ast.Load): # resolve the value resolved = self.visit(value).value try: v = getattr(resolved, attr) name = self.env.add_tmp(v) return self.term_type(name, self.env) except AttributeError: # something like datetime.datetime where scope is overridden if isinstance(value, ast.Name) and value.id == attr: return resolved raise ValueError("Invalid Attribute context {name}" .format(name=ctx.__name__))
Example #3
Source File: _analyze.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def visit_FunctionDef(self, node): self.refStack.push() for n in node.body: self.visit(n) self.tree.kind = _kind.SIMPLE_ALWAYS_COMB for n in node.body: if isinstance(n, ast.Expr) and isinstance(n.value, ast.Str): continue # skip doc strings if isinstance(n, ast.Assign) and \ isinstance(n.targets[0], ast.Attribute) and \ self.getKind(n.targets[0].value) != _kind.REG: pass else: self.tree.kind = _kind.ALWAYS_COMB return # rom access is expanded into a case statement in addition # to any always_comb that contains a list of signals # if self.tree.hasRom or self.tree.hasLos: if self.tree.hasRom: self.tree.kind = _kind.ALWAYS_COMB self.refStack.pop()
Example #4
Source File: cmd.py From recipes-py with Apache License 2.0 | 6 votes |
def _apply_imports_to_unparsed_expression(exp_ast, imports): """Attempts to evaluate the code equivalent of `exp_ast`, with `imports` as available symbols. If it's successful, it returns the evaluated object. Otherwise this returns the unparsed code for `exp_ast`. Args: * exp_ast (Union[ast.Name, ast.Attribute, ast.Call]) - The expression to evaluate. * imports (Dict[str, object]) - The symbols to include during the evaluation of `exp_ast`. Returns the evaluation of `exp_ast` if it can successfully evaluate with `imports`. Otherwise this returns the source-code representation of exp_ast as a string. """ assert isinstance(exp_ast, (ast.Name, ast.Attribute, ast.Call)), type(exp_ast) unparsed = _unparse(exp_ast).strip() try: return eval(unparsed, {'__builtins__': None}, imports) except (NameError, AttributeError): return unparsed
Example #5
Source File: topython.py From pyrser with GNU General Public License v3.0 | 6 votes |
def visit_Hook(self, node: parsing.Hook) -> ast.expr: """Generates python code calling a hook. self.evalHook('hookname', self.ruleNodes[-1]) """ return ast.Call( ast.Attribute( ast.Name('self', ast.Load()), 'evalHook', ast.Load()), [ ast.Str(node.name), ast.Subscript( ast.Attribute( ast.Name('self', ast.Load()), 'ruleNodes', ast.Load()), ast.Index(ast.UnaryOp(ast.USub(), ast.Num(1))), ast.Load())], [], None, None)
Example #6
Source File: expr.py From vnpy_crypto with MIT License | 6 votes |
def visit_Attribute(self, node, **kwargs): attr = node.attr value = node.value ctx = node.ctx if isinstance(ctx, ast.Load): # resolve the value resolved = self.visit(value).value try: v = getattr(resolved, attr) name = self.env.add_tmp(v) return self.term_type(name, self.env) except AttributeError: # something like datetime.datetime where scope is overridden if isinstance(value, ast.Name) and value.id == attr: return resolved raise ValueError("Invalid Attribute context {name}" .format(name=ctx.__name__))
Example #7
Source File: formatting.py From snoop with MIT License | 6 votes |
def format_executing_node_exception(self, event): try: assert not NO_ASTTOKENS node = Source.executing(event.frame).node assert node description = { ast.Call: 'calling', ast.Subscript: 'subscripting', ast.Attribute: 'getting attribute', ast.Compare: 'comparing', }.get(type(node), 'evaluating') source = event.source.get_text_with_indentation(node) plain_prefix = u'!!! When {}: '.format(description) prefix = u'{c.red}{}{c.reset}'.format(plain_prefix, c=self.c) return indented_lines( prefix, source, plain_prefix=plain_prefix ) except Exception: return []
Example #8
Source File: transformers.py From async2rewrite with MIT License | 6 votes |
def ensure_ctx_var(self, coro): d_list = [] for d in coro.decorator_list: if isinstance(d, ast.Attribute): d_list.append(d.attr) elif isinstance(d, ast.Call): if isinstance(d.func, ast.Attribute): d_list.append(d.func.attr) if 'command' not in d_list: return coro coro_args = [arg.arg for arg in coro.args.args] if not coro_args: coro.args.args.append(ast.arg(arg='ctx', annotation=None)) elif 'self' in coro_args and 'ctx' not in coro_args: coro.args.args.insert(1, ast.arg(arg='ctx', annotation=None)) elif 'self' not in coro_args and 'ctx' not in coro_args: coro.args.args.insert(0, ast.arg(arg='ctx', annotation=None)) stats_counter['coro_changes'] += 1 return coro
Example #9
Source File: transformers.py From async2rewrite with MIT License | 6 votes |
def stateful_wait_for(self, call): if isinstance(call.func, ast.Attribute): if call.func.attr in ['wait_for_message', 'wait_for_reaction']: event = call.func.attr.split('_')[2] event = 'message' if event == 'message' else 'reaction_add' call.func.attr = 'wait_for' if call.args: timeout = call.args[0] call.args = [] call.keywords.append(ast.keyword(arg='timeout', value=timeout)) call.args.insert(0, ast.Str(s=event)) for kw in list(call.keywords): if kw.arg != 'check' and kw.arg != 'timeout': call.keywords.remove(kw) warnings.warn('wait_for keyword breaking change detected. Rewrite removes the {} keyword' ' from wait_for.'.format(kw.arg)) elif kw.arg == 'timeout': warnings.warn('wait_for timeout breaking change detected. Timeouts now raise ' 'asyncio.TimeoutError instead of returning None.') stats_counter['call_changes'] += 1 return call
Example #10
Source File: transformers.py From async2rewrite with MIT License | 6 votes |
def stateful_create_channel(self, call): if isinstance(call.func, ast.Attribute): if call.func.attr == 'create_channel': for kw in list(call.keywords): if isinstance(kw.value, ast.Attribute): channel_type = kw.value.attr call.keywords.remove(kw) break else: channel_type = 'text' call.func.attr = 'create_{}_channel'.format(channel_type) guild = find_arg(call, "guild", 0) if guild: call.args = call.args[1:] call.func.value = guild stats_counter['call_changes'] += 1 return call
Example #11
Source File: expression.py From hadrian with Apache License 2.0 | 6 votes |
def _unfold(x, path, state): if isinstance(x, ast.Attribute): path.insert(0, {"string": x.attr}) return _unfold(x.value, path, state) elif isinstance(x, ast.Subscript) and isinstance(x.slice, ast.Index): path.insert(0, _expression(x.slice.value, state)) return _unfold(x.value, path, state) else: if isinstance(x, ast.Name) and x.id in state["cells"]: return _form(state, x.lineno, OrderedDict([("cell", x.id), ("path", path)])) elif isinstance(x, ast.Name) and x.id in state["pools"]: return _form(state, x.lineno, OrderedDict([("pool", x.id), ("path", path)])) else: return _form(state, x.lineno, OrderedDict([("attr", _expression(x, state)), ("path", path)]))
Example #12
Source File: markers.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def do_compare(self, node): def sanity_check(lhsnode, rhsnode): valid = True if isinstance(lhsnode, ast.Str) and isinstance(rhsnode, ast.Str): valid = False #elif (isinstance(lhsnode, ast.Attribute) # and isinstance(rhsnode, ast.Attribute)): # klhs = self.get_attr_key(lhsnode) # krhs = self.get_attr_key(rhsnode) # valid = klhs != krhs if not valid: s = self.get_fragment(node.col_offset) raise SyntaxError('Invalid comparison: %s' % s) lhsnode = node.left lhs = self.evaluate(lhsnode) result = True for op, rhsnode in zip(node.ops, node.comparators): sanity_check(lhsnode, rhsnode) op = op.__class__.__name__.lower() if op not in self.operators: raise SyntaxError('unsupported operation: %r' % op) rhs = self.evaluate(rhsnode) result = self.operators[op](lhs, rhs) if not result: break lhs = rhs lhsnode = rhsnode return result
Example #13
Source File: _ast_to_ir2.py From tmppy with Apache License 2.0 | 5 votes |
def type_factory_method_ast_to_ir2(ast_node: ast.Call, compilation_context: CompilationContext, in_match_pattern: bool, check_var_reference: Callable[[ast.Name], None], match_lambda_argument_names: Set[str], current_stmt_line: int): assert isinstance(ast_node, ast.Call) assert isinstance(ast_node.func, ast.Attribute) assert isinstance(ast_node.func.value, ast.Name) assert ast_node.func.value.id == 'Type' if ast_node.func.attr == 'pointer': return type_pointer_expr_ast_to_ir2(ast_node, compilation_context, in_match_pattern, check_var_reference, match_lambda_argument_names, current_stmt_line) elif ast_node.func.attr == 'reference': return type_reference_expr_ast_to_ir2(ast_node, compilation_context, in_match_pattern, check_var_reference, match_lambda_argument_names, current_stmt_line) elif ast_node.func.attr == 'rvalue_reference': return type_rvalue_reference_expr_ast_to_ir2(ast_node, compilation_context, in_match_pattern, check_var_reference, match_lambda_argument_names, current_stmt_line) elif ast_node.func.attr == 'const': return const_type_expr_ast_to_ir2(ast_node, compilation_context, in_match_pattern, check_var_reference, match_lambda_argument_names, current_stmt_line) elif ast_node.func.attr == 'array': return type_array_expr_ast_to_ir2(ast_node, compilation_context, in_match_pattern, check_var_reference, match_lambda_argument_names, current_stmt_line) elif ast_node.func.attr == 'function': return function_type_expr_ast_to_ir2(ast_node, compilation_context, in_match_pattern, check_var_reference, match_lambda_argument_names, current_stmt_line) elif ast_node.func.attr == 'template_instantiation': return template_instantiation_ast_to_ir2(ast_node, compilation_context, in_match_pattern, check_var_reference, match_lambda_argument_names, current_stmt_line) elif ast_node.func.attr == 'template_member': return template_member_access_ast_to_ir2(ast_node, compilation_context, in_match_pattern, check_var_reference, match_lambda_argument_names, current_stmt_line) else: raise CompilationError(compilation_context, ast_node, 'Undefined Type factory method')
Example #14
Source File: topython.py From pyrser with GNU General Public License v3.0 | 5 votes |
def visit_Call(self, node: parsing.Call) -> ast.expr: """Generates python code calling the function. fn(*args) """ return ast.Call( ast.Attribute( ast.Name('self', ast.Load), node.callObject.__name__, ast.Load()), [ast.Str(param) for param in node.params], [], None, None)
Example #15
Source File: modulefinder.py From ironpython2 with Apache License 2.0 | 5 votes |
def scan_opcodes_cli(self, co): import ast with open(co.co_filename, 'rU') as f: nodes = ast.parse(f.read(), co.co_filename) items = [] class ModuleFinderVisitor(ast.NodeVisitor): def visit_Assign(self, node): for x in node.targets: if isinstance(x, ast.Subscript): if isinstance(x.value, ast.Name): items.append(("store", (x.value.id, ))) elif isinstance(x.value, ast.Attribute): items.append(("store", (x.value.attr, ))) else: print 'Unknown in store: %s' % type(x.value).__name__ elif isinstance(x, ast.Name): items.append(("store", (x.id, ))) def visit_Import(self, node): items.extend([("import", (None, x.name)) for x in node.names]) def visit_ImportFrom(self, node): if node.level == 1: items.append(("relative_import", (node.level, [x.name for x in node.names], node.module))) else: items.extend([("import", ([x.name for x in node.names], node.module))]) v = ModuleFinderVisitor() v.visit(nodes) for what, args in items: yield what, args
Example #16
Source File: _ast_to_ir2.py From tmppy with Apache License 2.0 | 5 votes |
def _is_class_field_initialization(ast_node: ast.AST): return (isinstance(ast_node, ast.Assign) and not ast_node.type_comment and len(ast_node.targets) == 1 and isinstance(ast_node.targets[0], ast.Attribute) and isinstance(ast_node.targets[0].ctx, ast.Store) and isinstance(ast_node.targets[0].value, ast.Name) and ast_node.targets[0].value.id == 'self' and isinstance(ast_node.targets[0].value.ctx, ast.Load))
Example #17
Source File: markers.py From kobo-predict with BSD 2-Clause "Simplified" License | 5 votes |
def get_attr_key(self, node): assert isinstance(node, ast.Attribute), 'attribute node expected' return '%s.%s' % (node.value.id, node.attr)
Example #18
Source File: rewrite.py From python-netsurv with MIT License | 5 votes |
def helper(self, name, *args): """Call a helper in this module.""" py_name = ast.Name("@pytest_ar", ast.Load()) attr = ast.Attribute(py_name, name, ast.Load()) return ast.Call(attr, list(args), [])
Example #19
Source File: symbols.py From importmagic with BSD 2-Clause "Simplified" License | 5 votes |
def visit_Attribute(self, node, chain=False): if isinstance(node.value, ast.Name): self._scope.extend_symbol(node.value.id) self._scope.extend_symbol(node.attr) if not chain: self._scope.end_symbol() elif isinstance(node.value, ast.Attribute): self.visit_Attribute(node.value, chain=True) self._scope.extend_symbol(node.attr, extend_only=True) else: self._scope.end_symbol() self.visit(node.value) self._scope.end_symbol()
Example #20
Source File: raise_visitor.py From darglint with MIT License | 5 votes |
def set_handling(self, attr): # type: (Union[ast.Attribute, ast.Name, ast.Tuple]) -> None self.handling = self._get_attr_name(attr)
Example #21
Source File: raise_visitor.py From darglint with MIT License | 5 votes |
def _get_attr_name(self, attr): # type: (Union[ast.Attribute, ast.Name, ast.Tuple]) -> List[str] curr = attr # type: Any parts = list() # type: List[str] # We assume here that the ast has a limited # depth. Even if it's several thousand long, # it should work fine. while curr: if isinstance(curr, ast.Attribute): parts.append(curr.attr) curr = curr.value elif isinstance(curr, ast.Name): parts.append(curr.id) curr = None elif isinstance(curr, ast.Tuple): names = list() for node in curr.elts: if isinstance(node, ast.Name): names.extend(self._get_attr_name(node)) else: logger.error( 'While getting the names from a caught ' 'tuple of exceptions, encountered ' 'something other than an ast.Name: ' '{}'.format( node.__class__.__name__ ) ) return names else: logger.error( 'While getting ast.Attribute representation ' 'a node had an unexpected type {}'.format( curr.__class__.__name__ ) ) curr = None parts.reverse() return ['.'.join(parts)]
Example #22
Source File: function_description.py From darglint with MIT License | 5 votes |
def _get_exception_name(raises): # type: (ast.Raise) -> str if isinstance(raises.exc, ast.Name): return raises.exc.id elif isinstance(raises.exc, ast.Call): if hasattr(raises.exc.func, 'id'): return getattr(raises.exc.func, 'id') elif hasattr(raises.exc.func, 'attr'): return getattr(raises.exc.func, 'attr') else: logger.debug( 'Raises function call has neither id nor attr.' 'has only: %s' % str(dir(raises.exc.func)) ) elif isinstance(raises.exc, ast.Attribute): return raises.exc.attr elif isinstance(raises.exc, ast.Subscript): id_repr = '' if hasattr(raises.exc.value, 'id'): id_repr = getattr(raises.exc.value, 'id') n_repr = '' if hasattr(raises.exc.slice, 'value'): value = getattr(raises.exc.slice, 'value') if hasattr(value, 'n'): n_repr = getattr(value, 'n') return '{}[{}]'.format( id_repr, n_repr, ) else: logger.debug('Unexpected type in raises expression: {}'.format( raises.exc )) return ''
Example #23
Source File: build-protos.py From mars with Apache License 2.0 | 5 votes |
def visit_Call(self, node): if isinstance(node.func, ast.Attribute) and node.func.attr == 'EnumDescriptor': enum_kw = self._collect_call_kwargs(node) if enum_kw['name'].s == 'OperandType': for op_def in enum_kw['values'].elts: op_kw = self._collect_call_kwargs(op_def) self.operand_codes.append((op_kw['name'].s, op_kw['number'].n)) self.generic_visit(node)
Example #24
Source File: parser.py From resolwe with Apache License 2.0 | 5 votes |
def get_value(self, node): """Convert value from an AST node.""" if not isinstance(node, ast.Attribute): raise TypeError("must be an attribute") if node.value.id != self.choices.__name__: raise TypeError("must be an attribute of {}".format(self.choices.__name__)) return getattr(self.choices, node.attr)
Example #25
Source File: markers.py From jbox with MIT License | 5 votes |
def do_compare(self, node): def sanity_check(lhsnode, rhsnode): valid = True if isinstance(lhsnode, ast.Str) and isinstance(rhsnode, ast.Str): valid = False #elif (isinstance(lhsnode, ast.Attribute) # and isinstance(rhsnode, ast.Attribute)): # klhs = self.get_attr_key(lhsnode) # krhs = self.get_attr_key(rhsnode) # valid = klhs != krhs if not valid: s = self.get_fragment(node.col_offset) raise SyntaxError('Invalid comparison: %s' % s) lhsnode = node.left lhs = self.evaluate(lhsnode) result = True for op, rhsnode in zip(node.ops, node.comparators): sanity_check(lhsnode, rhsnode) op = op.__class__.__name__.lower() if op not in self.operators: raise SyntaxError('unsupported operation: %r' % op) rhs = self.evaluate(rhsnode) result = self.operators[op](lhs, rhs) if not result: break lhs = rhs lhsnode = rhsnode return result
Example #26
Source File: markers.py From jbox with MIT License | 5 votes |
def get_attr_key(self, node): assert isinstance(node, ast.Attribute), 'attribute node expected' return '%s.%s' % (node.value.id, node.attr)
Example #27
Source File: markers.py From recruit with Apache License 2.0 | 5 votes |
def do_compare(self, node): def sanity_check(lhsnode, rhsnode): valid = True if isinstance(lhsnode, ast.Str) and isinstance(rhsnode, ast.Str): valid = False #elif (isinstance(lhsnode, ast.Attribute) # and isinstance(rhsnode, ast.Attribute)): # klhs = self.get_attr_key(lhsnode) # krhs = self.get_attr_key(rhsnode) # valid = klhs != krhs if not valid: s = self.get_fragment(node.col_offset) raise SyntaxError('Invalid comparison: %s' % s) lhsnode = node.left lhs = self.evaluate(lhsnode) result = True for op, rhsnode in zip(node.ops, node.comparators): sanity_check(lhsnode, rhsnode) op = op.__class__.__name__.lower() if op not in self.operators: raise SyntaxError('unsupported operation: %r' % op) rhs = self.evaluate(rhsnode) result = self.operators[op](lhs, rhs) if not result: break lhs = rhs lhsnode = rhsnode return result
Example #28
Source File: markers.py From recruit with Apache License 2.0 | 5 votes |
def get_attr_key(self, node): assert isinstance(node, ast.Attribute), 'attribute node expected' return '%s.%s' % (node.value.id, node.attr)
Example #29
Source File: topython.py From pyrser with GNU General Public License v3.0 | 5 votes |
def visit_Rule(self, node: parsing.Rule) -> ast.expr: """Generates python code calling a rule. self.evalRule('rulename') """ return ast.Call( ast.Attribute(ast.Name('self', ast.Load()), 'evalRule', ast.Load()), [ast.Str(node.name)], [], None, None)
Example #30
Source File: rewrite.py From python-netsurv with MIT License | 5 votes |
def builtin(self, name): """Return the builtin called *name*.""" builtin_name = ast.Name("@py_builtins", ast.Load()) return ast.Attribute(builtin_name, name, ast.Load())