前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >最易写出bug?Python命名空间和作用域介绍

最易写出bug?Python命名空间和作用域介绍

作者头像
MeteoAI
发布2019-08-12 14:40:33
7110
发布2019-08-12 14:40:33
举报
文章被收录于专栏:MeteoAI

本文主要介绍一下Python命名空间和作用域。

简单的说,命名空间就是一种“名称-对象”的映射表,使得我们可以通过对象指定的名称来访问它们。

比如meteoai=666666我们可以用meteoai来访问到具体的值666666

在python中,具体的命名空间就是一个 字典(dictionary) ,它的键就是变量名,它的值就是那些变量的值(对象)。

A namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries。

但是命名空间可以相互独立地存在,可以按照一定的层级组织起来,每个命名空间有其对应的作用域。举个简单的例子:

代码语言:javascript
复制
global_a = "I am in global scope" 
def function_a():
    local_a = "I am in function_a"
    return local_a
print(global_a)
print(function_a())
print(local_a) # 局部变量local_a无法在全局空间中被访问到,会报错

# output:
I am in global scope
I am in function_a
NameError: name 'local_a' is not defined

function_a中的变量local_amodule level的变量global_a就在不同的命名空间中,所以print(local_a)会报错。

要想使得local_a可以在函数外部被访问到,只需要加一行代码:

代码语言:javascript
复制
global_a = "I am in global scope" 
def function_a():
    global local_a
    local_a = "I am in function_a"
    return local_a
print(global_a)
print(function_a())
print(local_a)

# output:
I am in global scope
I am in function_a
I am in function_a

python中的关键字defclasslamda等能够改变变量作用域,即它们代码块中的变量,不可在外部访问。而 iftryforwhile 等关键字不涉及变量作用域的更改,即它们代码块中的变量,可在外部访问。

而python中对变量命名空间的搜索基于LEGB规则,按此顺序依次进行搜索。首先从当前作用域开始寻找变量,如果没找到就往上一层作用域寻找,没找到就再上一层......

LEGB:

•Local(L): Defined inside function/class•Enclosed(E): Defined inside enclosing functions(Nested function concept)•Global(G): Defined at the uppermost level•Built-in(B): Reserved names in Python builtin modules

即:当前作用域局部变量->外层作用域变量->再外层作用域变量->......->当前模块全局变量->pyhton内置变量,如果还是找不到会抛出NameError异常。

代码语言:javascript
复制
a_var = 'global value'
def outer():
    a_var = 'enclosed value'
    def inner():
        a_var = 'local value'
        print(a_var)
    inner()
outer()

# output
local value

所以我们要谨慎使用from a_module import *,因为这条语句向global namespace 导入了一些变量,可能会存在重名变量被覆盖的风险。

global 和 nonlocal

•global: 全局变量•nonlocal: 外层嵌套函数的变量

python 函数中变量的作用域和其他语言类似。如果变量是在函数内部定义的,即为局部变量,只在函数内部有效。一旦函数执行完毕,局部变量就会被回收,无法访问。相对应的,全局变量则是定义在整个文件层次上的,可以在文件内的任何地方被访问,在函数的内部也是可以的。但是我们不能在函数内部随意修改全局变量的值。会报错:

代码语言:javascript
复制
A = 1
def func1():
    A+=1

func1()

# output
UnboundLocalError: local variable 'A' referenced before assignment

这是因为python会默认函数的内部变量为局部变量,但发现在函数内部又没有对变量进行声明,所以就会报错。如果要执行这样的操作,需要在函数内部加上global A这个声明。

global关键字用来在函数或其他局部作用域中使用全局变量。但是如果不修改全局变量也可以不使用global关键字。

代码语言:javascript
复制
a_var = 'global value'
def a_func():
    global a_var
    a_var = 'local value'
    print(a_var, '[ a_var inside a_func() ]')
print(a_var, '[ a_var outside a_func() ]')
a_func()
print(a_var, '[ a_var outside a_func() ]')

# output:
global value [ a_var outside a_func() ]
local value [ a_var inside a_func() ]
local value [ a_var outside a_func() ]

同样的,我们可以使用nonlocal关键字在嵌套函数的内部改变改变嵌套作用域的变量(L改变E中的变量)。

函数的嵌套可以保证内部函数的隐私,内部函数只能被其外部函数所访问,不会暴露在全局作用域中。因此可以用内部函数来封装一些隐私数据,如用户名密码等,可以提高程序的安全性,同时可以提高程序的运行效率。

