DEV Community 👩‍💻👨‍💻

Cover image for Elixir Pipe in Python
Azizul Haque Ananto
Azizul Haque Ananto

Posted on

Elixir Pipe in Python

I really like the Pipe operator in Elixir. This is something from the future!

As I work with Python more often, I was trying to implement that pipe functionality in Python with few lines of codes.

from functools import reduce


def pipe(*fn_list):
    return reduce(
        lambda x, f: f(x) if not isinstance(x, list) else f(*x),
        fn_list,
    )

Enter fullscreen mode Exit fullscreen mode

How to use it?

Example -

import json
from dataclasses import dataclass
import requests


@dataclass
class Request:
    url: str
    method: str


def parse_request(req: str):
    return pipe(
        req,
        json.loads,
        lambda x: Request(**x),
    )


def validate_url(req: Request):
    return req if req.url.startswith("http") else None


def validate_method(req: Request):
    return req if req.method in ["GET", "POST", "PUT", "DELETE"] else None


def get_content(req: Request):
    return requests.get(req.url).content


def check_content_type(content: str, content_type: str):
    return content if content.startswith(content_type) else None


print(
    pipe(
        """{"url": "https://google.com", "method": "GET"}""",
        parse_request,
        validate_url,
        validate_method,
        get_content,
        lambda content: content.decode("utf-8"),
        lambda content: check_content_type(content, "<!doctype html>"),
    )
)

Enter fullscreen mode Exit fullscreen mode

You can use lambda and functions in pipe.

Notice the last function in pipe, check_content_type takes two arguments, the first one content is passed from the previous pipe function, so we take that in lambda argument and then call the check_content_type with that content and another argument.

Let me know your thoughts!

**The cover image is taken from here.

Top comments (0)

Let's team up together 🤝

We're Hiring

We're hiring for a Senior Full Stack Engineer to join the DEV team. Want the deets? Head here to learn more about who we're looking for.