Python ast.NameConstant() Examples

The following are 30 code examples of ast.NameConstant(). 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: 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 #2
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 #3
Source File: keywords.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def _check_last_return_in_function(self, node: ast.Return) -> None:
        parent = get_parent(node)
        if not isinstance(parent, FunctionNodes):
            return

        returns = len(tuple(filter(
            lambda return_node: return_node.value is not None,
            walk.get_subnodes_by_type(parent, ast.Return),
        )))

        last_value_return = (
            len(parent.body) > 1 and
            returns < 2 and
            isinstance(node.value, ast.NameConstant) and
            node.value.value is None
        )

        one_return_with_none = (
            returns == 1 and
            isinstance(node.value, ast.NameConstant) and
            node.value.value is None
        )

        if node.value is None or last_value_return or one_return_with_none:
            self.add_violation(InconsistentReturnViolation(node)) 
Example #4
Source File: injection_shell.py    From bandit with Apache License 2.0 6 votes vote down vote up
def has_shell(context):
    keywords = context.node.keywords
    result = False
    if 'shell' in context.call_keywords:
        for key in keywords:
            if key.arg == 'shell':
                val = key.value
                if isinstance(val, ast.Num):
                    result = bool(val.n)
                elif isinstance(val, ast.List):
                    result = bool(val.elts)
                elif isinstance(val, ast.Dict):
                    result = bool(val.keys)
                elif isinstance(val, ast.Name) and val.id in ['False', 'None']:
                    result = False
                elif not six.PY2 and isinstance(val, ast.NameConstant):
                    result = val.value
                else:
                    result = True
    return result 
Example #5
Source File: inflect.py    From bazarr with GNU General Public License v3.0 6 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 #6
Source File: tree.py    From dlint with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def kwarg_primitive(call, kwarg_name, primitive):
    try:
        # Python 3
        primitive_type = ast.NameConstant

        def comparator(keyword, inner_primitive):
            return (
                isinstance(keyword.value, primitive_type)
                and keyword.value.value == inner_primitive
            )
    except AttributeError:
        # Python 2, AttributeError on ast.NameConstant
        primitive_type = ast.Name

        def comparator(keyword, inner_primitive):
            return (
                isinstance(keyword.value, primitive_type)
                and keyword.value.id == str(inner_primitive)
            )

    return any(
        keyword.arg == kwarg_name
        and comparator(keyword, primitive)
        for keyword in call.keywords
    ) 
Example #7
Source File: inflect.py    From grabbit with MIT License 6 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 #8
Source File: expressions.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 6 votes vote down vote up
def stringify_node(self, node: Any) -> str:
        if hasattr(node, 'first_token') and hasattr(node, 'last_token'):
            return self.code[node.first_token.startpos:node.last_token.endpos]

        if isinstance(node, ast.NameConstant):
            return str(node.value)
        if isinstance(node, ast.Str):
            return "'" + node.s.replace("'", "''") + "'"
        if isinstance(node, ast.Num):
            return str(node.n)
        if isinstance(node, ast.BinOp):
            left = self.stringify_node(node.left)
            right = self.stringify_node(node.right)
            op = self.stringify_operation(node.op)
            return f'{left} {op} {right}'

        return str(node) 
Example #9
Source File: python2ir.py    From ppci with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_ty(self, annotation) -> ir.Typ:
        """ Get the type based on type annotation """
        if isinstance(annotation, type):
            type_name = annotation.__name__
        elif annotation is None:
            return
        else:
            if (
                isinstance(annotation, ast.NameConstant)
                and annotation.value is None
            ):
                return
            type_name = annotation.id

        if type_name in self.type_mapping:
            return self.type_mapping[type_name]
        else:
            self.error(annotation, "Unhandled type: {}".format(type_name)) 
Example #10
Source File: functions.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def _check_boolean_arguments(self, node: ast.Call) -> None:
        if len(node.args) == 1 and not node.keywords:
            return  # Calls with single boolean argument are allowed

        for arg in node.args:
            if not isinstance(arg, ast.NameConstant):
                continue

            is_ignored = self._is_call_ignored(node)

            # We do not check for `None` values here:
            if not is_ignored and arg.value in {True, False}:
                self.add_violation(
                    BooleanPositionalArgumentViolation(
                        arg, text=str(arg.value),
                    ),
                ) 
