parser.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:python-fire 作者: google 项目源码 文件源码
def _LiteralEval(value):
  """Parse value as a Python literal, or container of containers and literals.

  First the AST of the value is updated so that bare-words are turned into
  strings. Then the resulting AST is evaluated as a literal or container of
  only containers and literals.

  This allows for the YAML-like syntax {a: b} to represent the dict {'a': 'b'}

  Args:
    value: A string to be parsed as a literal or container of containers and
      literals.
  Returns:
    The Python value representing the value arg.
  Raises:
    ValueError: If the value is not an expression with only containers and
      literals.
    SyntaxError: If the value string has a syntax error.
  """
  root = ast.parse(value, mode='eval')
  if isinstance(root.body, ast.BinOp):
    raise ValueError(value)

  for node in ast.walk(root):
    for field, child in ast.iter_fields(node):
      if isinstance(child, list):
        for index, subchild in enumerate(child):
          if isinstance(subchild, ast.Name):
            child[index] = _Replacement(subchild)

      elif isinstance(child, ast.Name):
        replacement = _Replacement(child)
        node.__setattr__(field, replacement)

  # ast.literal_eval supports the following types:
  # strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None
  # (bytes and set literals only starting with Python 3.2)
  return ast.literal_eval(root)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号