Breadcrumbs

Scoping rule

Features

  • If there is no value corresponding to the local variable name in a function, the name can be found based on the LGB rule.

    • Namespace: An area that contains the variable name

    • Local scope: A namespace and local domain inside a function

    • Global scope: Global domain outside a function

    • Built-in scope: The domain related to the contents defined by Python and an internal domain

    • LGB rule: The order of finding a variable name. local → global → built-in

Example

Python
# Error: can't find simple_pi in circle_area
simple_pi = 3.14
def circle_area(r):
    return r*r*simple_pi
 
# simple_pi should be declared as global if it is used in circle_area_ok
def circle_area_ok(r):
    global simple_pi
    return r*r*simple_pi

tp_log(str(circle_area(3.0)))
#expected result: 28.26