Example #11
Source File: cqgi.py    From cadquery-freecad-module with GNU Lesser General Public License v3.0 6 votes vote down vote up
def visit_Assign(self, node):

        try:
            left_side = node.targets[0]

                    #do not handle attribute assignments
            if isinstance(left_side,ast.Attribute):
                return

            # Handle the NamedConstant type that is only present in Python 3
            astTypes = [ast.Num, ast.Str, ast.Name]
            if hasattr(ast, 'NameConstant'):
                astTypes.append(ast.NameConstant)

            if type(node.value) in astTypes:
                self.handle_assignment(left_side.id, node.value)
            elif type(node.value) == ast.Tuple:
                # we have a multi-value assignment
                for n, v in zip(left_side.elts, node.value.elts):
                    self.handle_assignment(n.id, v)
        except:
            traceback.print_exc()
            print("Unable to handle assignment for node '%s'" % ast.dump(left_side))

        return node 
Example #12
Source File: compares.py    From wemake-python-styleguide with MIT License 6 votes vote down vote up
def _is_simplifiable_assign(
        self,
        node_body: List[ast.stmt],
    ) -> Optional[str]:
        wrong_length = len(node_body) != 1
        if wrong_length or not isinstance(node_body[0], AssignNodes):
            return None
        if not isinstance(node_body[0].value, ast.NameConstant):
            return None
        if node_body[0].value.value is None:
            return None

        targets = get_assign_targets(node_body[0])
        if len(targets) != 1:
            return None

        return source.node_to_string(targets[0]) 
Example #13
Source File: macro_extractor.py    From skydoc with Apache License 2.0 6 votes vote down vote up
def get_type(expr):
  """Find the type of an expression.

  Args:
    expr: The expression to check.

  Returns:
    The type of the expression.
  """
  if isinstance(expr, ast.Num):
    return build_pb2.Attribute.INTEGER
  elif isinstance(expr, ast.Str):
    return build_pb2.Attribute.STRING
  elif isinstance(expr, ast.List):
    return build_pb2.Attribute.STRING_LIST
  elif isinstance(expr, ast.Name) and (expr.id == "True" or expr.id == "False"):
    return build_pb2.Attribute.BOOLEAN
  elif hasattr(ast, 'NameConstant') and isinstance(expr, ast.NameConstant) and (expr.value == True or expr.value == False):
    return build_pb2.Attribute.BOOLEAN
  else:
    return build_pb2.Attribute.UNKNOWN 
Example #14
Source File: checker.py    From pyflakes with MIT License 6 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 #15
Source File: checker.py    From blackmamba with MIT License 6 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 PY33) and isinstance(item, ast.NameConstant):
        # None, True, False are nameconstants in python3, but names in 2
        return item.value
    else:
        return UnhandledKeyType() 
Example #16
Source File: python.py    From nbparameterise with MIT License 6 votes vote down vote up
def check_fillable_node(node, path):
    if isinstance(node, (ast.Num, ast.Str)):
        return
    elif isinstance(node, ast.NameConstant) and (node.value in (True, False)):
        return
    elif isinstance(node, ast.List):
        for n in node.elts:
            check_fillable_node(n, path)
        return
    elif isinstance(node, ast.Dict):
        for n in node.keys:
            check_fillable_node(n, path)
        for n in node.values:
            check_fillable_node(n, path)
        return
    
    raise astcheck.ASTMismatch(path, node, 'number, string or boolean') 
Example #17
Source File: _343.py    From codetransformer with GNU General Public License v2.0 6 votes vote down vote up
def _make_expr_build_slice(toplevel, stack_builders):
    # Arg is always either 2 or 3.  If it's 3, then the first expression is the
    # step value.
    if toplevel.arg == 3:
        step = make_expr(stack_builders)
    else:
        step = None

    def normalize_empty_slice(node):
        """
        Convert LOAD_CONST(None) to just None.

        This normalizes slices of the form a[b:None] to just a[b:].
        """
        if isinstance(node, ast.NameConstant) and node.value is None:
            return None
        return node

    upper = normalize_empty_slice(make_expr(stack_builders))
    lower = normalize_empty_slice(make_expr(stack_builders))

    return ast.Slice(lower=lower, upper=upper, step=step) 
