from selenium import webdriver def f(): webdriver = webdriver.Chrome() return webdriver 

PyCharm gives an error, Unresolved reference webdriver ( import is gray) If you remove the f function, everything will work fine.

    1 answer 1

    x = creates a local variable x inside the function (in the absence of global x , nonlocal x declarations). From the definition of language :

    It is a local variable.

    Therefore, the f() call in your case leads to UnboundLocalError , as the webdriver is a local variable and you try to access it before it is assigned a value. The presence of a global variable with the same name does not matter. In any place of the function x this is a local variable due to the presence of x = inside. See the Python FAQ: Why am I getting an UnboundLocalError when the variable has a value?

    To fix the code, just rename the webdriver inside the function (driver, browser are good name candidates):

     browser = webdriver.Chrome()