當前位置: 首頁>>代碼示例>>Python>>正文


Python _ast.Name方法代碼示例

本文整理匯總了Python中_ast.Name方法的典型用法代碼示例。如果您正苦於以下問題:Python _ast.Name方法的具體用法?Python _ast.Name怎麽用?Python _ast.Name使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在_ast的用法示例。


在下文中一共展示了_ast.Name方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: visit_augassign

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def visit_augassign(self, node: _ast.AugAssign):  # target, op, value
        value = self._run(node.value)
        target = node.target
        target_cls = target.__class__
        op_cls = node.op.__class__

        if target_cls == _ast.Name:
            target_id = target.id  # type: ignore
            self.symbol_table[target_id] = BINOP_TABLE[op_cls](
                self.symbol_table[target_id], value,
            )
        elif target_cls == _ast.Subscript:
            sym = self._run(target.value)  # type: ignore
            xslice = self._run(target.slice)  # type: ignore
            if isinstance(target.slice, _ast.Index):  # type: ignore
                sym[xslice] = BINOP_TABLE[op_cls](sym[xslice], value,)
            else:
                raise BadSyntax('This assign method is not allowed')
        else:
            raise BadSyntax('This assign method is not allowed')
        return 
開發者ID:item4,項目名稱:yui,代碼行數:23,代碼來源:calc.py

示例2: setup_py

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def setup_py(location: str) -> dict:
    """Returns back any configuration info we are able to determine from a setup.py file"""
    setup_config = {}
    try:
        with open(location) as setup_py_file:
            for node in ast.walk(ast.parse(setup_py_file.read())):
                if (
                    type(node) == _ast.Call
                    and type(getattr(node, "func", None)) == _ast.Name
                    and node.func.id == "setup"  # type: ignore
                ):
                    for keyword in node.keywords:  # type: ignore
                        if keyword.arg == "packages":
                            setup_config["modules"] = ast.literal_eval(keyword.value)
                            break
                    break
    except Exception as error:
        warnings.warn(f"Error ({error}) occurred trying to parse setup.py file: {location}")

    return setup_config 
開發者ID:timothycrosley,項目名稱:portray,代碼行數:22,代碼來源:config.py

示例3: get_node_args_and_keywords

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def get_node_args_and_keywords(assigned_objs, assignments, selector=None):
    referenced_nodes = set([])
    selector_line = -1
    assignment_nodes = []
    for node in assignments:
        for i in walk_tree(node):
            if i and isinstance(i, (_ast.keyword, _ast.Name)) and 'id' in i.__dict__:
                if i.id == selector:
                    selector_line = i.lineno
                elif i.lineno == selector_line:
                    referenced_nodes.add(i.id)
    for node in assigned_objs:
        for target in node.targets:
            if getattr(target, 'id', None) in referenced_nodes:
                assignment_nodes.append(node)
    return assignment_nodes 
開發者ID:Chris7,項目名稱:django-djangui,代碼行數:18,代碼來源:source_parser.py

示例4: visit_Name

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def visit_Name( self, node ):
    new_node = LocalVar( id=node.id )
    new_node._name = node.id
    return ast.copy_location( new_node, node )


#-------------------------------------------------------------------------
# ReorderAST
#-------------------------------------------------------------------------
# Reorders an AST branch beginning with the indicated node.  Intended
# for inverting the order of Name/Attribute chains so that the Name
# node comes first, followed by chains of Attribute/Subscript nodes.
#
# This visitor will also insert Self nodes to represent references to the
# self variable, and remove Index nodes which seem to serve no useful
# purpose. 
開發者ID:cornell-brg,項目名稱:pymtl,代碼行數:18,代碼來源:ast_transformer.py

示例5: reverse

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def reverse( self, tree ):
    # Visit the tree
    self.visit( tree )

    # The top of the stack is the new root of the tree
    current = new_root = self.stack.pop()
    name    = [current._name]

    # Pop each node off the stack, update pointers
    while self.stack:
      next_         = self.stack.pop()
      current.value = next_
      current       = next_
      name.append( current._name )

    # Name generation
    new_root._name = '.'.join( name ).replace('.[', '[')

    # Update the last pointer to None, return the new_root
    current.value = None
    return new_root 
開發者ID:cornell-brg,項目名稱:pymtl,代碼行數:23,代碼來源:ast_transformer.py

