Home > Software design >  Python variable won't update outside of module
Python variable won't update outside of module

Time:02-08

I have a variable called store_number that I pass in from my main.py into a module called store_selector which increments the store number until it finds a valid store. The whole thing is in a while loop and after the first loop the store variable does not keep it's updated value from the store_selector module but instead reverts to it's original value. I know this has something to do with declaring a global variable but the problem is if I declare a global variable inside the module I assume it will keep assigning the initial value when that module is called (since it's in a while loop in the main.py)

Any ideas?

Inside main.py

store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_selector(driver, store_number)
    item_inspector(driver)

Inside functions.py

def store_selector(driver, store_number):
    textbox = driver.find_element(By.ID, "myStore-formInput")
    #time.sleep(1)
    store_number  = 1
    textbox.send_keys(store_number, Keys.RETURN)
    time.sleep(1)
    while driver.find_element(By.ID, "myStore-errorMessage").is_displayed() and store_number < 10000:
        store_number  = 1
        textbox.clear()
        textbox.send_keys(store_number, Keys.RETURN)
        time.sleep(1)
    else:
        store_button = driver.find_element(By.CSS_SELECTOR, f'button[data-storeid="{str(store_number).zfill(4)}"]')
        store_button.click()

CodePudding user response:

You can just move store_number =1 into your main script

store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_selector(driver, store_number)
    item_inspector(driver)
    store_number =1

Or if you insist on doing so in store_selector, return the incremented value to the main function

store_number = 103

while store_number < 10000:
    store_dropdown(driver)
    store_number = store_selector(driver, store_number)
    item_inspector(driver)

and

def store_selector(driver, store_number):
    store_number  = 1

    ########
    # Your function
    ########

    return store_number

You should really be using the first solution unless you have a really good reason to be incrementing your counter in the function (i.e. conditional incrementation)

  •  Tags:  
  • Related