views:

30

answers:

1

Hi all,

I encountered a problem with the scope variables have when IPython is invoked at the end of a python script. All functions I call in the script itself can modify variables, which will subsequently be used by other functions. If I call the same functions in ipython, the scripted ones can access the changed variables but variables which existed when ipython was called don't change. Thus my question: How do I propagate the global variables into ipython? (I could do something like A=globals()['A'] of course but thats ugly)

A: 

You could create a class with a static method (decorator: @staticmethod) that returns a singleton instance of that class. That object can contain any number of members that function as globals.

class Globals:
    __master = None
    somevar = 1
    othervar = 2

    @staticmethod
    def get_master():
        if Globals.__master is None:
            Globals.__master = Globals()

        return Globals.__master

g1 = Globals.get_master()
g2 = Globals.get_master()
g1.somevar += 1

print g1.somevar
print g2.somevar

Prints:

2
2
James Roth
where is staticmethod defined? Is it a builtin?
BandGap
It's built in to python 2.4 and later.
James Roth