Global,Local and the use of globals() in Python

#python #global #local #variables

Soham Kundu Mar 17 2021 · 1 min read
Share this

Let's get straight to the point.

Can we access the value of a global variable inside a function, if a local variable is also  of the same name  ?

Basically, is the below example possible ?

Please try it for yourself

count=4

def fun():

    count=1

    print(f"Local var count is {count}")

   global count

   print(f"global var count is {count}")

fun()

No right ?

Now before we go running to change the name of the variable to something like this

count = 4

def fun():

    x = 1

   print(f"Local var x is {x}")

   print("global var count is {count}")

fun()

Please wait !

There exists a method called globals() from which we can achieve the same as shown below

count=4

def fun():

   count = 1

   print(f"local var count is {count}")

    x = globals()['count']

    print(f"global var count is {x}")

fun()

Hope it helps.

Thanks

Comments
Read next