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?

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

Comments

9

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

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.