Home > Mobile >  Cannot use a variable if it is used in a DEF, under an IF condition
Cannot use a variable if it is used in a DEF, under an IF condition

Time:09-13

So I have a file from which I import another file, in the main file I need to use a variable that is in another file and is under DEF function and IF condition. But every time I get that there is no such variable.

Code:

First file:

from modules.proxy import *
set_proxy()
browser.get("website.com")

Second file:

def set_proxy():
   if proxy_type == "type1":
    global browser
    browser = webdriver.Chrome(CHROME_DIR)

Result: " name 'browser' is not defined "

CodePudding user response:

you should return the browser variable value in the end of the function like this:

return browser

now get it main file like this:

browser = set_proxy()
browser.get("website.com")

CodePudding user response:

You need to give a default value for browser.

File 1:

browser: str = ""

def test():
    proxy: bool = True
    if proxy:
        global browser
        browser = "TEST"

File 2:

import file1

file1.test()
print(file1.browser)
file1.browser = "TEST2"
print(file1.browser)

As expected the output are:

TEST
TEST2
  • Related