I have been dabbling a bit in Python recently, even though my main focus is still C#. Hence, one thing I’ve really missed is LINQ. And when I say LINQ, I mostly mean LINQ to Objects and the extension methods on the Enumerable class. I’m not a big fan of the “from… select…where” syntax. While LINQ can be a bit overwhelming at first, there are now quite a few LINQ methods I can no longer do without.
There are two articles by Mark Heath on this topic I can recommend:
- list comprehension and generators, two concepts used to tackle problems that in C# would be tackled with LINQ
- Python methods that come closest to LINQ methods (mostly from the itertools
What I think this “Pythonic” approach lacks is LINQ’s ability to chain together operations by writing them out left to right, as each LINQ method operating on an instance of IEnumerable returns another IEnumerable.
There are those that say that Python does not need something like LINQ. I disagree. The fluent syntax of LINQ method calls chained together is a major readability improvement over the classic approach of nested function calls.
Luckily, there are open-source projects filling this void, e.g.
- py-linq is pretty straightforward with methods named exactly as their LINQ counterparts on a class called Enumerable.
- asq is another one with pretty similar design principles.
- And then there is RxPy a library for reactive programming in Python which has chaining like LINQ methods and a whole lot more.