Sean Preston
Sean Preston

Reputation: 37

Cannot reference variable created with "vars()[]" from a dictionary

I am tasked with creating in inventory management system for a comic book store as a school python assessment. I currently have a dictionary that has the names of the comics and the stock values of these comics imported from a CSV file;

comic_books =  {}

with open('data.csv', 'r+',  newline='') as csvfile:
    csvreader = csv.reader(csvfile)
    for row in csvreader:
        comic_books[row[0]] = int(row[1])

One of the programs requirements is to ensure the user can see the stock of all comics at once. To do this, I simply created two label widgets for each key in my dictionary using the vars() function (alongside some formatting to ensure things like spaces in the comic names didn't cause conflicts);

itteration = 2

for item in comic_books:

    vars()[item.replace(" ", "") + "Stock"] = Label(main, text=item+":")
    vars()[item.replace(" ", "") + "Stock"].grid(column=1, row=itteration, padx=5)

    vars()[item.replace(" ", "") + "StockAmount"] = Label(main, text=comic_books[item])
    vars()[item.replace(" ", "") + "StockAmount"].grid(column=2, row=itteration, padx=5)
    itteration += 1

I eventually got below result, which works as expected:

image

Basically, my problem is that I am tying to refer to one of these variables later in my code (specifically, this is part of the code that runs when the user sells a comic, in order to update the labels with the new values);

for item in comic_books:
                vars()[item.replace(" ", "") + "StockAmount"].config(text=comic_books[item])

This is not working, and whenever the program tries to run the line above, I get this error:

  File "C:\Users\XXX\Desktop\pythonAsessment2\test.py", line 114, in sellProcess
    vars()[item.replace(" ", "") + "Stock"].config(text=comic_books[item])
KeyError: 'Comic2Stock'

Thanks!

Upvotes: 1

Views: 46

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385980

I'm at a loss as to what to do at this point.

The first thing to do is stop using vars() to create dynamic variables. That is almost never a good idea as it makes your code needlessly complex, hard to write, and hard to debug.

Instead, use a dictionary if you want to reference individual items by name. It would look something like this:

labels = {}
for item in comic_books:
    key= "{} Stock".format(item)
    labels[key] = Label(main, text=item+":")
    labels[key].grid(column=1, row=itteration, padx=5)
    ...

Upvotes: 2

Related Questions