Example #18
Source File: safe_eval.py    From wemake-python-styleguide with MIT License 5 votes vote down vote up
def literal_eval_with_names(  # noqa: WPS231
    node: Optional[ast.AST],
) -> Any:
    """
    Safely evaluate constants and ``ast.Name`` nodes.

    We need this function to tell
    that ``[name]`` and ``[name]`` are the same nodes.

    Copied from the CPython's source code.
    Modified to treat ``ast.Name`` nodes as constants.

    See: :py:`ast.literal_eval` source.

    We intentionally ignore complexity violation here,
    becase we try to stay as close to the original source as possible.
    """
    binary_operators = (ast.Add, ast.Sub)
    if isinstance(node, (Constant, ast.NameConstant)):
        return node.value
    elif isinstance(node, (ast.Str, ast.Bytes, ast.Num)):  # pragma: py-gte-38
        # We wrap strings to tell the difference between strings and names:
        return node.n if isinstance(node, ast.Num) else '"{0!r}"'.format(node.s)
    elif isinstance(node, (ast.Tuple, ast.List, ast.Set, ast.Dict)):
        return _convert_iterable(node)
    elif isinstance(node, ast.BinOp) and isinstance(node.op, binary_operators):
        maybe_complex = _convert_complex(node)
        if maybe_complex is not None:
            return maybe_complex
    return _convert_signed_num(node) 
Example #19
Source File: python.py    From nbparameterise with MIT License 5 votes vote down vote up
def type_and_value(node):
    if isinstance(node, ast.Num):
        # int or float
        return type(node.n), node.n
    elif isinstance(node, ast.Str):
        return str, node.s
    elif isinstance(node, ast.NameConstant) and (node.value in (True, False)):
        return (bool, node.value)
    elif isinstance(node, ast.List):
        return (list, [type_and_value(n)[1] for n in node.elts])
    elif isinstance(node, ast.Dict):
        return (dict, {type_and_value(node.keys[i])[1]: type_and_value(node.values[i])[1] for i in range(len(node.keys))})

    raise NotImplementedError() 
Example #20
Source File: py_converter.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def parse_numpy_array(self, arr):
        """Given a Numpy array, produces an appropriate Python array
        or numerical literal representing its contents."""
        parse_single = lambda i: NameConstant(i) if isinstance(i, bool) else Num(i)
        if arr.ndim == 0:
            return parse_single(arr.item())
        if arr.ndim == 1:
            return ast.List([parse_single(i.item()) for i in arr], Load())

        elts = []
        for row in arr:
            elts.append(self.parse_numpy_array(row))
        return ast.List(elts, Load()) 
Example #21
Source File: py_converter.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def visit_call(self, call: Expr):
        """For calls, we must distinguish between ordinary functions,
        operators, and constructor calls."""
        func = call.op
        fields, field_defs = self.convert_fields(call.args)

        if isinstance(func, tvm.ir.Op):
            raise Exception('Operators should have been lowered and eliminated')

        if isinstance(func, relay.Constructor):
            # produce a constructor value
            return (self.create_call('ConstructorValue',
                                     [ast.Num(func.tag),
                                      ast.List(fields, Load()),
                                      NameConstant(None)]),
                    field_defs)

        # lowered operator: generate a call to a function that gets the PackedFunc
        # from TVM's registry
        if isinstance(func, Function) and func.attrs and func.attrs.Primitive.value == 1:
            op_call_def, op_call = self.create_op_call(func, call.args, fields)
            return (op_call, field_defs + [op_call_def])

        # ordinary function
        converted_func, defs = self.visit(func)
        defs += field_defs
        return (ast.Call(converted_func, fields, []), defs) 
