使用try/except时Python中的奇怪变量范围
当我运行此程序时,我得到以下结果:使用try/except时Python中的奇怪变量范围,python,Python,当我运行此程序时,我得到以下结果: foo = 'asdf' bar = 'asdf' foobar = 'asdf' def test(): def get_foo(): print 'foo = ' + foo def get_bar(): try: print 'bar = ' + bar except Exception as e: print 'nobody set bar :(' def get_foobar():
foo = 'asdf'
bar = 'asdf'
foobar = 'asdf'
def test():
def get_foo():
print 'foo = ' + foo
def get_bar():
try:
print 'bar = ' + bar
except Exception as e:
print 'nobody set bar :('
def get_foobar():
try:
foobar
except Exception as e:
print e
foobar = "nobody set foobar :("
print foobar
print 'trying to get foo'
get_foo()
print '\ntrying to get bar'
get_bar()
print '\ntrying to get foobar'
get_foobar()
test()
我设置了三个变量:foo,bar,foobar。然后,我使用三个嵌套函数将它们打印出来:get_foo、get_bar和get_foobar
get_foo只需打印foo
获取工具栏打印工具栏并检查异常
get_foobar使用try except来确保在打印之前设置了foobar
不知怎的,get_foobar失败了 将行
global foobar
添加到get\u foobar()
这告诉字节码编译器您希望使用全局作用域而不是局部作用域引用此函数中的变量
赋值隐式地将变量的作用域更改为整个函数作用域的局部
字节码:
trying to get foo
foo = asdf
trying to get bar
bar = asdf
trying to get foobar
local variable 'foobar' referenced before assignment
nobody set foobar :(
注意使用LOAD\u FAST
和STORE\u FAST
代替LOAD\u GLOBAL
和STORE\u GLOBAL
。有一个操作码列表供参考
您可以使用此代码快速转储函数的字节码:
## code input (local)
def test():
print foobar
foobar = 2
## bytecode output
#
# 3 0 LOAD_FAST 0 (foobar)
# 3 PRINT_ITEM
# 4 PRINT_NEWLINE
#
# 4 5 LOAD_CONST 1 (2)
# 8 STORE_FAST 0 (foobar)
# 11 LOAD_CONST 0 (None)
# 14 RETURN_VALUE
## code input (global)
def test():
global foobar
print foobar
foobar = 2
## bytecode output
#
# 4 0 LOAD_GLOBAL 0 (foobar)
# 3 PRINT_ITEM
# 4 PRINT_NEWLINE
#
# 5 5 LOAD_CONST 1 (2)
# 8 STORE_GLOBAL 0 (foobar)
# 11 LOAD_CONST 0 (None)
# 14 RETURN_VALUE
Martijn Pieters称之为。由于您在函数中对
foobar
进行了赋值,因此创建了一个新的局部变量foobar
,但这是在编译时而不是运行时发生的,这就是为什么try
块中已经存在未初始化版本的foobar
的原因。赋值将变量标记为局部变量。
import compiler, dis
code = compiler.compile('''
def test():
print foobar
foobar = 2
''', '__main__', 'exec')
dis.dis(code.co_consts[1])