Sean D
Sean D

Reputation: 4292

Python 2.7 scoping issue with variable/method when placed inside a function

I'm new to python and notice this code works when written without being put inside a function.

from selenium import webdriver

driver = lambda: None

def setup_browser():
   # unnecessary code removed
    driver = webdriver.Firefox()
    return driver

setup_browser()
driver.set_window_size(1000, 700)
driver.get("https://icanhazip.com/")

As shown above, I get this error:

`AttributeError: 'function' object has no attribute 'set_window_size'

My reading is that driver is not being updated before it is called. Why is this?

Upvotes: 1

Views: 54

Answers (1)

ohmu
ohmu

Reputation: 19752

The problem is that inside of setup_browser() you're setting a local variable named driver, but you are not modifying the global variable driver. To do that, you need to use the global keyword:

def setup_browser():
    global driver
    driver = webdriver.Firefox()
    return driver

However, overriding the driver global variable and returning it at the same time is redundant. It would be better to not define driver globally as a null function, but to assign it directly. E.g.,

from selenium import webdriver

def setup_browser():
    driver = webdriver.Firefox()
    return driver

driver = setup_browser()
driver.set_window_size(1000, 700)
driver.get("https://icanhazip.com/")

Upvotes: 2

Related Questions