views:

113

answers:

3

Let's say we have a module m:

var = None

def get_var():
    return var

def set_var(v):
    var = v

This will not work as expected, because set_var() will not store v in the module-wide var. It will create a local variable var instead.

So I need a way of referring the module m from within set_var(), which itself is a member of module m. How should I do this?

+10  A: 
def set_var(v):
    global var
    var = v

The global keyword will allow you to change global variables from within in a function.

Jeffrey Aylesworth
+8  A: 

As Jeffrey Aylesworth's answer shows, you don't actually need a reference to the local module to achieve the OP's aim. The global keyword can achieve this aim.

However for the sake of answering the OP title, How to refer to the local module in Python?:

import sys

var = None

def set_var(v):
    sys.modules[__name__].var = v

def get_var():
    return var
Ben James
+3  A: 

As a follow up to Jeffrey's answer, I would like to add that, in Python 3, you can more generally access a variable from the closest enclosing scope:

def set_local_var():

    var = None

    def set_var(v):
        nonlocal var  
        var = v

    return (var, set_var)

# Test:
(my_var, my_set) = set_local_var()
print my_var  # None
my_set(3)
print my_var  # Should now be 3

(Caveat: I have not tested this, as I don't have Python 3.)

EOL