当前位置: 首页>>代码示例>>Python>>正文


Python ast.Attribute方法代码示例

本文整理汇总了Python中ast.Attribute方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Attribute方法的具体用法?Python ast.Attribute怎么用?Python ast.Attribute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.Attribute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: visit_FunctionDef

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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() 
开发者ID:myhdl,项目名称:myhdl,代码行数:23,代码来源:_analyze.py

示例2: _unfold

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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)])) 
开发者ID:modelop,项目名称:hadrian,代码行数:18,代码来源:expression.py

示例3: _apply_imports_to_unparsed_expression

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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 
开发者ID:luci,项目名称:recipes-py,代码行数:23,代码来源:cmd.py

示例4: visit_Expr

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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 
开发者ID:alexander-bauer,项目名称:swirlypy,代码行数:19,代码来源:Recording.py

示例5: ensure_ctx_var

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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 
开发者ID:tylergibbs2,项目名称:async2rewrite,代码行数:26,代码来源:transformers.py

示例6: stateful_wait_for

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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 
开发者ID:tylergibbs2,项目名称:async2rewrite,代码行数:25,代码来源:transformers.py

示例7: stateful_create_channel

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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 
开发者ID:tylergibbs2,项目名称:async2rewrite,代码行数:19,代码来源:transformers.py

示例8: visit_Attribute

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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__)) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:21,代码来源:expr.py

示例9: format_executing_node_exception

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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 [] 
开发者ID:alexmojaki,项目名称:snoop,代码行数:24,代码来源:formatting.py

示例10: visit_Hook

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
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) 
开发者ID:LionelAuroux,项目名称:pyrser,代码行数:20,代码来源:topython.py

示例11: filterstr_to_filterfunc

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
def filterstr_to_filterfunc(filter_str: str, item_type: type):
    """Takes an --post-filter=... or --storyitem-filter=... filter
     specification and makes a filter_func Callable out of it."""

    # The filter_str is parsed, then all names occurring in its AST are replaced by loads to post.<name>. A
    # function Post->bool is returned which evaluates the filter with the post as 'post' in its namespace.

    class TransformFilterAst(ast.NodeTransformer):
        def visit_Name(self, node: ast.Name):
            # pylint:disable=no-self-use
            if not isinstance(node.ctx, ast.Load):
                raise InvalidArgumentException("Invalid filter: Modifying variables ({}) not allowed.".format(node.id))
            if node.id == "datetime":
                return node
            if not hasattr(item_type, node.id):
                raise InvalidArgumentException("Invalid filter: {} not a {} attribute.".format(node.id,
                                                                                               item_type.__name__))
            new_node = ast.Attribute(ast.copy_location(ast.Name('item', ast.Load()), node), node.id,
                                     ast.copy_location(ast.Load(), node))
            return ast.copy_location(new_node, node)

    input_filename = '<command line filter parameter>'
    compiled_filter = compile(TransformFilterAst().visit(ast.parse(filter_str, filename=input_filename, mode='eval')),
                              filename=input_filename, mode='eval')

    def filterfunc(item) -> bool:
        # pylint:disable=eval-used
        return bool(eval(compiled_filter, {'item': item, 'datetime': datetime.datetime}))

    return filterfunc 
开发者ID:instaloader,项目名称:instaloader,代码行数:32,代码来源:__main__.py

示例12: _has_attr_call

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
def _has_attr_call(node, attr_name):
    return (
        isinstance(node.left, ast.Attribute)
        and node.left.attr == attr_name
    ) 
开发者ID:devmanorg,项目名称:fiasko_bro,代码行数:7,代码来源:ast_nodes_validators.py

示例13: find_method_calls

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
def find_method_calls(tree, attr_name):
    attributes = [node for node in ast.walk(tree) if isinstance(node, ast.Attribute)]
    return attr_name in {a.attr for a in attributes} 
开发者ID:devmanorg,项目名称:fiasko_bro,代码行数:5,代码来源:ast_helpers.py

示例14: get_base_assign_value_name

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
def get_base_assign_value_name(node):
    """
        Base.foo().bar --> 'Base'
    """
    current_node = node
    while True:
        if isinstance(current_node, ast.Attribute):
            current_node = current_node.value
        elif isinstance(current_node, ast.Call):
            current_node = current_node.func
        else:
            break
    return getattr(current_node, 'id', None) 
开发者ID:devmanorg,项目名称:fiasko_bro,代码行数:15,代码来源:ast_helpers.py

示例15: has_exit_calls

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Attribute [as 别名]
def has_exit_calls(function_definition):
    calls = [c for c in ast.walk(function_definition)
             if isinstance(c, ast.Call) and hasattr(c, 'func')]
    has_plain_exit_calls = any(
        [c.func.id == 'exit' for c in calls if isinstance(c.func, ast.Name)]
    )
    has_sys_exit_calls = any(
        [hasattr(c.func.value, 'id') and
         c.func.value.id == 'sys' and
         c.func.attr == 'exit' for c in calls if isinstance(c.func, ast.Attribute)]
    )
    return has_plain_exit_calls or has_sys_exit_calls 
开发者ID:devmanorg,项目名称:fiasko_bro,代码行数:14,代码来源:ast_helpers.py


注:本文中的ast.Attribute方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。