KeyError: global not accessible through imported class

KeyError: global not accessible through imported class

我正在尝试计算化学方程式中元素的数量。我以某种方式创建的调试器无法访问程序中的全局变量。具体来说,我正在尝试访问 carrotsleft 没有被添加到堆栈中。有什么想法吗?

Debug.py

class Debugger(object):
    def __init__(self,objs):
        assert type(objs)==list, 'Not a list of strings'
        self.objs = objs
    def __repr__(self):
        return '<class Debugger>'
    def show(self):
        for o in self.objs:
            print o,globals()[o] #EDIT

Chemical_Balancer.py

from Debug import Debugger

def directions():
    print 'Welcome to the chem Balancer.'
    print 'Use the following example to guide your work:'
    global left #LEFT IS GLOBAL
    left = 'B^6 + C^2 + B^3 + C^3 + H^9 + O^4 + Na^1'
    print left
    print "#Please note to use a 'hat' when entering all elements"
    print '#use only one letter elements for now'
# left = raw_input('enter formula:')  #enter formula to count
directions()

chem_stats = {}
chem_names = []
chem_names = []
chem_indy = []

for c in range(len(left)):
    if left[c].isalpha() and left[c].isupper():
        chars = ''
        if left[c+1].islower():
            chars += left[c]+left[c+1]
        else:
            chars += left[c]
        #print chars
        chem_indy.append(c)
        chem_names.append(chars)

carrots = [x for x in range(len(left)) if left[x]=='^']

debug = Debugger(['carrots','chem_names','chem_indy','chem_stats']) # WITHOUT LEFT
debug.show()

错误信息:

Traceback (most recent call last):
  File "C:\Python27\#Files\repair\Chemical_Balancer.py", line 38, in <module>
    debug.show()
  File "C:\Python27\lib\site-packages\Debug.py", line 12, in show
    print o,globals()[o]
  File "<string>", line 1, in <module>
KeyError: 'carrots'

关于 left 变量的具体错误:

当您说变量是全局变量时,python 知道在使用其名称时必须在全局命名空间中查找它。但是在代码中 left 还没有分配到这样的命名空间中。

如您所见,left被注释掉了

#left = raw_input('enter formula:')  #enter formula to count

通过删除行开头的 # 取消注释,因此 directions 函数内的行

global left

可以找到它,下面的说明也可以。

关于实施: 允许调试器知道在哪里寻找变量的一种解决方案,即在哪个模块中,可以是在创建模块时向其提供模块的名称。然后调试器对象可以通过 sys.modules[module_name].__dict__

访问创建它的模块的全局变量

debugger.py

import sys
class Debugger(object):
    def __init__(self, module_name, objs):
        assert type(objs)==list,'Not a list of strings'
        self.objs = objs
        self.module_name = module_name
    def __repr__(self):
        return '<class Debugger>'
    def show(self):
        for o in self.objs:
            print o, sys.modules[self.module_name].__dict__[o]

chemical_balancer.py

import debugger as deb
a = 1
b = 2
d = deb.Debugger(__name__, ['a', 'b'])
print(d.objs)
d.show()
a = 10
b = 20
d.show()

产生

['a', 'b']
a 1
b 2
a 10
b 20

如您所见,每次调用 show 方法时,调试器都会打印变量的当前值

我发现 this SO Q&A 内容丰富且有帮助。