如何在Python中引用本地模块?

时间:2022-01-29 21:26:05

Let's say we have a module m:

假设我们有一个模块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.

这将无法按预期工作,因为set_var()不会在模块范围的var中存储v。它将创建一个局部变量var。

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?

所以我需要一种从set_var()中引用模块m的方法,它本身就是模块m的成员。我该怎么做?

3 个解决方案

#1


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.

正如Jeffrey Aylesworth的回答所示,您实际上并不需要参考本地模块来实现OP的目标。 global关键字可以实现这一目标。

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

但是为了回答OP标题,如何在Python中引用本地模块?:

import sys

var = None

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

def get_var():
    return var

#2


10  

def set_var(v):
    global var
    var = v

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

global关键字允许您在函数中从内部更改全局变量。

#3


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:

作为Jeffrey的回答的后续内容,我想补充一点,在Python 3中,您可以更一般地从最近的封闭范围访问变量:

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

(警告:我没有测试过这个,因为我没有Python 3.)

#1


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.

正如Jeffrey Aylesworth的回答所示,您实际上并不需要参考本地模块来实现OP的目标。 global关键字可以实现这一目标。

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

但是为了回答OP标题,如何在Python中引用本地模块?:

import sys

var = None

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

def get_var():
    return var

#2


10  

def set_var(v):
    global var
    var = v

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

global关键字允许您在函数中从内部更改全局变量。

#3


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:

作为Jeffrey的回答的后续内容,我想补充一点,在Python 3中,您可以更一般地从最近的封闭范围访问变量:

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

(警告:我没有测试过这个,因为我没有Python 3.)