Signup/Sign In

Python global Keyword with Examples

Posted in Programming   LAST UPDATED: OCTOBER 4, 2021

    The keyword global indicates that the scope of the variable which has been declared as global will remain as long as the entire program is executed, i.e its scope is module level. Other variables or objects which have local scope go out of scope (or become inaccessible) after the method completes or the code block in which they were defines finishes execution.

    Conditions applicable to a global object

    1. As trivial as it might sound, the variable needs to be prefixed with the global keyword if it is being defined inside a method.

    2. But if it has been defined outside a method, it is global by default.

    3. A variable defined or declared inside a method/function is considered to be in the local namespace by default.

    4. This means using the keyword global outside a function is not required since an object would be global by default if it has been defined outside the method.

    5. Accessing a global object inside a method doesn't require having to use the keyword global.

    Let's take a few examples and see.

    1. Accessing global variables inside a method

    The example below covers the case where we have to access the global variables inside a method.

    # a and b are global, no need to use the keyword, 
    # since they are outside the function, hence global by default
    
    a = 23
    b = 10.5
    
    def operation():
        c = a*b
        print(c)
    
    # calling the function
    operation()

    Output:

    241.5


    2. Assigning a new value to a global variable

    The value of a global object can be changed inside a function too. This can be done by simply specifying the object/variable as global inside the method and performing operations on it. Any changes made on the global object inside the method (when the object has been explicitly mentioned as global) will be reflected outside the method as well.

    a = 23
    b = 10.5
    
    def operation():
        global a, b
        a = a*b
        b = a+b
        print(a)
        print(b)
    
    # calling the operation
    operation()

    Output:

    241.5
    252.0


    3. What if I don't use the global keyword?

    Well, here is an example illustrating the same. It results in an UnboundLocalError.

    a = 23
    b = 10.5
    
    def operation():
        a = a*b
        b = a+b
        print(a)
        print(b)
    
    # calling the function
    operation()

    Output:

    UnboundLocalError: local variable 'a' referenced before assignment
    

    If there is a specific requirement to have a set of global variables that need to be used in many different modules/ programs, it is strongly suggested to create a special module, and name it as config or cfg. This module will contain the global objects/variables and it can be conveniently imported into the scripts which require it or use it.

    This way, the config file becomes a global module for your application. Any changes made in this config module in any other module that uses it will be reflected in all other modules. This is similar to resource sharing, wherein one resource (the config file that contains globals) is shared among all other modules. This approach is recommended as all your global objects will be at one place.

    Suppose my config.py has the below contents, (just the global variables)

    a = 1
    b = 2.3
    my_str = "Studytonight"
    my_data = None

    Suppose my working.py has the below contents,

    import config
    
    config.a = config.a +1.2
    
    print(config.b)
    print(config.my_str)
    print(config.my_data)

    Output:

    2.2
    2.3
    Studytonight

    As you can see, this simplifies the code.


    4. Global objects inside nested methods

    This is similar to using global values inside methods/functions. The only difference is that, in normal methods, there is usually one function inside which the object has to be explicitly specified as global. In nested methods, there will be a hierarchy, and the object which is global has to be specified in the method wherein it is being accessed or changed.

    In the below code, the operation method is the outermost method and change method is the inner method. In the operation method, my_var has been assigned with value 28. It is local to the operation method. Inside this method is the change method.

    The change method has a global variable which has been explicitly mentioned, and it has been assigned a value of 127. Outside of the change method (but inside of operation method), the change method is called. Outside the operation method, the operation method is called.

    Before and after the change method is called, the value of my_var doesn't change. It takes up the local value itself. But if changes are made to my_var within the change method, the changes would reflect outside of the operation method as well. Why? Because the global keyword has been used to define my_var inside the local scope of the change method.

    Changes made to the my_var inside the change method are reflected outside as well since it has a global scope.

    def operation():
        my_var = 28
    
        def change():
            # making my_var global
            global my_var
            # assigning it a value
            my_var = 127
            print("Inside change method:", my_var) 
    
        print( "Inside operation method:",my_var) 
        change()
        print("After changing the value of my_var: ", my_var)
    
    operation()
    
    print("The value of my_var now", my_var)

    Output:

    Inside operation method: 28
    Inside change method: 127
    After changing the value of my_var:  28
    The value of my_var now 127
    

    Note: It is important to understand that usage of global should be avoided in most cases since it makes encapsulation of the program logic hard.


    Conclusion

    In this post, we understood the usage and importance of the global keyword. Don't forget to share the experiences that you had while using the global keyword.

    You may also like:

    Published by: SmritiSatyan
    Tags:PythonPython global
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS