Python ast.Bytes() Examples

The following are 16 code examples of ast.Bytes(). 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: 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 #3
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 #4
Source File: source_visitor.py    From vermin with MIT License 6 votes vote down vote up
def visit_BinOp(self, node):
    # Examples:
    #   BinOp(left=Bytes(s=b'%4x'), op=Mod(), right=Num(n=10))
    #   BinOp(left=Call(func=Name(id='bytearray', ctx=Load()), args=[Bytes(s=b'%x')], keywords=[]),
    #         op=Mod(), right=Num(n=10))
    if (hasattr(ast, "Bytes") and isinstance(node.left, ast.Bytes))\
       and isinstance(node.op, ast.Mod):
      self.__bytes_format = True
      self.__vvprint("bytes `%` formatting requires 3.5+ (or 2.6+ as `str` synonym)")

    if (isinstance(node.left, ast.Call) and isinstance(node.left.func, ast.Name) and
         node.left.func.id == "bytearray") and isinstance(node.op, ast.Mod):
      self.__bytearray_format = True
      self.__vvprint("bytearray `%` formatting requires 3.5+")

    self.generic_visit(node) 
Example #5
Source File: test_utils.py    From pasta with Apache License 2.0 6 votes vote down vote up
def supports_feature(feature):
  if feature == 'bytes_node':
    return hasattr(ast, 'Bytes') and issubclass(ast.Bytes, ast.AST)
  if feature == 'exec_node':
    return hasattr(ast, 'Exec') and issubclass(ast.Exec, ast.AST)
  if feature == 'type_annotations':
    try:
      ast.parse('def foo(bar: str=123) -> None: pass')
    except SyntaxError:
      return False
    return True
  if feature == 'fstring':
    return hasattr(ast, 'JoinedStr') and issubclass(ast.JoinedStr, ast.AST)
  # Python 2 counts tabs as 8 spaces for indentation
  if feature == 'mixed_tabs_spaces':
    return sys.version_info[0] < 3
  return False 
Example #6
Source File: model_form.py    From flake8-django with GNU General Public License v3.0 5 votes vote down vote up
def is_string_dunder_all(self, element):
        """
        Return True if element is ast.Str or ast.Bytes and equals "__all__"
        """
        if not isinstance(element.value, (ast.Str, ast.Bytes)):
            return False

        node_value = element.value.s
        if isinstance(node_value, bytes):
            node_value = node_value.decode()
        return node_value == '__all__' 
Example #7
Source File: _recompute.py    From icontract with MIT License 5 votes vote down vote up
def visit_Bytes(self, node: ast.Bytes) -> bytes:
        """Recompute the value as the bytes at the node."""
        result = node.s

        self.recomputed_values[node] = result
        return node.s 
Example #8
Source File: source_visitor.py    From vermin with MIT License 5 votes vote down vote up
def visit_Constant(self, node):
    # From 3.8, Bytes(s=b'%x') is represented as Constant(value=b'%x', kind=None) instead.
    if hasattr(node, "value") and isinstance(node.value, bytes):
      self.__bytesv3 = True
      self.__vvprint("byte strings (b'..') require 3+ (or 2.6+ as `str` synonym)")

      for directive in BYTES_DIRECTIVE_REGEX.findall(str(node.value)):
        self.__add_bytes_directive(directive, node.lineno) 
Example #9
Source File: ast3.py    From gast with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visit_Constant(self, node):
            if node.value is None:
                new_node = ast.NameConstant(node.value)
            elif node.value is Ellipsis:
                new_node = ast.Ellipsis()
            elif isinstance(node.value, bool):
                new_node = ast.NameConstant(node.value)
            elif isinstance(node.value, (int, float, complex)):
                new_node = ast.Num(node.value)
            elif isinstance(node.value, str):
                new_node = ast.Str(node.value)
            else:
                new_node = ast.Bytes(node.value)
            ast.copy_location(new_node, node)
            return new_node 
Example #10
Source File: _343.py    From codetransformer with GNU General Public License v2.0 5 votes vote down vote up
def _make_const_bytes(const):
    return ast.Bytes(s=const) 
