处理模块中未定义的全局 (python)

Dealing with undefined global in module (python)

所以我有一些 python 代码是这样的

import mymodule

sum_global= mymodule.populateGlobalList("bigdict.txt")

等等...使用 mymodule 中的代码,包括方法

def populateGlobalList(thefile):
    #do the stuff

目前一切顺利。

但是在 mymodule 的其他地方我有一个方法说

def usefulFunction(arg1, arg2):
   #lotsofstuff
   if arg1 not in sum_global:
      #add to list

所以解释器在未定义的 sum_global 上跳闸,这是有道理的。现在 usefulFunction 可以将 sum_global 作为参数,至少在理论上是这样。但是 sum_global 是一本英语词典,广泛用于检查遇到的单词是否为英语单词(或至少拼写正确)。由于这种情况经常发生,将其设为本地只会让人感到不必要的尴尬。

另一方面,只是在模块中声明一个全局的 sum_global(本质上是为了愚弄解释器),目的是将这个空容器填充到导入 mymodule 的程序感觉完全错误。

针对这种情况的声音设计是什么?

每个模块都有自己的全局命名空间。您将 sum_global 添加到错误的模块,它不在 mymodule.

要么将 sum_global 放入 mymodule 中,要么将其作为参数传递给需要它的函数。

听起来好像您想推迟计算 sum_global 值,直到您有了文件名;您可以 populateGlobalList() 在此处设置全局;这一切都在 mymodule:

sum_global = None

def populateGlobalList(filename):
    global sum_global
    if sum_global is None:
        sum_global = "result of your population work"

此函数不return数据,它设置模块中的全局变量(假设尚未设置)。

但是,您应该尝试避免创建这样的全局变量。由于您的模块的用户必须提供文件名,如果用户代码跟踪 populateGlobalList() 调用的结果并且 显式 将其传递到 usefulFunction()`通话:

import mymodule

sum_global = mymodule.populateGlobalList("bigdict.txt")

result = mymodule.usefulFunction(arg1, arg2, sum_global)

并重组 usefulFunction() 以要求这样的论点。

下一步是让您的模块为此使用 class

class MyClass(object):
    def __init__(self, filename):
        self._populate()

    def _populate(self):
        self.sum = "result of your population work"

    def useful_function(self, arg1, arg2):
        # do work with self.sum

然后到处使用 class:

 interesting_object = mymodule.MyClass('bigdict.txt')
 result = interesting_object.useful_function(arg1, arg2)