當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。