1

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?

2
  • 2
    driver = setup_browser() Commented Mar 17, 2018 at 1:05
  • I get it now. Without that the return value goes nowhere. Thank you! Commented Mar 17, 2018 at 1:08

1 Answer 1

2

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/")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.