Using Results¶
The following examples demonstrate squint’s Result
class.
This document builds on the previous Making Selections and
Building Queries tutorials.
Get Started¶
We will get started the same way we did in the previous tutorials. Begin
by starting the Python interactive prompt in the same directory as the
example.csv
file. Once you are at
the >>>
prompt, import squint and load the data:
>>> import squint
>>> select = squint.Select('example.csv')
Creating a Result Object¶
Typically, we create Result
objects by calling a Query’s
execute()
method:
>>> select('A').execute()
<Result object (evaltype=list) at 0x7ff5f372>
We can also create Results directly with the following syntax:
>>> iterable = [1, 2, 3, 4, 5]
>>> squint.Result(iterable, evaltype=list)
<Result object (evaltype=list) at 0x7ff5f38d>
The evaltype
Attribute¶
The evaltype
attribute—short
for “evaluation type”—indicates the type of container
that a Result represents:
>>> result = select('A').execute()
>>> result.evaltype
<class 'list'>
Eager Evaluation¶
When a Result is eagerly evaluated, all of its contents
are loaded into memory at the same time. Doing this returns
an container of elements whose type is determined by the
Result’s evaltype
.
Use the fetch()
method to eagerly
evaluate the result and get its contents:
>>> result = select('A').execute()
>>> result.fetch()
['x', 'x', 'y', 'y', 'z', 'z']
For many results, eager evaluation is entirely acceptible. But large results might use a lot of memory or even exceed the memory available on your system.
Lazy Evaluation¶
When a Result is lazily evaluated, its individual elements are computed one-at-a-time as they are needed. In fact, the primary purpose of a Result object is to facilitate lazy evaluation when possible.
Use a for
loop to lazily evaluate the result and get its
contents:
>>> result = select('A').execute()
>>> for element in result:
... print(element)
...
...
x
x
y
y
z
z
For each iteration of the loop in the above example, the next element is evaluated and the previous element is discarded. At no point in time do all of the elements occupy memory together.
Note
When lazily evaluating a Result, you are free to check the
evaltype
but it is never actually
used to create an object of that type.