How to access a local module in Python?

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 it set_var()will not be stored vin the system-wide var. Instead, it will create a local variable var.

So, I need a way to pass a module mfrom set_var(), which itself is a member of the module m. How can I do it?

+3
source share
3 answers

As Jeffrey Alesworth’s answer shows, you don’t really need a link to a local module to achieve the OP goal. Keyword globalcan achieve this goal.

OP, Python?:

import sys

var = None

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

def get_var():
    return var
+9
def set_var(v):
    global var
    var = v

.

+10

In response to Jeffrey's answer, I would like to add that in Python 3 you can access the variable more widely from the nearest enclosing area:

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

(Caution: I have not tested this since I do not have Python 3.)

+3
source

Source: https://habr.com/ru/post/1724493/


All Articles