代码语言:javascript
复制
a_var = 'global value'
def outer():
    a_var = 'local value'
    print('outer before:', a_var)
    def inner():
        nonlocal a_var 
        a_var = 'inner value'
        print('in inner():', a_var)
    inner()
    print("outer after:", a_var)
outer()

## output:
outer before: local value
in inner(): inner value
outer after: inner value

使用总结:

1、局部作用域改变全局变量(L中修改G中的变量)用globalglobal同时还可以定义新的全局变量

2、内层函数改变外层函数变量(在L中修改E中的变量)用nonlocalnonlocal不能定义新的外层函数变量,只能改变已有的外层函数变量,同时nonlocal不能改变全局变量。

闭包(closure)

闭包和前面所说的嵌套函数类似,不同的是,外层函数返回的是一个函数。例如:

代码语言:javascript
复制
def calc_power(n):
    def inner_power(base):
        return base ** n
    return inner_power # 返回值是一个函数

calc_square = calc_power(2) # 计算一个数的平方
calc_cube = calc_power(3) # 计算一个数的立方 
print(calc_square)
print(calc_cube)

print(f"The square of 6 is {calc_square(6)}")
print(f"The cube of 3 is {calc_cube(3)}")

# output
<function calc_power.<locals>.inner_power at 0x10cf998c8>
<function calc_power.<locals>.inner_power at 0x10cfd60d0>
The square of 6 is 36
The cube of 3 is 27

合理使用闭包可以使得代码更加简洁,可读性更好。闭包常常和装饰器(decorator)一起使用。

global variable 和 free variable

global variable是作用范围是整个模块(G)的变量, 而free variable是某个代码块中引用但不是在此处定义的变量。global variable 和 free variable并没有必然的联系。举个例子:

代码语言:javascript
复制
############
## example 1
############
a = 1
def func_a():
    print(a) 
# 这里的a是global variable,同时在func_a()中,a也是free variable

############
## example 2
############
a = 1
def func_b():
    a = 2
    print(a) 
# 这里的a分别是global variable和local variable,但是没有free variable

############
## example 3
############
def func_c():
    a = 1
    def func_d():
        b = 2
        print(a)
        print(b)
# 在func_d()中a是free variable,但是这里没有全局变量

dir(), globals()和locals()

globals()返回全局的符号表(global symbol table)。locals() 函数会以字典类型返回当前位置的全部局部变量(local symbol table)。

A symbol table is a data structure maintained by a compiler which contains all necessary information about the program. These include variable names, methods, classes, etc. There are mainly two kinds of symbol table. 1.Local symbol table ==> globals()2.Global symbol table ==> locals()

关于namespace和symbol table:

A symbol table is an implementation detail. Namespaces are implemented using symbol tables, but symbol tables are used for more than just namespaces. For example, functions have their own symbol table for local variables, but those variables do not exist in any namespace (that is, it is impossible to somehow access the local variables of a function using a fully-qualified name). You could say a namespace is a symbol table that can be traversed with simple attribute access alone.

在global scope 中, locals()globals() 返回global namespace的同一个字典。

dir([object]) : Without arguments, return the list of names in the current local scope (similar to locals().keys()). With an argument, attempt to return a list of valid attributes for that object. 不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

代码语言:javascript
复制
print(dir()) # show the names in the module namespace
## OUTPUT: ##
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
############################################################
print(globals())
## OUTPUT: ##
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10da810f0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/xxx/xxx/xxx/xxx/test.py', '__cached__': None}
############################################################
locals() == globals()
## OUTPUT: ##
True
############################################################
print(list(locals().keys()).sort() == dir().sort())
## OUTPUT: ##
True
############################################################
def test_func(arg):    
    a = 1
    print (locals())
test_func(666)
## OUTPUT: ##
{'a': 1, 'arg': 666}
############################################################
def test_func(arg):    
    a = 1
    print(dir())
    print(locals().keys())
    print(dir().sort() == list(locals().keys()).sort())
test_func(666)
## OUTPUT: ##
['a', 'arg']
dict_keys(['a', 'arg'])
True

References

[1] A Beginner's Guide to Python's Namespaces, Scope Resolution, and the LEGB Rule: https://sebastianraschka.com/Articles/2014_python_scope_and_namespaces.html [2] Global, Local and nonlocal Variables: https://www.python-course.eu/python3_global_vs_local_variables.php

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-08-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 MeteoAI 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • global 和 nonlocal
    • 使用总结:
    • 闭包(closure)
    • global variable 和 free variable
    • dir(), globals()和locals()
      • References
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档