Beispiel #1
0
def argnode_source(source: Source, node: ast.AST,
                   vars_only: bool) -> Union[str, ast.AST]:
    """Get the source of an argument node

    Args:
        source: The executing source object
        node: The node to get the source from
        vars_only: Whether only allow variables and attributes

    Returns:
        The source of the node (node.id for ast.Name,
            node.attr for ast.Attribute). Or the node itself if the source
            cannot be fetched.
    """
    if isinstance(node, ast.Constant):
        return repr(node.value)

    if sys.version_info < (3, 9):  # pragma: no cover
        if isinstance(node, ast.Index):
            node = node.value
        if isinstance(node, ast.Num):
            return repr(node.n)
        if isinstance(node, (ast.Bytes, ast.Str)):
            return repr(node.s)
        if isinstance(node, ast.NameConstant):
            return repr(node.value)

    if vars_only:
        return (node.id if isinstance(node, ast.Name) else
                node.attr if isinstance(node, ast.Attribute) else node)

    # requires asttokens
    return source.asttokens().get_text(node)
Beispiel #2
0
def argnode_source(source: Source, node: ast.AST,
                   vars_only: bool) -> Union[str, ast.AST]:
    """Get the source of an argument node

    Args:
        source: The executing source object
        node: The node to get the source from
        vars_only: Whether only allow variables and attributes

    Returns:
        The source of the node (node.id for ast.Name,
            node.attr for ast.Attribute). Or the node itself if the source
            cannot be fetched.
    """
    if vars_only:
        return (node.id if isinstance(node, ast.Name) else
                node.attr if isinstance(node, ast.Attribute) else node)

    # requires asttokens
    return source.asttokens().get_text(node)