Home > Software design >  How do I change the value of a variable stored in another file?
How do I change the value of a variable stored in another file?

Time:08-16

I've been working on a text based role-playing game made purely with Python. I have a file tree like this :-

Parent Folder
    Directory abc
        File A
    

    Directory xyz
        File B

Imagine there's a variable named userInventory which is a list, stored in File A.

userInventory = ["hp_potion", "pod_token", "broken_cup"]

What I wanna do is to import File A in File B, and then update the value of userInventory which is in File A by appending something to it in File B.

If I try to do something like this in B :

import sys
sys.path.insert('../Path/to/File/A)
import A

A.userInventory.append("bronze_sword")

Then it imports the file and actually updates the value of userInventory, but once the program in File B ends, the changes made to userInventory are declined and the variable reverts back to normal. This happens because it never really changes the value of userInventory which is stored in File A. What Python does is to assign the new value temporarily which exists until the program is running in B.

My Question is : How do I change its value completely which then can be used further in other files?

I mean, when you're developing a game in multiple files, you need some variables that will define some of the user stats and the game and are stored in a different file for easy access all over the parent folder.

CodePudding user response:

You should consider that python is for logic, not really for persisting data.

Which is why you can load your variable from the file A, it goes in memory, and when you modify it, it only changes it in memory and will not get persisted.

To persist your data, you can use any of json, pickle, or sqlite3, which are intended to store/retrieve data.

Also, I doubt you want to use sys.path, I've never needed it myself and it looks like it you need relative importing.

  • Related