DEV Community

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

Posted on • Updated 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),

Enter fullscreen mode Exit fullscreen mode

How to use it?

Example -

import json
from dataclasses import dataclass
import requests

class Request:
    url: str
    method: str

def parse_request(req: str):
    return pipe(
        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

        """{"url": "", "method": "GET"}""",
        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 (1)

bigyatdev profile image
Bigyat Dev

Thank you, makes it really nice chaining django querysets.