Ask Your Question

Revision history [back]

In case you prefer indexing syntax x[i] over function call syntax x(i), you can use the following helper class:

from collections import defaultdict

class keydefaultdict(defaultdict):
    def __missing__(self, key):
        if self.default_factory is not None:
            ret = self[key] = self.default_factory(key)
            return ret
        else:
            raise KeyError(key)

Then:

sage: x = keydefaultdict(lambda i: SR.var('x_{}'.format(i)))
sage: x[1]
x_1
sage: x[12]
x_12