Python假设变量是局部的

问题描述

首先,我要说的是这是一项作业,所需的行为不在我的控制之下。我正在创建一个名为globaltest.py的脚本,如果运行该文件调用文件中的函数,则该脚本的行为应完全相同。我都是从ipython上做的。它应该创建一个名为station_dict的字典,该字典可以在ipython控制台中访问,也可以用whos命令查看。@H_404_3@

from globaltest import file_to_dict
file_to_dict()

函数运行时,这应该产生一个名为station_dict的变量。@H_404_3@

这是简单运行脚本时的行为:@H_404_3@

Run globaltest

这还将创建一个名为station_dict的字典。@H_404_3@

问题是调用并使用函数file_to_dict不会在仅运行文件时创建变量。这是我的代码。感谢您的帮助。@H_404_3@

#!//bin/env python3

def main():

    global station_dict

    station_dict = {}

    station_dict['foo'] = 'bar'

def file_to_dict():

    global station_dict

    station_dict = {}

    station_dict['foo'] = 'bar'

if __name__ == '__main__':
    main()

以下是使用该功能的结果:@H_404_3@

Python 3.4.5 |Continuum Analytics,Inc.| (default,Jul  2 2016,17:47:47)
Type "copyright","credits" or "license" for more @R_748_4045@ion.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object',use 'object??' for extra details.

In [1]: from globaltest import file_to_dict

In [2]: file_to_dict()

In [3]: whos
Variable       Type        Data/Info
------------------------------------
file_to_dict   function    <function file_to_dict at 0x7f869f39cea0>

这是运行该程序的结果:@H_404_3@

Python 3.4.5 |Continuum Analytics,use 'object??' for extra details.

In [1]: run globaltest.py

In [2]: whos
Variable       Type        Data/Info
------------------------------------
file_to_dict   function    <function file_to_dict at 0x7fb92b7df8c8>
main           function    <function main at 0x7fb92b7df0d0>
station_dict   dict        n=1

解决方法

这里发生了两件事:

  1. Python所谓的“全局”并不是真正的全局,它是模块级别的(即在模块名称空间中)。因此,当您运行file_to_dict时,station_dictglobaltest的命名空间中被设置,尽管该命名空间未绑定(即未导入),所以station_dict是不可访问的。要访问它,您可以执行以下操作:

    import globaltest
    globaltest.station_dict
    
  2. IPython的%run在解释器的命名空间中运行代码。

也就是说,我不知道如何实现自己想要的。据我所知,一个函数无法在其调用名称空间中设置变量,尽管有可能进入inspect之类的黑手。

如果有帮助,您可以阅读有关sharing variables between modules的信息。