Example #22
Source File: py_converter.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def create_match_check(self, pattern: Pattern, data):
        """Given an ADT match pattern and a (Python) expression pointing to
        an ADT value, this generates a Python expression that checks if the
        ADT value matches the given pattern (returning True or False)."""

        # wildcard or var match everything
        if isinstance(pattern, (relay.PatternWildcard, relay.PatternVar)):
            return NameConstant(True)

        conds = []

        if isinstance(pattern, relay.PatternConstructor):
            # constructor patterns check whether the constructors match
            # and also the matches of any nested patterns

            # equiv: (arg.tag == patern_constructor.tag)
            conds.append(ast.Compare(ast.Attribute(data, 'tag', Load()),
                                     [ast.Eq()],
                                     [ast.Num(pattern.constructor.tag)]))

        assert isinstance(pattern, (relay.PatternConstructor, relay.PatternTuple))
        # now check for any nested patterns
        for i in range(len(pattern.patterns)):
            nested_pat = pattern.patterns[i]
            # can safely skip var or wildcard patterns: they will
            # never cause a check to fail
            if not isinstance(nested_pat, relay.PatternConstructor):
                continue

            # index into the value corresponding to the subpattern
            field_index = ast.Subscript(ast.Attribute(data, 'fields', Load()),
                                        ast.Index(Num(i)), Load())
            conds.append(self.create_match_check(nested_pat, field_index))

        # if we do not need to check nested pattern, just return the single check
        if len(conds) == 1:
            return conds[0]
        # otherwise AND together any nested checks
        return ast.BoolOp(ast.And(), conds) 
Example #23
Source File: compiler.py    From Transcrypt with Apache License 2.0 5 votes vote down vote up
def visit_AnnAssign (self, node):
        if node.value != None:  # Rather than node.value is a NameConstant with value None
            self.visit (
                ast.Assign (
                    [node.target],
                    node.value
                )
            ) 
Example #24
Source File: dialect.py    From idom with MIT License 5 votes vote down vote up
def _transform_htm_prop_single(
        self,
        exp_nodes: List[ast.AST],
        call_stack: "_HtmlCallStack",
        attr: str,
        is_index: bool,
        value_or_index: Union[str, int],
    ) -> None:
        if isinstance(value_or_index, bool):
            const = ast.NameConstant(value_or_index)
            call_stack.add_attributes(ast.Str(attr), const)
        elif isinstance(value_or_index, int):
            call_stack.add_attributes(ast.Str(attr), exp_nodes[value_or_index])
        else:
            call_stack.add_attributes(ast.Str(attr), ast.Str(value_or_index)) 
Example #25
Source File: definitions.py    From vkbottle with MIT License 5 votes vote down vote up
def name_constant_type(d: ast.NameConstant):
    consts = {True: "true", False: "false", None: "null"}
    return consts[d.value] 
Example #26
Source File: yacc.py    From yaksok with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def p_atom_false(t):
    '''atom : FALSE'''
    t[0] = ast.NameConstant(False)
    t[0].lineno = t.lineno(1)
    t[0].col_offset = -1  # XXX 
Example #27
Source File: yacc.py    From yaksok with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def p_atom_true(t):
    '''atom : TRUE'''
    t[0] = ast.NameConstant(True)
    t[0].lineno = t.lineno(1)
    t[0].col_offset = -1  # XXX 
Example #28
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_nameconstant(self):
        self.expr(ast.NameConstant(4), "singleton must be True, False, or None") 
Example #29
Source File: _343.py    From codetransformer with GNU General Public License v2.0 5 votes vote down vote up
def _make_const_none(none):
    return ast.NameConstant(value=None) 
Example #30
Source File: walkers.py    From jishaku with MIT License 5 votes vote down vote up
def visit_Return(self, node):
        # Do not modify valueless returns
        if node.value is None:
            return node

        # Otherwise, replace the return with a yield & valueless return
        return ast.If(
            test=ast.NameConstant(
                value=True,  # if True; aka unconditional, will be optimized out
                lineno=node.lineno,
                col_offset=node.col_offset
            ),
            body=[
                # yield the value to be returned
                ast.Expr(
                    value=ast.Yield(
                        value=node.value,
                        lineno=node.lineno,
                        col_offset=node.col_offset
                    ),
                    lineno=node.lineno,
                    col_offset=node.col_offset
                ),
                # return valuelessly
                ast.Return(
                    value=None,
                    lineno=node.lineno,
                    col_offset=node.col_offset
                )
            ],
            orelse=[],
            lineno=node.lineno,
            col_offset=node.col_offset
        )