Ask Your Question
0

injecting names into global namespace doesn't work with doctest

asked 2013-08-12 17:39:10 +0100

paragon gravatar image

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.)

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
1

answered 2013-08-12 17:53:04 +0100

Nicolas M Thiéry gravatar image

updated 2013-08-12 17:54:47 +0100

sage.misc.misc.inject_variable might be your friend.

edit flag offensive delete link more

Comments

Thank you! It is my friend!

paragon gravatar imageparagon ( 2013-08-12 18:20:45 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2013-08-12 17:39:10 +0100

Seen: 311 times

Last updated: Aug 12 '13