Search code examples
python-2.7functionglobal-variables

Approach on creating python global variable


I am writing some code of python & selenium webdriver. I got error:

UnboundLocalError: local variable XXX referenced before assignment

I was making global assignment in the main function where that object is first initialised. After doing some study i got solution of assigning global variable in function. I made global assignment in one of the function, then i got the error in another function

So my question is do i really need to assign global assignment in each function or in only first assignment of that global variable.

sample code when i got the error :

class sample:
    driver = None
    def dclose():
        driver.close()
        sys.exit(0)
    def clickLink():
        try:
            driver.find_element_by_link_text('about').click()
        except:
            print "Error: link not found"
    def main():
        global driver
        driver = webBase.Driver(URL)  # another class where i have initalised webdriver with some logger activity.
        clickLink()
        dclose()

Now after assigning global in clickLink()

class sample:
    driver = None
    def dclose():
        global driver  # does it require  #1
        driver.close()
        sys.exit(0)
    def clickLink():
        global driver # does it require  #2
        try:
            driver.find_element_by_link_text('about').click()
        except:
            print "Error: link not found"
    def main():
        global driver # does it require #3
        driver = webBase.Driver(URL)  # another class where i have initalised webdriver with some logger activity.
        clickLink()
        dclose()

which global assignment is must?


Solution

  • Use the constructor to assign it and refer to it by self. Now the driver is a class level variable instead of global. Variables with global scope should be avoided when not required.

    class Sample:
    
        def __init__(self):
            self.driver = webBase.Driver(URL)
    
        def dclose():
            self.driver.close()
            sys.exit(0)
    
        def clickLink():
            try:
                self.driver.find_element_by_link_text('about').click()
            except:
                print("Error: link not found")
    
        def main():
            clickLink()
            dclose()
    

    In order to achieve low coupling, this implementation is better, in which case the driver has to be passed as argument when instantiating the Sample class:

    class Sample:
    
        def __init__(self, driver):
            self.driver = driver
    
        def dclose():
            self.driver.close()
            sys.exit(0)
    
        def clickLink():
            try:
                self.driver.find_element_by_link_text('about').click()
            except:
                print("Error: link not found")
    
        def main():
            clickLink()
            dclose()