5/06/2020

Python - Variable Scope

** Variable Scope


==========================================

'''
LEGB (Local, Enclosing, Global, Built-in)
'''

x = 'global x'

def test():
y = 'local y'
print(y)

test()

---------------------------------

local y

---------------------------------

==========================================

x = 'global x'

def test():
y = 'local y'
print(x)

test()

---------------------------------

global x

---------------------------------

==========================================

x = 'global x'

def test():
y = 'local y'
print(x)

test()

print(y)


---------------------------------

NameError: name 'y' is not defined

---------------------------------

==========================================


x = 'global x'

def test():
y = 'local y'
print(x)

test()

print(x)


---------------------------------

global x
global x

---------------------------------

==========================================

x = 'global x'

def test():
x = 'local x'
print(x)

test()

print(x)

---------------------------------

local x
global x

---------------------------------

==========================================

x = 'global x'

def test():
global x
x = 'local x'
print(x)

test()

print(x)

---------------------------------

local x
local x

---------------------------------

==========================================

# x = 'global x'

def test():
global x
x = 'local x'
print(x)

test()

print(x)

---------------------------------

local x
local x

---------------------------------

==========================================

# x = 'global x'

def test():
# global x
x = 'local x'
print(x)

test()

print(x)

---------------------------------

  File "C:\Users\purunet\Documents\py1\new6.py", line 17, in

    print(x)
NameError: name 'x' is not defined

---------------------------------

==========================================

def test(z):
x = 'local x'
print(z)

test('local z')

---------------------------------

local z

---------------------------------

==========================================

def test(z):
x = 'local x'
print(z)

test('local z')

print(z)

---------------------------------

File "C:\Users\purunet\Documents\py1\new6.py", line 16, in

    print(z)
NameError: name 'z' is not defined

---------------------------------

==========================================

m = min([5, 1, 4, 2, 3])
print(m)

---------------------------------

1

---------------------------------

==========================================

import builtins

print(dir(builtins))

---------------------------------

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

---------------------------------

==========================================

import builtins

def min():
pass

m = min([5, 1, 4, 2, 3])
print(m)

---------------------------------

File "C:\Users\purunet\Documents\py1\new6.py", line 17, in
    m = min([5, 1, 4, 2, 3])
TypeError: min() takes 0 positional arguments but 1 was given

---------------------------------

==========================================

import builtins

def my_min():
pass

m = min([5, 1, 4, 2, 3])
print(m)

---------------------------------

1

---------------------------------

==========================================

def outer():
x = 'outer x'

def inner():
x = 'inner x'
print(x)


inner()
print(x)
outer()

---------------------------------

inner x
outer x

---------------------------------

==========================================

def outer():
x = 'outer x'

def inner():
# x = 'inner x'
print(x)


inner()
print(x)
outer()

---------------------------------

outer x
outer x

---------------------------------

==========================================

def outer():
# x = 'outer x'

def inner():
x = 'inner x'
print(x)


inner()
print(x)
outer()

---------------------------------

 File "C:\Users\purunet\Documents\py1\new6.py", line 18, in

    outer()
  File "C:\Users\purunet\Documents\py1\new6.py", line 17, in outer
    print(x)
NameError: name 'x' is not defined

---------------------------------

==========================================


def outer():
x = 'outer x'

def inner():
# x = 'inner x'
print(x)


inner()
print(x)

outer()


---------------------------------

outer x
outer x

---------------------------------

==========================================

def outer():
x = 'outer x'

def inner():
nonlocal x
x = 'inner x'
print(x)


inner()
print(x)

outer()

---------------------------------

inner x
inner x

---------------------------------

==========================================

'''
LEGB (Local, Enclosing, Global, Built-in)
'''

x = 'global x'


def outer():
x = 'outer x'

def inner():
x = 'inner x'
print(x)


inner()
print(x)

outer()
print(x)


---------------------------------

inner x
outer x
global x

---------------------------------

==========================================

'''
LEGB (Local, Enclosing, Global, Built-in)
'''

x = 'global x'


def outer():
# x = 'outer x'

def inner():
# x = 'inner x'
print(x)


inner()
print(x)

outer()
print(x)

---------------------------------

global x
global x
global x

---------------------------------