Phuc Nguyen
Phuc Nguyen

Reputation: 13

Overwrite a python file while using it?

I have first file (data.py):

database = {
    'school': 2,
    'class': 3
}

my second python file (app.py)

import data
del data.database['school']
print(data.database)
>>>{'class': 3}

But in data.py didn't change anything? Why? And how can I change it from my app.py?

Upvotes: 1

Views: 331

Answers (3)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

To elaborate on Gelineau's answer: at runtime, your source code is turned into a machine-usable representation (known as "bytecode") which is loaded into the process memory, then executed. When the del data.database['school'] statement (in it's bytecode form) is executed, it only modifies the in-memory data.database object, not (hopefully!) the source code itself. Actually, your source code is not "the program", it's a blueprint for the runtime process.

What you're looking for is known as data persistance (data that "remembers" it's last known state between executions of the program). There are many solutions to this problem, ranging from the simple "write it to a text or binary file somewhere and re-read it at startup" to full-blown multi-servers database systems. Which solution is appropriate for you depends on your program's needs and constraints, whether you need to handle concurrent access (multiple users / processes editing the data at the same time), etc etc so there's really no one-size-fits-all answers. For the simplest use cases (single user, small datasets etc), json or csv files written to disk or a simple binary key:value file format like anydbm or shelve (both in Python's stdlib) can be enough. As soon as things gets a bit more complex, SQL databases are most often your best bet (no wonder why they are still the industry standard and will remain so for long years).

In all cases, data persistance is not "automagic", you will have to write quite some code to make sure your changes are saved in timely manner.

Upvotes: 2

Sasuke_214
Sasuke_214

Reputation: 69

As what you are trying to achieve is basically related to file operation. So when you are importing data , it just loads instanc of your file in memory and create a reference from your new file, ie. app.py. So, if you modify it in app.py its just modifiying the instance which is in RAM not in harddrive where your actual file is stored in harddrive.

If you want to change source code of another file "As its not good practice" then you can use file operations.

Upvotes: 0

Gelineau
Gelineau

Reputation: 2090

del data.database['school'] modifies the data in memory, but does not modify the source code.

Modifying a source code to manage the persistence of your data is not a good practice IMHO.

You could use a database, a csv file, a json file ...

Upvotes: 4

Related Questions