示例6: visit_Attribute

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def visit_Attribute( self, node ):

    # Visit children
    self.generic_visit( node )

    # If the direct child of this attribute was a portbundle then the node
    # will be removed by the visitor. We must update our name to include
    # portbundle name for proper mangling.
    if self.portbundle:
      new_node = _ast.Name( id  = '{}_{}'.format(self.portbundle, node.attr ),
                            ctx = node.ctx )
      new_node._object = node._object
      node = new_node

    # Attribute is a PortBundle, remove the node, set the submodule name
    if isinstance( node._object, PortBundle ):
      self.portbundle = node.attr
      return None

    # Otherwise, clear the submodule name, return node unmodified
    self.portbundle = None
    return ast.copy_location( node, node ) 
開發者ID:cornell-brg,項目名稱:pymtl,代碼行數:24,代碼來源:visitors.py

示例7: convert_to_value

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def convert_to_value(item):
    if isinstance(item, ast.Str):
        return item.s
    elif hasattr(ast, 'Bytes') and isinstance(item, ast.Bytes):
        return item.s
    elif isinstance(item, ast.Tuple):
        return tuple(convert_to_value(i) for i in item.elts)
    elif isinstance(item, ast.Num):
        return item.n
    elif isinstance(item, ast.Name):
        result = VariableKey(item=item)
        constants_lookup = {
            'True': True,
            'False': False,
            'None': None,
        }
        return constants_lookup.get(
            result.name,
            result,
        )
    elif (not PY33) and isinstance(item, ast.NameConstant):
        # None, True, False are nameconstants in python3, but names in 2
        return item.value
    else:
        return UnhandledKeyType() 
開發者ID:zrzka,項目名稱:blackmamba,代碼行數:27,代碼來源:checker.py

示例8: NAME

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def NAME(self, node):
        """
        Handle occurrence of Name (which can be a load/store/delete access.)
        """
        # Locate the name in locals / function / globals scopes.
        if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
            self.handleNodeLoad(node)
            if (node.id == 'locals' and isinstance(self.scope, FunctionScope)
                    and isinstance(node.parent, ast.Call)):
                # we are doing locals() call in current scope
                self.scope.usesLocals = True
        elif isinstance(node.ctx, (ast.Store, ast.AugStore)):
            self.handleNodeStore(node)
        elif isinstance(node.ctx, ast.Del):
            self.handleNodeDelete(node)
        else:
            # must be a Param context -- this only happens for names in function
            # arguments, but these aren't dispatched through here
            raise RuntimeError("Got impossible expression context: %r" % (node.ctx,)) 
開發者ID:zrzka,項目名稱:blackmamba,代碼行數:21,代碼來源:checker.py

示例9: _list_tasks

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def _list_tasks():
    """
    Fetches a list of all valid tasks that may be run, and the args they
    accept. Does not actually import the task module to prevent errors if a
    user does not have the dependencies installed for every task.

    :return:
        A list of 2-element tuples:
         0: a unicode string of the task name
         1: a list of dicts containing the parameter definitions
    """

    out = []
    dev_path = os.path.join(package_root, 'dev')
    for fname in sorted(os.listdir(dev_path)):
        if fname.startswith('.') or fname.startswith('_'):
            continue
        if not fname.endswith('.py'):
            continue
        name = fname[:-3]
        args = ()

        full_path = os.path.join(package_root, 'dev', fname)
        with open(full_path, 'rb') as f:
            full_code = f.read()
            if sys.version_info >= (3,):
                full_code = full_code.decode('utf-8')

        task_node = ast.parse(full_code, filename=full_path)
        for node in ast.iter_child_nodes(task_node):
            if isinstance(node, _ast.Assign):
                if len(node.targets) == 1 \
                        and isinstance(node.targets[0], _ast.Name) \
                        and node.targets[0].id == 'run_args':
                    args = ast.literal_eval(node.value)
                    break

        out.append((name, args))
    return out 
開發者ID:wbond,項目名稱:oscrypto,代碼行數:41,代碼來源:_task.py

示例10: visit_Slice

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def visit_Slice(self, node):
        if node.lower is not None:
            self.visit(node.lower)
        self.write(":")
        if node.upper is not None:
            self.visit(node.upper)
        if node.step is not None:
            self.write(":")
            if not (isinstance(node.step, Name) and node.step.id == "None"):
                self.visit(node.step) 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:12,代碼來源:_ast_util.py

