Python 如何获取新定义的变量
我试图找到一种方法来隔离代码中某个点之后定义的变量。对于此任务,我编写了以下内容:Python 如何获取新定义的变量,python,python-3.x,dictionary,global-variables,Python,Python 3.x,Dictionary,Global Variables,我试图找到一种方法来隔离代码中某个点之后定义的变量。对于此任务,我编写了以下内容: from copy import deepcopy beginning = deepcopy(dict(globals())) # getting the current stand a = 5 # new variable gets defined # possibly more code with other definitions here end = {k: v for k, v in dict(g
from copy import deepcopy
beginning = deepcopy(dict(globals())) # getting the current stand
a = 5 # new variable gets defined
# possibly more code with other definitions here
end = {k: v for k, v in dict(globals()).items() if k not in beginning}
在打印end
时,我希望只看到{'a':5}
,但事实并非如此。取而代之的是,我把整个范围重新设计了一遍
因此,字典理解上的if
条件显然失败。所以我有两个问题:
p.S:我正在使用Python3.6.1我得到
类型错误:应用deepcopy()
时无法pickle模块对象
,但忽略这一点(并进行浅拷贝),您可以获得所需的输出
我认为您在概念上的错误是忘记了开头
也已添加到globals()
dict
,需要在if
子句中排除:
>>> beginning = dict(globals())
>>> a = 5
>>> end = {k: v for k, v in dict(globals()).items() if k not in beginning and k != 'beginning'}
>>> end
{'a': 5}
在python3.5中一字不差地运行代码时,我得到了一个
AttributeError:“NoneType”对象在deepcopy发生的行中没有属性“update”
。@shuttle87