当前位置: 首页>>代码示例>>Python>>正文


Python ast.Bytes方法代码示例

本文整理汇总了Python中ast.Bytes方法的典型用法代码示例。如果您正苦于以下问题:Python ast.Bytes方法的具体用法?Python ast.Bytes怎么用?Python ast.Bytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.Bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: convert_to_value

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [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 PY2) and isinstance(item, ast.NameConstant):
        # None, True, False are nameconstants in python3, but names in 2
        return item.value
    else:
        return UnhandledKeyType() 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:27,代码来源:checker.py

示例2: convert_to_value

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [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

示例3: visit_BinOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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) 
开发者ID:netromdk,项目名称:vermin,代码行数:18,代码来源:source_visitor.py

示例4: supports_feature

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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 
开发者ID:google,项目名称:pasta,代码行数:19,代码来源:test_utils.py

示例5: is_string_dunder_all

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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__' 
开发者ID:rocioar,项目名称:flake8-django,代码行数:13,代码来源:model_form.py

示例6: visit_Bytes

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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 
开发者ID:Parquery,项目名称:icontract,代码行数:8,代码来源:_recompute.py

示例7: visit_Constant

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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) 
开发者ID:netromdk,项目名称:vermin,代码行数:10,代码来源:source_visitor.py

示例8: visit_Constant

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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 
开发者ID:serge-sans-paille,项目名称:gast,代码行数:17,代码来源:ast3.py

示例9: _make_const_bytes

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
def _make_const_bytes(const):
    return ast.Bytes(s=const) 
开发者ID:llllllllll,项目名称:codetransformer,代码行数:4,代码来源:_343.py

示例10: visit_Bytes

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
def visit_Bytes(self, b: ast.Bytes) -> VisitExprReturnT:
        return b, [] 
开发者ID:NetSys,项目名称:kappa,代码行数:4,代码来源:flatten.py

示例11: literal_eval_with_names

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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) 
开发者ID:wemake-services,项目名称:wemake-python-styleguide,代码行数:32,代码来源:safe_eval.py

示例12: _get_literal_value

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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 
开发者ID:PyCQA,项目名称:bandit,代码行数:56,代码来源:context.py

示例13: test__get_literal_value

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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)) 
开发者ID:PyCQA,项目名称:bandit,代码行数:47,代码来源:test_context.py

示例14: __get_attribute_name

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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 
开发者ID:netromdk,项目名称:vermin,代码行数:54,代码来源:source_visitor.py

示例15: __add_name_res_assign_node

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Bytes [as 别名]
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) 
开发者ID:netromdk,项目名称:vermin,代码行数:53,代码来源:source_visitor.py


注:本文中的ast.Bytes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。