Python ast.Name() Examples

The following are 30 code examples of ast.Name(). 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: setup.py    From pypika with Apache License 2.0 8 votes vote down vote up
def version():
    path = 'pypika/__init__.py'
    with open(path, 'r') as file:
        t = compile(file.read(), path, 'exec', ast.PyCF_ONLY_AST)
        for node in (n for n in t.body if isinstance(n, ast.Assign)):
            if len(node.targets) == 1:
                name = node.targets[0]
                if isinstance(name, ast.Name) and \
                      name.id in ('__version__', '__version_info__', 'VERSION'):
                    v = node.value
                    if isinstance(v, ast.Str):
                        return v.s

                    if isinstance(v, ast.Tuple):
                        r = []
                        for e in v.elts:
                            if isinstance(e, ast.Str):
                                r.append(e.s)
                            elif isinstance(e, ast.Num):
                                r.append(str(e.n))
                        return '.'.join(r) 
Example #2
Source File: Recording.py    From swirlypy with GNU General Public License v3.0 8 votes vote down vote up
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 #3
Source File: checker.py    From linter-pylama with MIT License 7 votes vote down vote up
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 PY2) and isinstance(item, ast.NameConstant):
        # None, True, False are nameconstants in python3, but names in 2
        return item.value
    else:
        return UnhandledKeyType() 
Example #4
Source File: inflect.py    From pybids with MIT License 7 votes vote down vote up
def _get_value_from_ast(self, obj):
        """
        Return the value of the ast object.
        """
        if isinstance(obj, ast.Num):
            return obj.n
        elif isinstance(obj, ast.Str):
            return obj.s
        elif isinstance(obj, ast.List):
            return [self._get_value_from_ast(e) for e in obj.elts]
        elif isinstance(obj, ast.Tuple):
            return tuple([self._get_value_from_ast(e) for e in obj.elts])

        # None, True and False are NameConstants in Py3.4 and above.
        elif sys.version_info.major >= 3 and isinstance(obj, ast.NameConstant):
            return obj.value

        # For python versions below 3.4
        elif isinstance(obj, ast.Name) and (obj.id in ["True", "False", "None"]):
            return string_to_constant[obj.id]

        # Probably passed a variable name.
        # Or passed a single word without wrapping it in quotes as an argument
        # ex: p.inflect("I plural(see)") instead of p.inflect("I plural('see')")
        raise NameError("name '%s' is not defined" % obj.id) 
Example #5
Source File: _analyze.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_Compare(self, node):
        node.obj = bool()
        for n in [node.left] + node.comparators:
            self.visit(n)
        op, arg = node.ops[0], node.comparators[0]
# #         node.expr.target = self.getObj(arg)
# #         arg.target = self.getObj(node.expr)
        # detect specialized case for the test
        if isinstance(op, ast.Eq) and isinstance(node.left, ast.Name):
            # check wether it can be a case
            val = arg.obj
            if isinstance(val, bool):
                val = int(val)  # cast bool to int first
            if isinstance(val, (EnumItemType, int)):
                node.case = (node.left, val)
            # check whether it can be part of an edge check
            n = node.left.id
            if n in self.tree.sigdict:
                sig = self.tree.sigdict[n]
                v = self.getValue(arg)
                if v is not None:
                    if v == 0:
                        node.edge = sig.negedge
                    elif v == 1:
                        node.edge = sig.posedge 
Example #6
Source File: _analyze.py    From myhdl with GNU Lesser General Public License v2.1 6 votes vote down vote up
def visit_If(self, node):
        node.ignore = False
        if not node.orelse:
            test = node.test
            if isinstance(test, ast.Name):
                if test.id == '__debug__':
                    node.ignore = True
                    return  # skip
        self.generic_visit(node)

        # add fields that match old compiler package
        tests = [(node.test, node.body)]
        else_ = []
        self.flattenIf(node.orelse, tests, else_, node.body[0].col_offset)
        node.tests = tests
        node.else_ = else_ 
Example #7
Source File: action.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def visit_Call(self, node, return_task=False):
        sub_node = node.func
        while not isinstance(sub_node, ast.Name):
            sub_node = sub_node.value
        py_object = eval(compile(ast.Expression(sub_node), "", "eval"), self._globals)
        if py_object == CalmTask or isinstance(py_object, EntityType):
            task = eval(compile(ast.Expression(node), "", "eval"), self._globals)
            if task is not None and isinstance(task, TaskType):
                if self.target is not None and not task.target_any_local_reference:
                    task.target_any_local_reference = self.target
                if return_task:
                    return task
                self.task_list.append(task)
                self.all_tasks.append(task)
                return
        return self.generic_visit(node) 
