py-linq
py-linq is a little wrapper package that I wrote a few years ago for querying and transforming collections of Python objects. I found that the built-in Python querying and transforming tools were lacking. Specifically, the Python API made the code unreadable and difficult to understand. It made me long for the LINQ API’s available in .NET. So I decided to sit down and try to write it.
Getting started
To get started using py-linq, you will need to install it from PyPI.
pip install py-linq
To start querying and transforming your Python collection you will need to import Enumerable
.
from py_linq import Enumerable
Enumerable
Enumerable
is just the access point for the py-linq API. There are 2 ways to instantiate an Enumerable
object.
my_collection = Enumerable()
my_collection = Enumerable(collection)
The collection class has to implement the __iter__
dunder. The default constructor Enumerable()
is just Enumerable(collection)
where collection is []
. Enumerable
itself is an iterable.
LINQ methods
The methods encapsulated by the Enumerable
class can be either executing functions or non-executing. Executing functions will iterate over the collection when it is called. Non-executing functions will not iterate over the collections. These functions will be executed only when the collection does get iterated over.
Once you have created an Enumerable
instance, the LINQ methods will become available to you. The methods implemented at this point are:
- select
- order_by
- order_by_descending
- skip
- take
- where
- select_many
- add
- concat
- join
- intersect
- except_
- to_list
- count
- sum
- min
- max
- avg
- median
- any
- element_at
- element_at_or_default
- first
- first_or_default
- last
- last_or_default
- contains
- group_by
- distinct
- group_join
- union
- all
- aggregate
- append
- prepend
- empty
- range
- repeat
- reverse
- skip_last
- skip_while
- take_last
- take_while
- zip
- default_if_empty
- single
- single_or_default
- to_dictionary