示例11: make_expr

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def make_expr(i, bytecode, context=None):
    if context is None:
      context = _ast.Load()

    op = bytecode[i][2]
    if op == LOAD_CONST:
      return Statement.make_const(i, bytecode)
    elif op in (LOAD_GLOBAL, LOAD_NAME, LOAD_FAST,        \
                STORE_GLOBAL, STORE_NAME, STORE_FAST,     \
                DELETE_GLOBAL, DELETE_NAME, DELETE_FAST):
      return Statement.make_name(i, bytecode, context=context)
    elif op in (LOAD_ATTR, STORE_ATTR, DELETE_ATTR):
      return Statement.make_attribute(i, bytecode, context=context)
    elif op in CALL_OPCODES:
      return Statement.make_call(i, bytecode)
    elif op in BINARY_OP_OPCODES:
      return Statement.make_binary_op(i, bytecode)
    elif op in (BUILD_TUPLE, BUILD_LIST):
      return Statement.make_tuple_list(i, bytecode)
    elif op in (STORE_MAP, BUILD_MAP):
      return Statement.make_dict(i, bytecode)
    elif op in (STORE_SUBSCR, BINARY_SUBSCR):
      return Statement.make_subscript(i, bytecode)
    elif op in STORE_SLICE_OPCODES or op in DELETE_SLICE_OPCODES:
      return Statement.make_store_delete_slice(i, bytecode)
    elif op == BUILD_SLICE:
      return Statement.make_slice(i, bytecode)

    logger.debug("Unhandled >> EXPR:\n%s", show_bytecode(bytecode[:i + 1]))

    # if we don't translate it, we generate a new named expr.
    Statement.UNDEFINED_COUNT += 1
    return i, _ast.Name('Undef_%d' % Statement.UNDEFINED_COUNT, _ast.Load()) 
開發者ID:neuroo,項目名稱:equip,代碼行數:35,代碼來源:stmt.py

示例12: make_binary_op

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def make_binary_op(i, bytecode):
    op = bytecode[i][2]
    bin_op = Statement.BIN_OP_AST_NODE_MAP[op]()
    i, rhs = Statement.make_expr(i - 1, bytecode)
    i, lhs = Statement.make_expr(i - 1, bytecode)
    return i, _ast.BinOp(lhs, bin_op, rhs)


  # Build Attr(value=Attr(value=Name(id=a), attr=b), attr=c) <=> a.b.c 
開發者ID:neuroo,項目名稱:equip,代碼行數:11,代碼來源:stmt.py

示例13: make_name

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def make_name(i, bytecode, context=None):
    arg = bytecode[i][3]
    if context is None:
      context = _ast.Load()
    return i, _ast.Name(arg, context) 
開發者ID:neuroo,項目名稱:equip,代碼行數:7,代碼來源:stmt.py

示例14: assign

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def assign(self, node, val):
        cls = node.__class__

        if cls == _ast.Name:
            self.symbol_table[node.id] = val
        elif cls in (_ast.Tuple, _ast.List):
            if not isinstance(val, abc.Iterable):
                raise TypeError(
                    'cannot unpack non-iterable {} object'.format(
                        type(val).__name__,
                    )
                )
            for telem, tval in itertools.zip_longest(
                node.elts, val, fillvalue=PLACEHOLDER,
            ):
                if telem == PLACEHOLDER:
                    raise ValueError('not enough values to unpack')
                if tval == PLACEHOLDER:
                    raise ValueError('too many values to unpack')
                self.assign(telem, tval)
        elif cls == _ast.Subscript:
            sym = self._run(node.value)
            xslice = self._run(node.slice)
            if isinstance(node.slice, _ast.Index):
                sym[xslice] = val
            elif isinstance(node.slice, _ast.Slice):
                sym[slice(xslice.start, xslice.stop)] = val
            elif isinstance(node.slice, _ast.ExtSlice):
                sym[xslice] = val
        else:
            raise BadSyntax('This assign method is not allowed') 
開發者ID:item4,項目名稱:yui,代碼行數:33,代碼來源:calc.py

示例15: delete

# 需要導入模塊: import _ast [as 別名]
# 或者: from _ast import Name [as 別名]
def delete(self, node):
        cls = node.__class__

        if cls == _ast.Name:
            del self.symbol_table[node.id]
        elif cls == _ast.Tuple:
            for elt in node.elts:
                self.delete(elt) 
開發者ID:item4,項目名稱:yui,代碼行數:10,代碼來源:calc.py


注:本文中的_ast.Name方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。