Example #8
Source File: expression.py    From hadrian with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: upgrade_stdmodule.py    From pyGSTi with Apache License 2.0 6 votes vote down vote up
def pre_Assign(self):
        value = self.cur_node.value
        for target in self.cur_node.targets:
            # ignore Subscripts for now
            if isinstance(target, _ast.Name):
                if target.id == '_target_model':
                    assert(isinstance(value, _ast.Call))
                    # done in three separate phases for safety with stringly-typed arguments
                    StateSpaceLabelWalker(value.args[0])
                    LabelWalker(value.args[1])
                    ExpressionWalker(value.args[2])
                else:
                    LabelWalker(value)

                # Build dependencies from the rhs
                # We don't consider the function name a dependency so bypass that
                critical_ast = value.args if isinstance(value, _ast.Call) else value
                value._dependencies = DependencyWalker(critical_ast).dependencies
                self.upgrades[target.id] = value

        return False


# Build variables for filling in the template 
Example #10
Source File: test_flattening.py    From sspam with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_noflattening(self):
        'Tests where nothing should be flattened'
        corresp = [(["a + b", "b + a"],
                   ast.BinOp(ast.Name('a', ast.Load()),
                             ast.Add(),
                             ast.Name('b', ast.Load()))),
                   (["c*d", "d*c"],
                    ast.BinOp(ast.Name('c', ast.Load()),
                              ast.Mult(),
                              ast.Name('d', ast.Load()))),
                   (["a + c*d", "d*c + a"],
                    ast.BinOp(ast.Name('a', ast.Load()), ast.Add(),
                              ast.BinOp(ast.Name('c', ast.Load()), ast.Mult(),
                                        ast.Name('d', ast.Load()))))]
        for refstring, result in corresp:
            self.generic_flattening(refstring, result) 
Example #11
Source File: cmd.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
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 #12
Source File: expressionfunction.py    From pyDcop with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def visit(self, node) -> Any:
        if isinstance(node, ast.Name):
            if isinstance(node.ctx, ast.Load):
                self.loaded.add(node.id)
            elif isinstance(node.ctx, ast.Store):
                self.stored.add(node.id)
        elif isinstance(node, ast.Return):
            self.has_return = True
        # We must keep track of importer name in order to avoid considering as variable
        # names:
        elif isinstance(node, ast.Import):
            self.imported.update([ n.name for n in node.names])
        elif isinstance(node, ast.ImportFrom):
            self.imported.update([ n.name for n in node.names])

        self.generic_visit(node) 
Example #13
Source File: expr.py    From recruit with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: pytables.py    From recruit with Apache License 2.0 6 votes vote down vote up
def visit_Attribute(self, node, **kwargs):
        attr = node.attr
        value = node.value

        ctx = node.ctx.__class__
        if ctx == ast.Load:
            # resolve the value
            resolved = self.visit(value)

            # try to get the value to see if we are another expression
            try:
                resolved = resolved.value
            except (AttributeError):
                pass

            try:
                return self.term_type(getattr(resolved, attr), 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 #15
Source File: checker.py    From linter-pylama with MIT License 6 votes vote down vote up
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,)) 
Example #16
Source File: asttools.py    From sspam with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visit_UnaryOp(self, node):
        'Replace bitwise unaryop with function call'
        self.generic_visit(node)
        if isinstance(node.op, ast.Invert):
            return ast.Call(ast.Name('mnot', ast.Load()),
                            [node.operand], [], None, None)
        return node 
Example #17
Source File: pattern_matcher.py    From sspam with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_twomult(self, target, pattern):
        'Check 2*... pattern that could be in another form'
        if isinstance(pattern.left, ast.Num) and pattern.left.n == 2:
            operand = pattern.right
        elif isinstance(pattern.right, ast.Num) and pattern.right.n == 2:
            operand = pattern.left
        else:
            return False

        # deal with case where wildcard operand and target are const values
        if isinstance(target, ast.Num) and isinstance(operand, ast.Name):
            conds = (operand.id in self.wildcards and
                     isinstance(self.wildcards[operand.id], ast.Num))
            if conds:
                eva = (self.wildcards[operand.id].n)*2 % 2**(self.nbits)
                if eva == target.n:
                    return True
            else:
                if target.n % 2 == 0:
                    self.wildcards[operand.id] = ast.Num(target.n / 2)
                    return True
                return False

        # get all wildcards in operand and check if they have value
        getwild = asttools.GetIdentifiers()
        getwild.visit(operand)
        wilds = getwild.variables
        for wil in wilds:
            if wil not in self.wildcards:
                return False
        return self.check_eq_z3(target, pattern) 
