Search code examples
pythondata-persistence

Saving an Object and being able to update its attributes


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.


Solution

  • 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.