Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

injecting names into global namespace doesn't work with doctest

Here is a minimal example of the problem I am running into. I have a file "MyClass.py":

class MyClass(object):
    def __init__(self,subscript):
        self.subscript = subscript

    def __repr__(self):
        return "MyClass " + str(self.subscript)

def make_MyClass(n):
    """
    Creates n MyClass instances and assigns them to to variables A0, ..., A(n-1).

    Examples::

        sage: make_MyClass(3)
        sage: A0
        MyClass 0
        sage: A2
        MyClass 2
        sage: A1.subscript
        1
    """
    for i in range(n):
        globals()["A" + str(i)] = MyClass(i)

If I doctest it, I get NameError: name 'A0' is not defined, but if I just load the file and type in the commands, it works how I want it to. It must be something about how globals() interacts with doctest.

I know it is possible to make this work, because for example the function var does something like this. I tried looking at the var.pyx source, but it looks like they are doing the same thing as me. (There is a comment about globals() being the reason that it had to be Cython. I tried making the example above a pyx, but that didn't seem to help.)