Hacker News new | ask | show | jobs
by shiandow 483 days ago
You can abuse the '>>' notation in python for pipes (or you could use |, I suppose), but you'll have to deal with whitespace shenanigans. I'm also not entirely sure about the order of evaluation. And you'll need to do partial function application by hand if you want that (though it is possible to write a meta function for that).

So one could write

    class Piped:
        def __init__(self, value):
            self.value = value
    
        def __or__(self, func):
            return Piped(func(self.value))
    
        def __repr__(self):
            return f"Piped({self.value!r})"
    
    Piped('test') | str.upper | (lambda x: x.replace('T', 't')) | "prefix_".__add__ # => prefix_tESt
but whether that is a good idea is a whole different matter.
1 comments

Apache Beam in Python does this, with code like

    counts = (
        lines
        | 'Split' >> (
            beam.FlatMap(
                lambda x: re.findall(r'[A-Za-z\']+', x)).with_output_types(str))
        | 'PairWithOne' >> beam.Map(lambda x: (x, 1))
        | 'GroupAndSum' >> beam.CombinePerKey(sum))

I'm not sure how I feel about it, other than the fact that I'd 100x rather write Beam pipelines in basically any other language. But that's about more than syntax.