DEV Community

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

Posted on

Elixir Pipe in Python v2

I had previously shared a cool way to chain functions. This is exactly same but with hacking the | (Or) operator ;)

import json
from dataclasses import dataclass
from functools import reduce

import requests


class Pipe:
    def __init__(self, val):
        self.val = val
        self.funcs = []

    def __or__(self, other):
        self.funcs.append(other)
        return self

    def __call__(self):
        return reduce(
            lambda x, func: func(x) if not isinstance(x, list) else func(*x),
            self.funcs,
            self.val,
        )


@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


pp = (
    Pipe("""{"url": "https://google.com", "method": "GET"}""")
    | parse_request
    | validate_url
    | validate_method
    | get_content
    | (lambda x: x.decode("utf-8"))
    | (lambda x: check_content_type(x, "<!doctype html>"))
)()

print(pp)
Enter fullscreen mode Exit fullscreen mode

Let me know your thoughts!

**The cover image is taken from here

Top comments (0)