Modifying the global variable in Python

Modifying the global variable in Python

Introduction

Hello World !! This is my first tech blog. I will do a little bit of context setting before i began writing this piece. I have been writing code in Python for little over a year and its mostly API's and lot of scripting work to pull reports and data cleaning. Before working in Python, i was working primarily in Java. In my recent times at work, i was writing a python package that has image related utilities and i had to modify the global variable initialised.

Sample code

Following is the closer version of how my code looked like. I have not created any class and simply put all my utils code as functions. I tried to modify the global variable in function before using the utility function. This is how i tried to do it.

folder_name = 'datastore'

def init(my_folder_name):
       # Using this function you can overwrite the default folder name to upload your data
       folder_name = my_folder_name

def upload_image(image_link):
      # Accessed the folder_name to upload the image_link passed as argument.

When i wrote the above piece of code in PyCharm code editor, the folder_name in init function has show the inspection info message saying that local variable folder_name is not used. I was confused initially seeing this message. On digging deeper, i found that Python has tried to create a variable with local scope in init function. i was thinking that my code would overwrite the folder_name that i initialised outside the functions. But it didn't work that way.

On checking further i understood that we have to explicitly indicate that i was trying to modify the global variable using global keyword. Only then i could modify the value initialised globally.

Following is the piece of code that worked out for me,

folder_name = 'datastore'

def init(my_folder_name):
       # Using this function you can overwrite the default folder name to upload your data
       global folder_name
       folder_name = my_folder_name

def upload_image(image_link):
      # Accessed the folder_name to upload the image_link passed as argument.

After marking the folder_name using global keyword and then modifying it works.

Hope you find this information useful. Please share your comments if there is any error or mistake. Thanks for reading :)

P.S: Relevant stackoverflow link (stackoverflow.com/questions/10588317/python..) for further reading