Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python variable won't update outside of module

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading