[Python]Namespaces & scope

Namespaces

Everything in Python is an object. A name helps Python to invoke the object that it refer to.
A namespace is a space that holds a bunch of names. Imagine it a 'namespace table' or a 'namespace dictionary'.

globalNamespace = {x : 1, y : 2, 'return value' : 10}

Note:

  • A module has a global namespace.
  • A class has not a global namespace.
  • Use global to access a global variable in global namespaces

Scope

Python searches names in following order, easily remember the sequence as LEGB. Will raise a SyntaxError if not found in those all namespaces.


Local --> Enclosed --> Global --> Built-in

Example 1# Explain the changes in global namespace and function namesapces with scope concept.

def fun(x, a) : ## 1# funDict = {}, 5# funDict = {x : 3, a : 9}
    y = x + a   ## 6# funDict = {x : 3, a : 9, y : 12}
    return y    ## 7# funDict = {x : 3, a : 9, y : 12, return value : 12}

\#\# main program
x = 3           ## 2# globalDict = {x : 3}
z = x + 12      ## 3# globalDict = {x : 3, z : 15}
a = fun(z, 9)   ## 4# globalDict = {x : 3, z : 15, a : ? } --> 5#,
        ## 8# globalDict = {x : 3, z : 15, a : 12}
x = a + 7       ## 9# globalDict = {x : 15, z : 15, a : 12}

Example 2# Show how enclosed scope works

def fun1() :
    def fun2() :
        print ("x inside the fun2 is ", x)
    x = 7
    print ("x inside the fun1 is ", x)
    func2()

x = 5    ## this is a global variable
print ("x in the main program is ", x)
fun1()

output:

x in the main program is 5
x inside the fun2 is 7
x inside the fun1 is 7

Modules

  • A module is simply a file containing Python code.
  • Each module gets it’s own global namespaces.
  • Each namespace is also completely isolated. Take a prefix to access names in it.
import SomeModule

SomeModule.method() ## Integer.add()

from SomeModule import SomeName
method() ## directly call method without module's name, ie. add()

from SomeModule import *

Note:

  1. Everything in Python is an object.
  2. A class has not a global namespace. That's why you need pass an instance as 1st argument and, self required in a class definition.
  3. A module has a global namespace.
  4. It is usually a bad idea to modify global variables inside the function scope.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容