安装python为什么是modify_为什么在Python中修改父框架仅适用于模块框架?

我正在玩inspect.stack().我尝试修改父框架的局部变量,它似乎仅在父框架是模块级别时才起作用.以下代码显示了这一点(Python 2.7):

import inspect

def outer():

a = 10

print a

modify()

print a

def modify():

inspect.stack()[1][0].f_locals['a'] = 8888

outer()

a = 20

print a

modify()

print a

当父框架是一个函数时,为什么它不起作用?我可以让它运作吗?

解决方法:

模块堆栈框架的f_locals是它的globals()!

您可以通过在modify函数中打印与globals()的比较来验证这一点:

def modify():

print(inspect.stack()[1][0].f_locals is globals())

inspect.stack()[1][0].f_locals['a'] = 8888

通过此更改,输出为:

$python3 modify.py

10

False

10

20

True

8888

修改globals()返回的字典确实有效(参见this问题).显然是documented,模块用一个简单的dict实现它们的命名空间:

Modules are imported by the import statement (see section The import

statement). A module object has a namespace implemented by a

dictionary object (this is the dictionary referenced by the

func_globals attribute of functions defined in the module).

但是,locals()返回的字典不必是本地名称空间:

Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by

the interpreter.

在某些版本的python2中,修改locals()在函数内部使用exec语句时起作用.尝试在外部函数中添加exec”,看看输出是否发生变化(不能保证更改!但更有可能).

编辑:在python 2.7.6上,如果堆栈帧使用exec语句并且代码中没有对局部变量的赋值,我可以使它工作.例如,外部定义为:

def outer():

exec('a = 10')

print(a)

modify()

print(a)

locals()['a'] = 9999

print(a)

我得到输出:

$python2 modify.py

10

False

8888

9999

20

True

8888

但是如果我在exec之后添加一个= 10,如:

def outer():

exec('a = 10')

a = 10

print(a)

modify()

print(a)

locals()['a'] = 9999

print(a)

结果是:

$python2 modify.py

10

False

10

10

20

True

8888

我希望这能告诉你,分配给当地人工作的条件很少,绝对不可靠.

在python3中的AFAIK,locals()返回的字典总是只是真实命名空间的副本,因此修改它永远不会起作用.但是也不能保证.

f_locals属性返回的值只是locals()在该点返回的值.

总结:不,没有可靠的方法来修改通用堆栈帧的本地命名空间.您不能修改,删除或添加新的局部变量到通用堆栈框架的命名空间.

标签:python,python-2-7

来源: https://codeday.me/bug/20190528/1174025.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值