Example #18
Source File: markers.py    From jbox with MIT License 5 votes vote down vote up
def do_attribute(self, node):
        if not isinstance(node.value, ast.Name):
            valid = False
        else:
            key = self.get_attr_key(node)
            valid = key in self.context or key in self.allowed_values
        if not valid:
            raise SyntaxError('invalid expression: %s' % key)
        if key in self.context:
            result = self.context[key]
        else:
            result = self.allowed_values[key]
        return result 
Example #19
Source File: workspace.py    From typhon with MIT License 5 votes vote down vote up
def execute_controlfile(self, name):
        """ Execute controlfile or agenda on workspace.

        This method looks recursively for a controlfile with the given name in the current
        directory and the arts include path. If such a file has been found it will be parsed
        and executed on the workspace.

        Args:

            name(str): Name of the controlfile

        Raises:

            Exception: If parsing of the controlfile fails.

        Returns:

            The controlfile as parsed Agenda object.

        """

        if not name in imports:
            agenda = Agenda.parse(name)
            imports[name] = agenda
        else:
            agenda = imports[name]

        self.execute_agenda(agenda)

        return agenda 
Example #20
Source File: workspace.py    From typhon with MIT License 5 votes vote down vote up
def __getattr__(self, name):
        """ Lookup the given variable in the local variables and the ARTS workspace.

        Args:
            name(str): Name of the attribute (variable)

        Raises:
            ValueError: If the variable is not found.
        """

        group_id = None
        if name in self._vars:
            var = self._vars[name]
            var.update()
            return var
        else:
            i = arts_api.lookup_workspace_variable(name.encode())
            if i < 0:
                raise AttributeError("No workspace variable " + str(name) + " found.")
            vs = arts_api.get_variable(i)
            group_id    = vs.group
            description = vs.description.decode("utf8")

        # Get its symbolic representation
        wsv = WorkspaceVariable(i, name, group_names[group_id], description, self)
        return wsv 
Example #21
Source File: asttools.py    From sspam with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visit_Call(self, node):
        'Replace custom function with bitwise operators'
        self.generic_visit(node)
        if isinstance(node.func, ast.Name):
            if len(node.args) == 2:
                if node.func.id == "mand":
                    op = ast.BitAnd()
                elif node.func.id == "mxor":
                    op = ast.BitXor()
                elif node.func.id == "mor":
                    op = ast.BitOr()
                elif node.func.id == "mlshift":
                    op = ast.LShift()
                elif node.func.id == "mrshift":
                    op = ast.RShift()
                else:
                    return node

                return ast.BinOp(node.args[0],
                                 op,
                                 node.args[1])

            elif len(node.args) == 1 and node.func.id == "mnot":
                arg = node.args[0]
                self.generic_visit(node)
                return ast.UnaryOp(ast.Invert(), arg)

        return self.generic_visit(node) 
Example #22
Source File: symbols.py    From importmagic with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 #23
Source File: expr.py    From recruit with Apache License 2.0 5 votes vote down vote up
def visit_Assign(self, node, **kwargs):
        """
        support a single assignment node, like

        c = a + b

        set the assigner at the top level, must be a Name node which
        might or might not exist in the resolvers

        """

        if len(node.targets) != 1:
            raise SyntaxError('can only assign a single expression')
        if not isinstance(node.targets[0], ast.Name):
            raise SyntaxError('left hand side of an assignment must be a '
                              'single name')
        if self.env.target is None:
            raise ValueError('cannot assign without a target object')

        try:
            assigner = self.visit(node.targets[0], **kwargs)
        except UndefinedVariableError:
            assigner = node.targets[0].id

        self.assigner = getattr(assigner, 'name', assigner)
        if self.assigner is None:
            raise SyntaxError('left hand side of an assignment must be a '
                              'single resolvable name')

        return self.visit(node.value, **kwargs) 
Example #24
Source File: index.py    From importmagic with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visit_Assign(self, node):
        # TODO: Handle __all__
        is_name = lambda n: isinstance(n, ast.Name)
        for name in filter(is_name, node.targets):
            if name.id == '__all__' and isinstance(node.value, ast.List):
                for subnode in node.value.elts:
                    if isinstance(subnode, ast.Str):
                        self._tree.add_explicit_export(subnode.s, 1.2)
            elif not name.id.startswith('_'):
                self._tree.add(name.id, 1.1) 
Example #25
Source File: config_scope.py    From sacred with MIT License 5 votes vote down vote up
def add_doc(target, variables, body_lines):
    if isinstance(target, ast.Name):
        # if it is a variable name add it to the doc
        name = target.id
        if name not in variables:
            doc = find_doc_for(target, body_lines)
            if doc is not None:
                variables[name] = doc
    elif isinstance(target, ast.Tuple):
        # if it is a tuple then iterate the elements
        # this can happen like this:
        # a, b = 1, 2
        for e in target.elts:
            add_doc(e, variables, body_lines) 