Example #11
Source File: flatten.py    From kappa with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def visit_Bytes(self, b: ast.Bytes) -> VisitExprReturnT:
        return b, [] 
Example #12
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 #13
Source File: context.py    From bandit with Apache License 2.0 4 votes vote down vote up
def _get_literal_value(self, literal):
        '''Utility function to turn AST literals into native Python types

        :param literal: The AST literal to convert
        :return: The value of the AST literal
        '''
        if isinstance(literal, ast.Num):
            literal_value = literal.n

        elif isinstance(literal, ast.Str):
            literal_value = literal.s

        elif isinstance(literal, ast.List):
            return_list = list()
            for li in literal.elts:
                return_list.append(self._get_literal_value(li))
            literal_value = return_list

        elif isinstance(literal, ast.Tuple):
            return_tuple = tuple()
            for ti in literal.elts:
                return_tuple = return_tuple + (self._get_literal_value(ti),)
            literal_value = return_tuple

        elif isinstance(literal, ast.Set):
            return_set = set()
            for si in literal.elts:
                return_set.add(self._get_literal_value(si))
            literal_value = return_set

        elif isinstance(literal, ast.Dict):
            literal_value = dict(zip(literal.keys, literal.values))

        elif isinstance(literal, ast.Ellipsis):
            # what do we want to do with this?
            literal_value = None

        elif isinstance(literal, ast.Name):
            literal_value = literal.id

        # NOTE(sigmavirus24): NameConstants are only part of the AST in Python
        # 3. NameConstants tend to refer to things like True and False. This
        # prevents them from being re-assigned in Python 3.
        elif six.PY3 and isinstance(literal, ast.NameConstant):
            literal_value = str(literal.value)

        # NOTE(sigmavirus24): Bytes are only part of the AST in Python 3
        elif six.PY3 and isinstance(literal, ast.Bytes):
            literal_value = literal.s

        else:
            literal_value = None

        return literal_value 
Example #14
Source File: test_context.py    From bandit with Apache License 2.0 4 votes vote down vote up
def test__get_literal_value(self):
        new_context = context.Context()

        value = ast.Num(42)
        expected = value.n
        self.assertEqual(expected, new_context._get_literal_value(value))

        value = ast.Str('spam')
        expected = value.s
        self.assertEqual(expected, new_context._get_literal_value(value))

        value = ast.List([ast.Str('spam'), ast.Num(42)], ast.Load())
        expected = [ast.Str('spam').s, ast.Num(42).n]
        self.assertListEqual(expected, new_context._get_literal_value(value))

        value = ast.Tuple([ast.Str('spam'), ast.Num(42)], ast.Load())
        expected = (ast.Str('spam').s, ast.Num(42).n)
        self.assertTupleEqual(expected, new_context._get_literal_value(value))

        value = ast.Set([ast.Str('spam'), ast.Num(42)])
        expected = set([ast.Str('spam').s, ast.Num(42).n])
        self.assertSetEqual(expected, new_context._get_literal_value(value))

        value = ast.Dict(['spam', 'eggs'], [42, 'foo'])
        expected = dict(spam=42, eggs='foo')
        self.assertDictEqual(expected, new_context._get_literal_value(value))

        value = ast.Ellipsis()
        self.assertIsNone(new_context._get_literal_value(value))

        value = ast.Name('spam', ast.Load())
        expected = value.id
        self.assertEqual(expected, new_context._get_literal_value(value))

        if six.PY3:
            value = ast.NameConstant(True)
            expected = str(value.value)
            self.assertEqual(expected, new_context._get_literal_value(value))

        if six.PY3:
            value = ast.Bytes(b'spam')
            expected = value.s
            self.assertEqual(expected, new_context._get_literal_value(value))

        self.assertIsNone(new_context._get_literal_value(None)) 
