Tim Molendijk
Tim Molendijk

Reputation: 1046

How to refer to the local module in Python?

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?

Upvotes: 3

Views: 1056

Answers (3)

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94515

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

Upvotes: 3

Ben James
Ben James

Reputation: 125177

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

Upvotes: 9

Jeffrey Aylesworth
Jeffrey Aylesworth

Reputation: 8490

def set_var(v):
    global var
    var = v

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

Upvotes: 10

Related Questions