Python Pitfalls #1: Global Variables

When we define global variables in Python, we could access it inside a function just as it’s a local variable. For example, following code print out the value of the global variable, count, which is 99.

global-variables-01

Figure 1-1. Print out global variable count.

However, if we want to update the value of global variable, there will be an error if we handle it just like local variables. The following code add one to global variable, count, and come across with an error message: UnboundLocalError……. The reason for this is because Python thought count is a local variable when we try to update it. For a local variable, we need to declare it first before modifying its value.

global variables 2

Figure 1-2. Error for modifying global variable, count.

To fix it, we need to add a global declaration for the variable count as follows:

global variables 3

Figure 1-3. Add global declaration for global variable before updating it.

Note that we only need to do this for immutable data types like int, str, bool, etc. For mutable data types like list we do not need to add global declaration. See the following sample code for details.

global variables - 4

Figure 1-4: Global declaration is not needed for mutable global variable like list.


Python编程陷阱 #1:全局变量


当我们在Python程序里声明一个全局变量,就可以在函数里面读取它的值,就好像局部变量一样。图例 1-1 里面我们在函数 f1 中打印全局变量 count 的值,99,没有任何问题。

但是如果我们要在函数内部修改全局变量的值,就会碰到问题。图例 1-2 的代码里面,我们把全局变量 count 的值加1,就会看到错误信息:UnboundLocalError……。这是因为修改count的值,Python会认为count是一个局部变量,如果局部变量没有声明就直接修改,那么就会出现上面的错误。

修改这个错误的方法是在函数里面增加一个全局变量的声明,如图例 1-3 中的代码那样,就不会有问题。

注意:这个问题只会出现在Python的不可变数据类型上,譬如数字、字符串、布尔型等,对于可变数据类型如列表,就不需要做这样的处理,可以直接修改,如图例1-4中对全局变量array的操作那样。