r/Python
•
u/Desperate_Cold6274
•
May 10 '26
•
2
Discussion Will python ever have a chaining operator?
In other languages I use map() and filter() through piping and my code usually looks readable as I can clearly see a data-stream transformation.
As it is today, users cannot do map() |> filter() |> list(), but they need to do list(filter(map())) which makes things unreadable. Lists of comprehension work fine for very simple use-case becoming unreadable very quickly as complexity increases.
However, in python there has always been some resistance, especially 15-20 years ago, but times are evolving. Also, by considering the wide adoption in data-science, it is worth noticing that numbers-crunchers are more familiar with the concept of “data transformation flow” than “function calls”. On the packages dimension , libraries like 🐼s support methods chaining which from an external viewpoint, it’s semantically similar.
Do you know if there is any indication that python core team may allow operator piping (and/or chaining) in the not-too-long-term?
69
u/AWildMonomAppears May 10 '26
It sounds simple but doing this nicely almost requires functional mechanics like auto-currying. In languages with pipes the right side waits for data (lazy). In Python it evaluates immediately so writing something like data |> map(func) would just throw for a missing argument on map.
To fix it Python would have to secretly rewrite your code to inject the data which goes against the rule that explicit is better than implicit. It also gets messy because standard functions dont even agree on whether data should be the first or last argument.
Instead Python relies on object-oriented method chaining. Since methods are attached to objects the state carries forward. You see this in Pandas with df.dropna().apply(func). It gives that clear data flow without needing any compiler magic. basically forces you to use the OO approach if you want to avoid nested paranthesis.
2
u/Schmittfried May 12 '26
basically forces you to use the OO approach if you want to avoid nested paranthesis.
Which is not a good thing in this case. Using fluent APIs is nice, but building them is horrible developer experience. You need countless classes that just represent an abstract notion of where you are in your call chain, carrying state from class to class.
1
u/AWildMonomAppears May 12 '26
I totally agree, Im a functional nerd. But breaking convention and established idioms is not worth the alternative.
1
u/Schmittfried May 12 '26
If appropriate language features were added, no conventions would be broken, we‘d just get additional ones. Sure, every feature has a cost and I‘m not convinced piping is the top priority, but I hardly see how repeatedly rejecting null-safe attribute access makes Python a better language. It honestly has way more uses than the walrus operator and the same amount of „hidden“ control flow.
3
u/an_actual_human May 10 '26
In Python it evaluates immediately so writing something like data |> map(func) would just throw for a missing argument on map.
data and map could be wrapped in something with lazy semantics so that they evaluate right away, but don't do anything until it's needed.
6
2
u/ConspicuousPineapple May 10 '26
Python it evaluates immediately so writing something like data |> map(func) would just throw for a missing argument on map.
Or you know, don't do that? We're talking about a new language operator, python is free to implement it properly. What you're describing makes no sense as nobody would design that feature that way.
You could even just have it as syntactic sugar to replace the first argument. That's what methods are already, you just expand that behavior to all functions.
I'll add that plenty of languages have pipes without currying and they manage just fine. Elixir being a prominent one.
10
u/muntoo R_{μν} - 1/2 R g_{μν} + Λ g_{μν} = 8π T_{μν} May 10 '26
Good design means managing complexity. That means following practices: don't mutate at a spooky distance, e.g.,
def log(s): sys.stdout = open("log.txt", "a") print(s) god_object.__getitem__ = god_object.counter.__add__ = lambda *args: (super(type(god_object.counter)).__add__(*args), print(s))[0]Programmers silently agree not to break invariants like this. If they did, then there is quite literally no function call you could trust... it could do anything.
Similarly, when introducing a feature that could break an existing invariant, you must justify that it is astronomically better than the invariant it breaks, because doing so increases the verification/provability burden even if the feature is never used, simply because it could be used.
2
u/ConspicuousPineapple May 10 '26
I'm not saying it would make sense to add in python (what I want is proper iterators instead), just that it's perfectly doable, and pretty easily at that.
I would also argue that pipes don't break any invariant as, again, method calls are exactly the same syntactic construct with a conventional restriction on top.
1
u/Bob_Dieter May 11 '26
There is another solution other than currying: some languages use macros to do the threading. For example, here is how clojures macro syntax could translate to python:
mylist = ->> range(20): filter(isodd) map(sqrt) list #or mylist = ->> range(20) as x: filter(isodd, x) map(sqrt, x) list(x)
11
u/Fabulous-Possible758 May 10 '26
https://pypi.org/project/pipe/
This is pretty simple to do in small one off classes too if you don’t want a whole library.
There’s just no real reason to extend the syntax for a case that’s pretty well covered and completely customizable.
42
u/RedSinned May 10 '26
What would be your use case in which you wouldn‘t use a library like polars, but is still so complex that the current capabilities are not enough?
20
u/Beginning-Fruit-1397 May 10 '26
A lot of things. mapping and filtering is the same as any for loop.
You don't want to create an arrow data structure for any list or dict8
u/RedSinned May 10 '26
Welle there are arrays and nested datatypes in polars which I would actually use over plain python in performance relevant use cases.
And that is kond of the reason I think it‘s not a top wished feature in python: most of the people already have their performance optimized libraries for their specific use case.
So a use case where you need so many operations that a for loop won‘t do but on the other hand is performance wise not relevant that you would actually want to do that in plain python is kind of niche.
Another thing is readabilty. Python core strength is its easyness to learn even for people without prior programming experience so constructs like |> don‘t feel very pythonic.
26
u/cdcformatc May 10 '26
writing code line by line is piping each successive line waits for the result of the last
x = map(...)
y = filter(x, ...)
z = list(y)36
u/mapadofu May 10 '26 edited May 10 '26
From the ancient tomes
Flat is better than nested. … Explicit is better than implicit.3
u/stevenjd May 13 '26
From the ancient tomes
Flat is better than nested. … Explicit is better than implicit.
Function chaining is completely explicit, and flat. It is nested function calls that are nested.
list(filter(map(args)))has three nested function calls, and you have to read them inside out to understand the order of evaluation. Languages which support chaining are written flat, in the same order as the functions are evaluated:
args | map | filter | list # hypothetical syntaxIf we actually followed the Zen of Python, and not just used it as a thought-terminating cliché, we would have function chaining.
7
u/invalidusernamelol May 11 '26 edited May 11 '26
You can also just use the universal intermediate for this (assuming it's not already being used for translation)
_ = map(...) _ = filter(_) result = list(_)That's also how you'd do it in the REPL, and it stops you from having to use a bunch of different names.
10
u/Limp_Illustrator7614 May 10 '26
i dont think python will ever officially support it because they kind of hate functional programming, but coconut does that exactly. it's a functional syntactical superset of python that compiles to python, where the piping operator is exactly `|>`. go read the docs
6
3
u/Wurstinator May 10 '26
"Any indication" would mean there is a PEP in the works for this, which you could search for.
I think it's unlikely. As you said, this can be done in libraries already.
3
u/--ps-- May 10 '26 edited May 10 '26
At my job, we have a code where we overload __ rshift __(), so you can then write something like begin_pipeline(fn) >> fn2 >> fn3 etc.., somethimes you need to use partial() to pass some additional parameters too, but honestly, I hate that part, because the semantics is very unclear for the code reader.
1
u/sausix May 10 '26
It should be possible to something like this:
pipe(func) >> sin >> cos >> print, P, "is the result"
It's a tuple transport and you just need markers for placing arguments anywhere else. I would follow the partial scheme so the value or *args will alway be appended.
3
u/red_hare May 10 '26 edited May 10 '26
I think you can do this with a decorator and bitwise or.
from functools import wraps
class _PipeFn:
def __init__(self, func, args, kwargs):
self.func, self.args, self.kwargs = func, args, kwargs
def __ror__(self, lhs):
return self.func(lhs, *self.args, **self.kwargs)
def pipeable(func):
@wraps(func)
def wrapper(*args, **kwargs):
return _PipeFn(func, args, kwargs)
return wrapper
def foo():
return 1
@pipeable
def bar(x):
return x + 1
@pipeable
def baz(x):
return x * 2
print(foo() | bar() | baz())Not that you should...
3
2
u/Evolve-Maz May 10 '26
You can write your own version of this. Even just for learning it's very helpful. Here's the gist:
Create a class called "Pipeline". Init function takes in data (just an object) and processors (list of processor functions, default empty).
Then override the rshift operator (>>) of the class to be your pipe operator. The signature is rshift(self, other). In our case other will be a callable with a single input. The rshift operator returns a new pipeline, with same data, and processors being the current list plus the other passed into this function.
For our use case, pretend we have a list of coordinates with x and y attributes, and your pipelines first calculates a z attr using Pythagoras theorem and then filters to all objects with z over 2.
data = [coord(1, 3), coord(4, 3), ...]
pipeline = Pipeline(data) >> add_z_coord >> filter_coord_above(2)
output = pipeline.execute()
Output will be a result object (idea borrowed from go). It'll have a data attribute and an err attribute. Error will hold any exception which occurred during execution of the Pipeline, including the step it happened at. And data will hold the final value from the Pipeline calculation.
Execute method will start with the initial Pipeline data and just run a for loop through all the processor callable passing in the data at each step and getting output. Wrap in a try except so you can track error state.
Once you write that once, you can decide whether you want extra sugar for map and filter as explicit processors, or if you want more data about steps. Etc.
2
u/RoadsideCookie May 10 '26
I posted this as a reply, but you can do "piping" in native Python like so:
from functools import reduce
result = reduce(lambda r, f: f(r),
[
lambda xs: [x * 2 for x in xs],
lambda xs: [x for x in xs if x > 4],
sum,
],
[1, 2, 3, 4, 5],
)But it's not very readable.
3
u/JaggedParadigm May 11 '26 edited May 19 '26
This is very similar to a utility function I tend to reach for:
from functools import reduce def pipe(data, *functions): return reduce(lambda a, x: x(a), functions, data)I either use it on single inputs with functions or lambdas like this:
def add_5(x): return x + 5 def divide_by_3(x): return x / 3 pipe( 4, add_5, divide_by_3, lambda x: x + 4 ) >>> 7.... or for dictionary inputs I tend to add/remove entries like this:
def keep(keys): def keep_inner(record): return {key: item for key, item in record.items if key in keys} return keep_inner pipe( {'a': 1, 'b': 2}, lambda x: x | {'c': x['a'] + x['b']}, lambda x: x | {'d': x['a'] * x['b'] * x['c']}, keep(['b', 'd']) ) >>> {'b': 2, 'd': 6}Of course, if the lambda are too ugly you can wrap them in function names (Ex: the first input in this last example could be called something like set_c_2_a_plus_b)
2
u/Temporary_Pie2733 May 10 '26
I’d rather see proper partial application and composition added to the language. list(filter(p, map(f, itr))) becomes (list ∘ filter(p) ∘ map(f))(itr). Then piping is just composition in the other direction, mixed with function application, itr |> map(f) |> filter(p) |> list.
2
u/jnazario May 10 '26
Heretical take from a a longtime python programmer who went through some similar questions over a decade ago: learn other languages which have the properties you like and use them.
Not every feature will come to one language. You’ll be pleased at what other ecosystems have and what else you can do and you’ll become a better programmer in python as well.
2
u/UseMoreBandwith May 10 '26
we already having chaining.
You just have to learn to write python.
You can implement chaining in your own classes by having methods return self:
class Calculator:
def __init__(self, value=0):
self.value = value
def add(self, n):
self.value += n
return self
def result(self):
return self.value
# Chaining in action
calc = Calculator(5).add(3).add(2)
print(calc.result()) # Output: 10 2
u/Agile-Ad5489 May 10 '26
users cannot do map() |> filter() |> list(), but they need to do list(filter(map())) which makes things unreadable
Four symbols and two spaces “() |> ” are more readable than one consistent pair of brackets?
Confusing “what I am used to” for “is objectively clearer” is not that close to insanity, but you can certainly see insanity clearly without binoculars.
3
u/JimWayneBob May 10 '26
I just wrap everything in parentheses and chain to make it look like pipping
Foo=(
bar_df
.filter(blah blah)
.select(ColA)
)
1
u/Sufficient_Meet6836 May 10 '26
Same, but that also doesn't allow you to use any given function, only methods defined on that class
3
u/shadowdance55 git push -f May 10 '26 edited May 10 '26
You should learn how to use nested comprehensions.
Edit: Just noticed you wrote that comprehensions are unreadable, but you are very wrong. They stack up very nicely, and are nearly identical in syntax to nested loops. Of course, if you're used to map/reduce syntax, they might be a bit unfamiliar, but that is true of literally any syntax - readability is exclusively a result of unfamiliarity.
2
u/sausix May 10 '26
Nested comprehensions are readable again if you put them in multiple lines. And then you have lost the advantage of a comprehension. Sure you can learn to read and write them fluently. But they're still more complicated than other Python syntax.
3
u/KingHavana May 10 '26
I'm not sure the only advantage to comprehensions is doing them in one line.
1
u/sausix May 10 '26
Comprehensions save you creating temporary collection variables for filling them up.
Once comprehensions get nested and comicplicated it's better to split into multiple lines and then there's only a small step to not use a comprehension at all at that spot.
1
u/KingHavana May 10 '26
I just prefer the style of comprehensions better. It sort of reads "the list of" then the description of the actual thing. It feels more like you're declaring what you want instead of building what you want.
-1
u/Beginning-Fruit-1397 May 10 '26
you can't say that he is wrong. I too think that comprehensions are garbage to read vs iterator chains.
this is all subjective
2
u/KingHavana May 10 '26
If you're repeatedly using three functions in the same order why not make a function that gives the output of those functions?
def process(x): return list(map(filter(x)))
1
u/Beginning-Fruit-1397 May 10 '26
FYI, someone made a nice list comparing fluent iterator libraries on this sub relatively recently:
https://www.reddit.com/r/Python/comments/1rj3ct7/comment/o8aordo/?context=3
(disclaimer: I'm the author of pyochain)
On chaining, i.e passing x to f as `x.f(args, kwargs)` rather than `f(x, args, kwargs`, I doubt that it will ever be added.
On specific iterators chains, I doubt it even more.
For the first thing, it's really trivial to implement.
It's a one liner method, and you can handle any type of generic functions and parameters with `Callable`, `Concatenate`, and `def foo[**P, T]() -> T` generics (or, urgh, if you prefer to use the old syntax, TypeVar T and ParamSpec P).
I regularly browse the python discussions forum and any suggestions such as this will be easily rejected.
Either you create:
- a new "builtin" method -> breaking change for an helper
- a new operator/overload one existing -> too much for an helper
On iterators chains, the strength of python, specifically with iterables, is that duck typing allows you to very easily implement custom collections.
If we were to add chaining for Iterators/Iterables, it would change the meaning of collections abc, who are minimal interfaces and would then become huge classes.
Now, my polars DataFrame who's an Iterable also has filter just like `collections.abc.Iterator`, but the signature won't be the same as `collections.abc.Iterator` so it violates the contract.
This would be a huge pain to work with if you use any decent type checker/linter, marking everything as override/ignore rule violation, especially if like me your primary coding activitiy is writing libraries.
1
u/squizzeak May 10 '26
I’ve done something similar to chaining but writing methods that return self, though this only works for chaining methods from the same class. But I like the idea of subclassing __rshift__!
1
u/borborygmis May 10 '26
This library has similar concepts: https://github.com/mtingers/kompoz
But overkill for your example where you can use something like functool.reduce.
In Kompoz, that translates to:
from dataclasses import dataclass, field
from kompoz import pipe
@dataclass
class TextCtx:
raw: str
words: list[str] = field(default_factory=list)
result: str = ""
@pipe
def lower(ctx: TextCtx) -> TextCtx:
ctx.raw = ctx.raw.lower()
return ctx
@pipe
def split(ctx: TextCtx) -> TextCtx:
ctx.words = ctx.raw.split()
return ctx
@pipe
def capitalize_each(ctx: TextCtx) -> TextCtx:
ctx.words = [w.capitalize() for w in ctx.words]
return ctx
@pipe
def join_space(ctx: TextCtx) -> TextCtx:
ctx.result = " ".join(ctx.words)
return ctx
pipeline = lower & split & capitalize_each & join_space
ok, ctx = pipeline.run(TextCtx(raw="PYTHON IS COOL"))
# ctx.result == "Python Is Cool"1
u/eanat May 10 '26
it would be great for scripting and system integration, but also can be disaster for other areas where ambiguity can be real pain.
TOOWTDI than TIMTOWTDI.
1
1
u/TuringTestDropout May 10 '26
I've had brief conversations with GvR about supporting functional programming more and he largely disagrees and regrets even allowing functools and map/filter into the standard library. I can understand his viewpoint that list comprehensions are enough and it makes idiomatic code harder to write and read.
The last time I talked about this with him was 2015 so maybe he's changed his mind about it since then, or there's been more influence from others since he's stepped back.
1
u/elven_mage May 10 '26
I'd very much love this, but without multiline lamba syntax you lose a lot of the real use.
There are people who have tried to make python stream libraries, look them up on GitHub. They are not as ergonomic as Java for this reason
1
u/gdchinacat May 10 '26
If I understand what you want correctly, I think this is pretty close:
from collections.abc import Callable, Iterable, Iterator
from typing import Self
mul = lambda x: x * 3
class mapiter[T](Iterable[T]):
def __init__(self, iter_: Iterable[T]):
self.iter_ = iter_
def __iter__(self) -> Iterator[T]:
return iter(self.iter_)
def __or__(self, func: Callable[[T], T]) -> Self:
return type(self)(func(x) for x in self.iter_)
l = mapiter(range(10))
assert list(l | mul | mul) == [x*3*3 for x in range(10)]
assert list(l | (lambda x: x ** 2)) == list(x**2 for x in range(10))I made it use Iterable rather than list as is best practice.
I disagree that it improves readability. But it does what you want. I doubt it would ever be accepted into the language syntax since it is so easy to do with existing mechanisms. Enjoy.
1
1
u/bakery2k May 10 '26
map() |> filter() |> list()
I feel like Guido would have been opposed to adding this to Python - he tended to dislike making the language too “functional”.
But nowadays the decision would rest with the Steering Council - who might well accept a well-written specification for it. They don’t really reject features based on philosophy any more.
1
u/IcarianComplex May 10 '26
Personally I just haven’t had much a need for this because most of my data manipulation needs happen at the SQL level, and that’s plenty expressive enough
1
u/aguspiza May 10 '26
you can implement some UFCS yourself or just check what others have implemented:
https://gist.github.com/ChenyangGao/d77fe5c3c738e6f9fb724a45e952dc0a
Or just migrate to nim language and enjoy 30x speed up with native UFCS.
https://github.com/narimiran/nim-basics/blob/master/code/ufcs.nim
1
u/saint_geser May 11 '26
There are some external libraries focused on functional programming, that implement different forms of chaining. For example, PuFunctional has seq() operator that chains operations in a readable manner.
But core python is, and has always been, very much against functional concepts making their way into the language. So wouldn't hold my breath.
1
u/Old-Eagle1372 May 11 '26
Overload operators, extend/overwrite functions. Create libraries, possibly open source so others can use them, this will increase your professional footprint
1
u/R3D3-1 May 11 '26
From my perspective, i it would remain vastly Limited in Python. Most use cases of piping I have at some point require a function that cannot be expressed well with Python's "expression only" lambdas, without also defining a bunch of auxiliary functions with no purpose other than turning statement-only constructs into functions.
1
u/Sherry-byte May 25 '26
The core team resistance is well-documented and the reasons are legitimate but the *readability problem* you're describing is real regardless of whether `|>` ever lands.
I actually ran into the same frustration recently and ended up building a small library for it *pipeflow*. It uses method chaining on a lazy wrapper the same pattern pandas already proved works so you get left-to-right readable pipelines today without waiting on a PEP:
```python
from pipeflow import Stream
result = (
Stream(users)
.filter(lambda u: u["active"])
.map(lambda u: u["name"].upper())
.sort()
.to(list)
)
```
Also supports `|` on plain lists if you prefer that style:
```python
range(10) | pipe(map, lambda x: x**2) | pipe(filter, lambda x: x > 5) | to(list)
```
Zero dependencies, fully lazy, fully typed. `pip install pipeflow` if you want to try it.
To your actual question though I wouldn't hold my breath on a native `|>`. The eager evaluation mismatch alone is a hard problem; in languages where pipes work well, the right-hand side is implicitly curried and waits for data. Python would have to silently rewrite your code to make that work, which goes against everything the language stands for.
0
156
May 10 '26
[removed] — view removed comment
17
u/Ragoo_ May 10 '26 edited May 10 '26
There was actually a new PEP for this, sponsored by Guido. See the discussion thread.
Coincidentially I just searched for it this morning to see what the curren state is but it seems to no longer be there and the discussion thread has no replies since February.
34
u/sausix May 10 '26
And you can do chaining with today's Python features and syntax already. I bet some frameworks already implemented that for theirselves.
This is possible and fits the idea already: pipe(func) | sin | cos | print
4
20
May 10 '26 edited May 10 '26
[removed] — view removed comment
3
u/tunisia3507 May 10 '26
Can any type checkers handle that pattern?
3
u/invalidusernamelol May 11 '26 edited May 11 '26
They can if you type the root function with a ParamSpec:
class Pipe[T]: __init__(self, val: T) -> None: self.val = val __gt__[**P, R](self, func: Callable[P, R]) --> Pipe[R]: return Pipe(func(self.val)) res = Pipe(...) > map > filter > listThis is not fully complete, but I've played around with pipeline classes that use this general syntax and it works pretty well. Since the type transformation is recalculated with each operation (func(T) -> R) you can chain your operations indefinitely as long as the return type of the previous function matches the input param type of the next function.
You do need to get into functools.partial if you have anything in the chain that can't be called with a single arg though.
Edit: here's a slightly more complete version ripped from a little testing module I have
type Proc[**P,T,R] = Callable[Concatenate[T, P], R] def consume[T](it: Iterable[T], n: int | None = None) -> None: deque(it, maxlen=0) if n is None else next(islice(it, n, n), None) def effect[**P,T](it: Iterable[T], func: Proc[P,T,Any], *args: P.args, **kwargs: P.kwargs) -> Iterable[T]: yield from (i for i in it if func(i, *args, **kwargs) or True) def transform[**P,T,R](it: Iterable[T], func: Proc[P,T,R], *args: P.args, **kwargs: P.kwargs) -> Iterable[R]: yield from (func(i, *args, **kwargs) for i in it) class Pipeline[T]: __slots__ = 'it', '_done' def __init__(self, it: Iterable[T]) -> None: self.it = it self._done = False def __iter__(self): return self.it def transform[**P,R](self, proc: Proc[P,T,R], *args: P.args, **kwargs: P.kwargs) -> Pipeline[R]: """Add a transform to the pipeline Transforms will mutate the data in the pipeline Example: ``` Pipeline(conn.logs).transform(log_filter, 'error').transform(upper) ``` """ return Pipeline(transform(self.it, proc, *args, **kwargs)) def tr[**P,R](self, proc: Proc[P,T,R], *args: P.args, **kwargs: P.kwargs) -> Pipeline[R]: """Alternate spelling of `Pipeline.transform`""" return Pipeline(transform(self.it, proc, *args, **kwargs)) # TODO: __or__ sould take Effect and Transform objects that contain procs and args def __or__[R](self, proc: Proc[...,T,R]) -> Pipeline[R]: """Used for chaining single arg transformations""" return Pipeline(transform(self.it, proc))1
u/Globbi May 10 '26
You mean checking if output of every function will fit input of the next one? I guess that's what would be needed. Honestly don't know and it's a good question if someone knows the answer.
5
u/justheretolurk332 May 10 '26
No, there is no way to specify that an iterable of callables should be coherent in this way. There are two ways I can think of to accomplish something similar. The simplest: You could require all of them to have the same input and output types. For something more flexible but also fairly advanced, you could write a class to hold the current chain of functions and make it generic in the return type of the current last function, with a method to append a new function (this method would enforce the type checking) and then return a new instance of the container class with the updated typing. You’d still have to build the chain one at a time though to get the typing benefits, so you’re probably not much better off.
150
u/_Denizen_ May 10 '26
That's piping, not chaining. This().is().chaining()
I dislike piping - it makes code less explicit i.e. harder to read.