0

I created a file 'user.py' and I gave it a variable 'coin' = '100'

coin = 100

I created another file and import this code

import user
print(user.coin) # Output 100
user.coin = 50

This variable is not updated in the 'user.py' file. I can to change the value from 99 to 50.

I want the change in 'user.py' file

coin = 50
  • You could write a new Python file, overwriting the user.py file with new contents. Not sure what the use case for that would be. – DSteman Jul 15 '22 at 10:07
  • Does this answer your question? [Saving an Object (Data persistence)](https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence) – mkrieger1 Jul 15 '22 at 10:18

3 Answers3

1

That's not how programming works. You for sure don't want to change the actual source code during execution.

What you are planing is more of a persistance topic. You could create a user that has a coins attribute and then store this somewhere - a file or a database for example. Then on the next execution you proceed from that state but your code should be unmodifiable except by yourself opening the file, writing stuff into it and saving again.

Christian
  • 1,437
  • 2
  • 8
  • 14
0

The variable 'coin' is assigned statically in user.py. You cannot change this in runtime. To change the assignation you would need to import the user.py as a textfile and edit accordingly.

See here.

0

assuming you know what you are doing, and there is no way to persist this data in json/yaml/xml do this:

import user 
from inspect import getsource
import re 
patterns = {
    'coin':200
}

text =getsource(user)
for key,value in patterns.items():
    finded = re.search(f'{key}.*',text).group()
    text = text.replace(finded,f'{key} = {value}')
with open('user.py','w') as arq:
    arq.write(text)