Example #26
Source File: helper.py    From YAPyPy with MIT License 5 votes vote down vote up
def atom_rewrite(loc, name, token, value, number, strs, namedc, ellipsis, dict, is_dict,
                 is_gen, is_list, comp, yield_expr):
    if name:
        if not token:
            return ast.Name(name.value, ast.Load(), **loc @ name)
        return ex_ast.AssignExpr(
            ast.Name(name.value, ast.Store(), **loc @ name), value=value, **loc @ token)

    if number:
        return ast.Num(eval(number.value), **loc @ number)

    if strs:
        return str_maker(*strs)

    if ellipsis:
        return ast.Ellipsis()

    if namedc:
        return ast.NameConstant(eval(namedc.value), **loc @ namedc)

    if is_dict:
        return dict or ex_ast.ExDict([], [], ast.Load(), **loc @ is_dict)

    if is_gen:
        if yield_expr:
            return yield_expr
        return comp(is_tuple=True) if comp else ast.Tuple([], ast.Load(), **loc @ is_gen)

    if is_list:
        return comp(is_list=True) if comp else ast.List([], ast.Load(), **loc @ is_list)

    raise TypeError 
Example #27
Source File: exception_trace.py    From clikit with MIT License 5 votes vote down vote up
def _format_tree(self, tree, source, io):
        offset = 0
        chunks = []

        nodes = [n for n in ast.walk(tree)]

        displayed_nodes = []

        for node in nodes:
            nodecls = node.__class__
            nodename = nodecls.__name__

            if "col_offset" not in dir(node):
                continue

            if nodecls in self.AST_ELEMENTS["keywords"]:
                displayed_nodes.append((node, nodename.lower(), "keyword"))
            elif nodecls == ast.Name and node.id in self.AST_ELEMENTS["builtins"]:
                displayed_nodes.append((node, node.id, "builtin"))
            elif nodecls == ast.Str:
                displayed_nodes.append((node, "'{}'".format(node.s), "literal"))
            elif nodecls == ast.Num:
                displayed_nodes.append((node, str(node.n), "literal"))

        displayed_nodes.sort(key=lambda elem: elem[0].col_offset)

        for dn in displayed_nodes:
            node = dn[0]
            s = dn[1]
            theme = dn[2]

            begin_col = node.col_offset

            src_chunk = source[offset:begin_col]
            chunks.append(src_chunk)
            chunks.append(io.format("{}{}</>".format(self.THEME[theme], s)))
            offset = begin_col + len(s)

        chunks.append(source[offset:])

        return "".join(chunks) 
Example #28
Source File: symbol_analyzer.py    From YAPyPy with MIT License 5 votes vote down vote up
def _visit_name(self, node: ast.Name):
    symtable = self.symtable
    name = node.id
    if isinstance(node.ctx, ast.Store):
        symtable.entered.add(name)
    elif isinstance(node.ctx, ast.Load):
        symtable.requires.add(name)
    return node 
Example #29
Source File: rewrite.py    From python-netsurv with MIT License 5 votes vote down vote up
def assign(self, expr):
        """Give *expr* a name."""
        name = self.variable()
        self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))
        return ast.Name(name, ast.Load()) 
Example #30
Source File: utils.py    From pyungo with MIT License 5 votes vote down vote up
def get_function_return_names(fct):
    """ Return variable name(s) or return statement of the given function """
    lines = inspect.getsourcelines(fct)
    outputs = None
    for line in lines[0][::-1]:
        stripped = line.strip()
        if "def" in stripped:
            # NOTE: This work as def is a reserved keyword which will trigger
            # invalid syntax if misused
            msg = "No return statement found in {}"
            raise PyungoError(msg.format(fct.__name__))
        ast_tree = ast.parse(stripped)
        for ast_node in ast.walk(ast_tree):
            if isinstance(ast_node, ast.Return):
                if isinstance(ast_node.value, ast.Name):
                    outputs = [ast_node.value.id]
                elif isinstance(ast_node.value, ast.Tuple):
                    outputs = [
                        elt.id
                        for elt in ast_node.value.elts
                        if isinstance(elt, ast.Name)
                    ]
                else:
                    name = ast_node.value.__class__.__name__
                    msg = (
                        "Variable name or Tuple of variable names are "
                        "expected, got {}".format(name)
                    )
                    raise PyungoError(msg)
                break
        if outputs:
            break
    return outputs