0

I am creating a POS system in Python, which is almost complete. (GUI not included). However, I want to be able to store the items that a user registers.

I tried saving the object to a file, but that did not help:

with open('myObject.pkl', 'wb') as outp:
    itemObject = Item("", 0, 0)
    pickle.dump(itemObject, outp, pickle.HIGHEST_PROTOCOL)

Even after I input the item's details ("name",price,stock) an exit the program, when I started it again I had to register the item all over again.

I also searched online on the matter, but all the results I got did not support updating the attributes of the object in the file.

I've also checked more examples on the forum, but none of them suit my needs well, like this one: Saving an Object (Data persistence), Python- Saving list of objects and its attributes

If it helps, here is where I defined the class and object:

class Item:
    def __init__(self, name, price, stock):
        self.name = name 
        self.price = price
        self.stock = stock

itemObject = Item("", 0, 0)

Here is the function that updates the class attributes based on user input:

def regItem():
    name = input("What is your item called? ")
    name.lower()
    if name == 'exit':
        exit()
    try:
        price = int(input("How much does it cost? "))
        name.lower()
        if name == 'exit':
            exit()
        if (isinstance(price, int)):
            stock = input("How much stock is available for this item? ")
            name.lower()
            if name == 'exit':
                exit()
            itemObject.name = name
            itemObject.price = price
            itemObject.stock = stock
            int(itemObject.price)
            int(itemObject.stock)
            print("Item",itemObject.name,"priced at",itemObject.price,"with available stock of",itemObject.stock,"has been registered")
            start()
    except ValueError:
        print("Must be a number")
        regItem()

I'm learning Python as my first language, and I'm also new to stack overflow. Any help would be appreciated. Thanks in advance.

  • Python doesn't magically associate that pickle file with an object when it starts up. You've got to load the pickle file. At startup, check for the pickle file. If it exists, then load the object(s) in it. If you were able to do that, then skip the regItem step. If not, then get the user to register it. I can't really tell from your example where itemObject came from so I don't have any code example to share. – saquintes Jan 13 '23 at 09:55

1 Answers1

0

You need to conditionally load the object you are trying to persist.

import os
import pickle

class Item:
    def __init__(self, name, price, stock):
        self.name = name
        self.price = price
        self.stock = stock

    def __str__(self):
        return f"Item {self.name} priced at {self.price} with available stock of {self.stock}"

def regItem():
    name = input("What is your item called? ")
    name.lower()
    if name == 'exit':
        exit()
    try:
        price = int(input("How much does it cost? "))
        name.lower()
        if name == 'exit':
            exit()
        if (isinstance(price, int)):
            stock = input("How much stock is available for this item? ")
            name.lower()
            if name == 'exit':
                exit()
            itemObject = Item(name, price, stock)
            print(f"{itemObject} has been registered")
            return itemObject
    except ValueError:
        print("Must be a number")
        return regItem()

def start(obj):
    print("Starting {}".format(obj))

def main():
    filename = 'myObject.pkl'

    if os.path.exists(filename):
        with open(filename, 'rb') as inp:
            itemObject = pickle.load(inp)
    else:
        itemObject = regItem()

        with open('myObject.pkl', 'wb') as outp:
            pickle.dump(itemObject, outp, pickle.HIGHEST_PROTOCOL)

    start(itemObject)

main()

Run this once to enter in the data. Run it again and it will start with the same object you started with.

saquintes
  • 1,074
  • 3
  • 11
  • The code works fine in storing one item, but if I run regItem after registering my first item, the second item is not saved. Do I have to declare a new object for a new item? Or do I have to create another .pkl file to store the second one? The code is the exact same by the way. – Red Hot Coffee Jan 14 '23 at 04:15
  • Yes you have to create a new object for a new item. You can use the same pkl file, but just need to take care in how you read/write to it. I think pickle can handle streaming, so you can keep dumping to a file new objects and then you would keep calling load on a stream to get them out. Alternatively, you can keep them in a list/dict and just pickle load/dump that. – saquintes Jan 17 '23 at 07:43