Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the well-loved pipe operation #49

Open
spapas opened this issue Oct 20, 2024 · 0 comments
Open

Add the well-loved pipe operation #49

spapas opened this issue Oct 20, 2024 · 0 comments

Comments

@spapas
Copy link

spapas commented Oct 20, 2024

You may want to add a pipe operator to have things like

square = lambda x: x ** 2

2 | square  | (lambda x: x+1) | print 

(this will output 5)

A naive implementation could be:

class PipeWrapper(ast.NodeTransformer):
    def visit_BinOp(self, node):
        if isinstance(node.op, ast.BitOr):
            node.left = self.visit(node.left)
            node.right = self.visit(node.right)

            return ast.Call(
                func=node.right,
                args=[node.left],
                keywords=[],
            )
        return self.generic_visit(node)


def transform_ast(tree, **_kwargs):
    """Transforms the Abstract Syntax Tree or a single node"""
    tree_or_node = PipeWrapper().visit(tree)
    ast.fix_missing_locations(tree_or_node)
    return tree_or_node

def add_hook(**_kwargs):
    """Creates and automatically adds the import hook in sys.meta_path"""
    hook = import_hook.create_hook(
        # transform_source=transform_source,
        transform_ast=transform_ast,
        hook_name=__name__,  # optional
    )
    return hook

This needs improvement to identify if the pipe operator or the binary or operator is needed, right now 1 | 2 throws error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant