개발/Python

Python Scope - LEGB Rule

Louisus 2020. 5. 2. 23:44
728x90

LEGB Rule

- Local 

Names assigned in any way within a function (def or lambda), and not declared global in that function.

 

# global x

x = 25

def my_func():

    # local x
    x = 50
    return x

print(x)
print(my_func())

print(x)

 

# 25

# 50

# 25

 

- Enclosing Function locals (EFLs)

Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer

 

name = 'This is a global name!'

 

def greet():
    name = 'Sammy'

    def hello():
        print('Hello ' + name)

greet()

# Nothing

 

- Global (module)

Names assigned at the top-level of a module file, or declared global in a def within the file


 

name = 'This is a global name!'

def greet():
    name = 'Sammy'

    def hello():
        print('Hello ' + name)

    hello()

greet()

print(name)

 

# Hello Sammy

# This is a global name!

 

-------

name = 'This is a global name!'

def greet():

    def hello():
        print('Hello ' + name)

    hello()

greet()

 

# Hello This is a global name!

 

------

 

x = 50

def func():
    global x
    x = 1000

print('before function call, x is ', x)
func()
print('after function call, x is ', x)

 

# before function call, x is  50
# after function call, x is  1000

 

 

- Built-in (Python)

Names preassigned in the built-in names module : open, range, SyntaxError, etc...

 

len = 23
print(len)

 

# 23