Clone this wiki locally
Pynq – Python Language Integrated Query
Microsoft created Linq (Language Integrated Query) using Expression trees, which is a math concept on how to parse operations into trees in a way that you can analyze the operations independently from the result.
Pynq is an implementation in Python of the Expression Tree theory and some of the providers. There will be more providers gradually, but Pynq will strive to make it as easy as possible to write your own provider.
To install Pynq check Installing.
Introduction to Expression Trees
Since Pynq uses solely expression trees as means to the provider to parse whatever it needs to parse, it means that anyone can implement a provider to basically anything that can be queried.
Expression Trees are a pretty simple concept to grasp (even though they are complex to implement). Let’s see an example:
Let’s say we want an expression tree of the “2+3” expression. This is what it evaluates to:
BinaryExpression("Add", ConstantExpression(2), ConstantExpression(3))
What that means is that a provider can now parse the expression you informed in order to find that you wanted the sum of 2 and 3, whatever that means in the given context.
If you want to know more about how Pynq implements expression trees and the ones available to you, check the Expression Trees page.
Pynq comes with a factory called From (from is a keyword in Python, thus we chose to ignore PEP-81).
From is the entry-point to Pynq. You use From to specify the Pynq Provider you want to use (we’ll talk more about Pynq Providers later). The following is a typical Pynq query:
filtered_collection = From(some_collection).where("item.property > 10").select_many()
This code gets all the items in the given collection (some_collection) that have the property “property” greater than 10. The key thing to note here is the From(some_collection) call.
The From method takes a pynq provider as parameter. Passing in collections is just a shortcut to use the CollectionProvider. If you pass Tuple or List instances to the From method, Pynq will assume you want CollectionProvider.
Nothing stops you from using other providers, though. Imagine we want to write a Twitter2 provider. We could use it like so:
tweets = From(TwitterProvider("user","password")) .where("item.author == 'heynemann'") .select_many()
This code selects all the tweets that have heynemann as author from the tweet list of “user”. This provider is not implemented (maybe yet), but it’s completely feasible.
To know more about the Pynq Factory you can check the Pynq Factory page.