sagemath/singlecell — Issue #230: Iterators and Nested Interacts
Author: kramer314
Created: 2012-01-22 04:07:26+00:00
State: open
Labels: interacts

Preparsed generators such as ```(0..10)``` are supposedly supported for interacts. For instance, the following:

```python
@interact
def f(n=(0..10)):
print n
```

works as expected, rendering a DiscreteSlider with values ranging from 1 to 10.

However this:

```python
c=1
@interact
def f(n=(0..10)):
global c
print '%d slider(s) generated'%c
for i in range(n):
c+=1
interact(f)
```

A slider renders once, but errors occur once it is updated, because the ```ellipsis_iter``` generator has been exhausted, so any new instances of the interacted function will think ```n=[]``` rather than ```n=[0,1,2,3,4,5,6,7,8,9,10]``` since the same generator object is being referenced by each instance. The error occurs because the default value of a list of values for a DiscreteSlider is 0, and attempting to return the 0th value of an empty list results in an IndexError.

The code can be modified to function as expected with the following change:

```python
c=1
@interact
def f(n=tuple((0..10))):
global c
print '%d slider(s) generated'%c
for i in range(n):
c+=1
interact(f)
```

but that doesn't solve the problem of generators being incompatible with nested interacts - it merely avoids the problem by passing in a container object (a tuple) that returns a new iterator each time it's accessed, rather than a single iterator object that can become exhausted.

If Sage's iterator preparsing is supported for interact arguments, it seems logical that nested interacts should also support them, but that would seem to require mimicking or implementing support for multiple iteration passes through Sage's iterator objects (which I'm not sure is feasible independent of patching Sage). At the very least, the interact documentation should be updated with caveats about nested interacts.