Skip to content

Commit f5af07b

Browse files
committed
Add slicing support to the GeneratorContainer class
Add slicing support to the GeneratorContainer class and attempt to optimize the number of requests needed to fullfil a slicing request. Set the `max=` parameter to the slice-stop value, if `max` wasn't already specified as a parameter in the wrapped generator function call.
1 parent f779b5e commit f5af07b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

ciscosparkapi/generator_containers.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
import functools
2525
import inspect
26+
from itertools import islice
2627

2728

2829
__author__ = "Chris Lunsford"
@@ -80,6 +81,43 @@ def __iter__(self):
8081
"""Return a fresh iterator."""
8182
return self.new_generator()
8283

84+
def __getitem__(self, item):
85+
"""Slice a generator container.
86+
87+
This is a convenience feature that, with a minor optimization, is
88+
essentially syntactic sugar for:
89+
90+
`itertools.islice(GeneratorContainer, start, stop, step)`
91+
92+
This method attempts to optimize the spark request page size for
93+
slicing by setting the `max` parameter to the stop-value of the slice.
94+
If the sliced sequence can be returned in a single response, it will
95+
be. Otherwise automatic pagination will take care of returning enough
96+
pages for the data to be sliced. If `max=` was already specified as a
97+
parameter to the generator function wrapped by the GeneratorContainer,
98+
this optimization will not change the value.
99+
100+
Args:
101+
item(slice): A slice object specifying the start, stop and step.
102+
103+
Returns:
104+
itertools.islice: An itertools.islice object slicing the
105+
GeneratorContainer's wrapped generator function.
106+
107+
"""
108+
if isinstance(item, slice):
109+
arguments = self.arguments.copy()
110+
arguments.setdefault('max', item.stop)
111+
return islice(
112+
self.generator_function(**arguments),
113+
item.start,
114+
item.stop,
115+
item.step,
116+
)
117+
else:
118+
raise IndexError("GeneratorContainers support slicing only. "
119+
"Indexing is not supported.")
120+
83121

84122
def generator_container(generator_function):
85123
"""Function Decorator: Containerize calls to a generator function.

0 commit comments

Comments
 (0)