DEV Community

Cover image for Scope in Python
Ruqiya Arshad
Ruqiya Arshad

Posted on

Scope in Python

Scope in Python is an inner system of rules in a namespace that has variable visibility rules. Variable visibility means how the variable can be seen, referenced, or accessed. Before mentioning and discussing the rules, we should discuss the types of scope in the system.

  1. Local Scope: is inside the function.
  2. Global Scope: is present in the module.
  3. Enclosing Scope: is present in the outer function and its inner nested functions.
  4. Built-In Scope: is present in language-based designed functions.

Now prior to jumping to the sequence of LEGB, let’s discuss rules of scope first. These scope rules check where you can observe and use the variable:

  • The variable named inside a function cannot be used outside the function.
#The following program explains the rules of scope in python.
#Rule 1-The variable declared inside a function cannot be used outside the function.

def citizen_identity():
    cnic_number = "35200-000000-1" #Local variable.
    print("The citizen identity card number is " + cnic_number + ".")
citizen_identity()#It prints only when below code line is removed.
                  #Output: "The citizen identity card number is 35200-000000-1."
print(cnic_number)#Error! as the local variable is used outside the function.
                  #Output: "NameError: name 'cnic_number' is not defined"
Enter fullscreen mode Exit fullscreen mode
  • Global variables can be accessed inside a local scope and modified by using the “global” keyword.
#The following program explains the rules of scope in python.
#Rule 2- Global variables can be accessed inside a local scope and modified by using the "global" keyword.

cnic_number = "35200-000000-0" #Global variable

def citizen_identity():
    global cnic_number #Global keyword indicates that no new variable is declared with the same name.
    cnic_number = "35200-000000-1" #Modifying the global variable value at output.
    print("The citizen identity card number is " + cnic_number + ".")
citizen_identity()#Output: "The citizen identity card number is 35200-000000-1."
Enter fullscreen mode Exit fullscreen mode
  • Function-to-function, the local variables cannot be reached or accessed.
#The following program explains the rules of scope in python.
#Rule 3- Function-to-function, the local variables cannot be reached or accessed.

def citizen_identity():
    cnic_number = "35200-000000-1"
    print("The citizen identity card number is " + cnic_number + ".")
citizen_identity()

def citizen_nationality():
    user_input = input("Mention your natioanllty here. ") #The program works fine upto here.
    nationality = ("Pakistani", "Kuwaiti", "Saudi Arabian")
    if user_input in nationality:
        print(cnic_number) #Error! "NameError: name 'cnic_number' is not defined".
                           #Local variable from other function cannot be used.
    else:
        print("Metioned nationality is not in the list!")
citizen_nationality()
Enter fullscreen mode Exit fullscreen mode
  • Both global and local scopes can have the same variable names, but the local variable causes a shadowing effect, making the global variable inaccessible.
#The following program explains the rules of scope in python.
#Both global and local scopes can have the same variable names
#But the local variable causes a shadowing effect
#Making the global variable inaccessible.

cnic_number = "35200-000000-0" #Not using global keyword causes shadowing of global variable value by local variable.

def citizen_identity():
    cnic_number = "35200-000000-1" #Local variable treated here as a new variable.
    print("The citizen identity card number is " + cnic_number + ".")
citizen_identity()
print(cnic_number)#Output: 35200-000000-0
                  #This shows that the global variable value is not changed.
                  #Remove this line to see the shadow effect.
Enter fullscreen mode Exit fullscreen mode

How scope rules are implemented can only be understood by coding practice. But why do we need to learn about these rules? The LEGB sequence (Local, Enclosing, Global, Built-In) is a blueprint in Python that locates variables in the scopes of namespaces when referenced in the code. For a smooth LEGB search of variables, the scope rules should be followed while coding, or else the errors will occur in the runtime.
Let’s understand the LEGB sequence in a practical manner.

#The following program explains the LEGB sequence Local->Enclosing->Global->BuiltIn.
#LEGB starts looking up the variable whenever it is referenced while execution.

cnic_number = "35200-000000-0" #global variable
def citizen_identity():
    cnic_number = "35200-000000-1" #local variable
    print("The citizen identity card number is " + cnic_number + ".") #LEGB search for variable begins here
                                                                       #Variable first found in local scope
citizen_identity()#Output: "The citizen identity card number is 35200-000000-1"

print(cnic_number)#LEGB Lookup. Referenced variable found in global scope.Output: "35200-000000-0"


def citizen_nationality(): #enclosing scope (outer)
    user_input = input("Mention your natioanllty here...") #local to outermost enclosing scope
    nationality = ("Pakistani", "Kuwaiti", "Saudi Arabian")#local variable

    if user_input in nationality: #LEGB variable lookup.
        print(cnic_number)#global variable. Local(not found)->Enclosing(not found)->Global(found)
    else:
        print("Metioned nationality is not in the list!")

    def citizen_name(): #inner enclosing scope
        name_input = input("Mention your name...")#local variable
        print(name_input) #LEGB search begins. Local(found)
        print(user_input) #non-local variable. LEGB search begins.Local(not found)->Enclosing(found)
    citizen_name() #executed last

citizen_nationality() #executed first
Enter fullscreen mode Exit fullscreen mode

The LEGB sequence is activated when the program is in execution mode, and it starts variable lookup when a variable is referenced in the program. The variable search in scopes then begins in order: Local->Enclosing->Global->Built-in. The point is to note here that LEGB is independent of the code line being executed logically.

Top comments (0)