0

I am trying to refresh perhaps reload the whole file I imported on a script in which I used to changed some things within that file, and using that script to reload the file I imported within itself.

How do I refresh a file which is a script that has been imported as a module after making changes on it using the script which contains that imported file.

This is what I am trying to achieve

#lists_values.py
Christine = [0,0,0]
George = [900,123,1]
#suppose Ralf = [ 0, 0, 0 ] is going at     this position soon.

#main.py
from lists_values import *
import lists_values

def insertRalf():
    with open("lists_values.py", "a") as myfile:
        myfile.write("Ralf = [0, 0, 0]\n")

insertRalf()

def resultView():
    #Maybe some code to refresh the file I imported? Which is the lists_value since I added another list I want to print it.

    #Print the NEW values of lists_values
    fd = open("lists_values.py", "r")
    print(fd.read())
    fd.close()
     #My goal is to see the new value 'Ralf', but since I imported the file when it was still unchanged, I wont see any Ralf if I print it now.

resultView()
glibdud
  • 7,550
  • 4
  • 27
  • 37
Sorcuris
  • 13
  • 1
  • 6
  • generally you don't want to do that, you'd store `Christine`, `George` and `Ralf` in a dictionary (or similar) and just update the object directly... why write to a file and reload? reloading is normally discouraged and only used out of convenience to a developer that has externally modified the code – Sam Mason Apr 17 '19 at 14:47
  • is there any way to store them in a dictionary to make these value stay there when I run the code once again? – Sorcuris Apr 17 '19 at 15:28
  • define "stay there"! taking a guess, why not just use the `json` module to load/save them to another file? there are lots of other file formats around for this, e.g. csv files or full blown relational databases – Sam Mason Apr 17 '19 at 15:33

1 Answers1

0

Welcome to Stackoverflow. There are better ways to do what you want!

You appear to be using the values module as some sort of namespace. It would be much more sensible to store only the data in some file. If you read the documentation for the shelve module you will see that for simple values and string keys it acts, within limits, as a sort of dictionary-on-disk.

Putting names in a Python namespace dynamically is a "code smell" - since you never know what names will be defined, you also end up having to access them dynamically with getattr or similar tedious stuff.

holdenweb
  • 33,305
  • 7
  • 57
  • 77