[Python] How can I improve the storeinROM method for safer and more efficient variable storage...

Discussão em 'Python' iniciado por Stack, Julho 4, 2025.

  1. Stack

    Stack Membro Participativo

    I’m working on an advanced Python calculator project for general and college-level math. It’s structured as a Calculator class with many math operations and a storeinROM method for saving variables to a text file (vars.txt).

    Here’s a simplified version of the relevant part:

    python Copy Edit class Calculator: def storeinROM(self, name, value: int): """Stores your variable in memory (ROM).""" with open("vars.txt", "a") as f: f.write(f'{name}={value}\n')

    def get_variable(self, name: str, onlyreturnvalue: bool = True, clearmemoryafteroutput=False):
    with open('vars.txt', "r") as f:
    varslist = f.readlines()
    for var in varslist:
    if name in var:
    if clearmemoryafteroutput:
    self.clearmemory()
    if onlyreturnvalue:
    return int(var[len(name)+1:len(var)-1])
    return var

    def clearmemory(self):
    with open("vars.txt", "w") as f:
    f.write("")


    The full version of the calculator class can be seen here on my blog for reference.

    Currently, storeinROM simply appends each variable as name=value to vars.txt. This works, but I want to make it more robust and safe.

    Specifically: 1️⃣ How can I prevent duplicate keys when storing a variable? 2️⃣ How can I update an existing key’s value instead of just adding another line? 3️⃣ Is there a better way to handle reading/writing variables — for example, should I use JSON instead of plain text? 4️⃣ How can I make this method thread-safe if multiple functions call it?

    I’m using Python 3.7+. Any suggestions for improving this method’s design or making it more efficient and error-resistant would be appreciated.

    Thanks in advance!

    Continue reading...

Compartilhe esta Página