-2

Code with comments:

result = {}

def number_of_products():
    return 1 # 2, 3...n

def total_inventory():
    return 100 # 200, 300... n

def set_values():
    result["numberOfProducts"] = number_of_products()
    result["totalInventory"] = total_inventory()

def run_orders():
    results = []
    for i in range(4):
         set_values()
         
         # result = {'numberOfProducts': 1, 'totalInventory': 1000} for the first iteration
         # result = {'numberOfProducts': 2, 'totalInventory': 2000} for the first iteration
         ...
         
         # Add result to the array for future use. 
         results.append(result)

         # Clean up the dictionary for reuse. 
         result.clear()

    print(results)

    # Expectation
    # [{'numberOfProducts': 1, 'totalInventory': 1000}, {'numberOfProducts': 2, 'totalInventory': 2000}, ...]

    # Actual
    # [{},{},...]

run_orders()

As you can see, I am getting empty values in the array when I use the .clear() method.

I also tried using result = {} but that gave the following result:

[{'numberOfProducts': 1, 'totalInventory': 1000}, {'numberOfProducts': 1, 'totalInventory': 1000}, {'numberOfProducts': 1, 'totalInventory': 1000}, ...]

How can I persist the values I get from different result(s)?

Raj
  • 3,637
  • 8
  • 29
  • 52
  • 3
    *"Clean up the dictionary for reuse"* — Instead of reusing the same dict, just *create a new one*…!? – deceze Feb 18 '21 at 09:30
  • In the second attempt you should have got UnboundLocalError instead. That result is weird. – user202729 Feb 18 '21 at 09:35
  • 1
    Besides it's usually not a good idea to use global variables anyway. – user202729 Feb 18 '21 at 09:36
  • Maybe you can find the answer in this topic : https://stackoverflow.com/questions/5105517/deep-copy-of-a-dict-in-python – Damien Castaignede Feb 18 '21 at 09:43
  • Not really, the main issue here is the misunderstanding of the global/local rule. https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use – user202729 Feb 18 '21 at 09:45

1 Answers1

0

There's really zero reason to use a global dict, just create a new dict for every result. In fact, "set_values" should probably return a new dict:

def number_of_products():
    return 1 # 2, 3...n

def total_inventory():
    return 100 # 200, 300... n

def get_values():
    return {
        "numberOfProducts": number_of_products(),
        "totalInventory": total_inventory()
    }

def run_orders():
    results = []

    for _ in range(4):
         result = get_values()
         results.append(result)

    print(results)

run_orders()
deceze
  • 510,633
  • 85
  • 743
  • 889