Example #15
Source File: source_visitor.py    From vermin with MIT License 4 votes vote down vote up
def __get_attribute_name(self, node):
    """Retrieve full attribute name path, like ["ipaddress", "IPv4Address"] from:
    `Attribute(value=Name(id='ipaddress', ctx=Load()), attr='IPv4Address', ctx=Load())`
    Or ["Fraction", "as_integer_ratio"] from:
    `Attribute(value=Call(func=Name(id='Fraction', ctx=Load()), args=[Num(n=42)], keywords=[]),
               attr='as_integer_ratio', ctx=Load())`
    """
    full_name = []
    primi_type = False
    for attr in ast.walk(node):
      if len(full_name) > 0 and self.__is_builtin_type(full_name[0]):
        primi_type = True
      if isinstance(attr, ast.Attribute):
        if hasattr(attr, "attr"):
          full_name.insert(0, attr.attr)
        if hasattr(attr, "value") and hasattr(attr.value, "id"):
          full_name.insert(0, attr.value.id)
      elif isinstance(attr, ast.Call):
        if hasattr(attr, "func") and hasattr(attr.func, "id"):
          full_name.insert(0, attr.func.id)
      elif not primi_type and isinstance(attr, ast.Dict):
        if len(full_name) == 0 or (full_name[0] != "dict" and len(full_name) == 1):
          full_name.insert(0, "dict")
      elif not primi_type and isinstance(attr, ast.Set):
        if len(full_name) == 0 or (full_name[0] != "set" and len(full_name) == 1):
          full_name.insert(0, "set")
      elif not primi_type and isinstance(attr, ast.List):
        if len(full_name) == 0 or (full_name[0] != "list" and len(full_name) == 1):
          full_name.insert(0, "list")
      elif not primi_type and isinstance(attr, ast.Str):
        if sys.version_info.major == 2 and isinstance(attr.s, unicode):
          name = "unicode"
        else:
          name = "str"
        if len(full_name) == 0 or (full_name[0] != name and len(full_name) == 1):
          full_name.insert(0, name)
      elif not primi_type and isinstance(attr, ast.Num):
        t = type(attr.n)
        name = None
        if t == int:
          name = "int"
        elif t == float:
          name = "float"
        if sys.version_info.major == 2 and t == long:  # novm
          name = "long"
        if name is not None and len(full_name) == 0 or \
          (full_name[0] != name and len(full_name) == 1):
          full_name.insert(0, name)
      elif not primi_type and hasattr(ast, "Bytes") and isinstance(attr, ast.Bytes):
        if len(full_name) == 0 or (full_name[0] != "bytes" and len(full_name) == 1):
          full_name.insert(0, "bytes")
    return full_name 
Example #16
Source File: source_visitor.py    From vermin with MIT License 4 votes vote down vote up
def __add_name_res_assign_node(self, node):
    if not hasattr(node, "value"):
      return

    value_name = None

    # If rvalue is a Call.
    if isinstance(node.value, ast.Call):
      if isinstance(node.value.func, ast.Name):
        value_name = node.value.func.id
      elif isinstance(node.value.func, ast.Attribute):
        value_name = dotted_name(self.__get_attribute_name(node.value.func))

    # If rvalue is an Attribute list
    elif isinstance(node.value, ast.Attribute):
      value_name = dotted_name(self.__get_attribute_name(node.value))

    elif isinstance(node.value, ast.Dict):
      value_name = "dict"
    elif isinstance(node.value, ast.Set):
      value_name = "set"
    elif isinstance(node.value, ast.List):
      value_name = "list"
    elif isinstance(node.value, ast.Str):
      if sys.version_info.major == 2 and isinstance(node.value.s, unicode):
        value_name = "unicode"
      else:
        value_name = "str"
    elif isinstance(node.value, ast.Num):
      t = type(node.value.n)
      if t == int:
        value_name = "int"
      elif sys.version_info.major == 2 and t == long:  # novm
        value_name = "long"
      elif t == float:
        value_name = "float"
    elif hasattr(ast, "Bytes") and isinstance(node.value, ast.Bytes):
      value_name = "bytes"

    if value_name is None:
      return

    targets = []
    if hasattr(node, "targets"):
      targets = node.targets
    elif hasattr(node, "target"):
      targets.append(node.target)
    for target in targets:
      if isinstance(target, ast.Name):
        target_name = target.id
        self.__add_name_res(target_name, value_name)