Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获取新定义的变量_Python_Python 3.x_Dictionary_Global Variables - Fatal编程技术网

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