1

I got a module stuff.py with a lot of unorganized objects.

import stuff

myList = getattr(stuff, 'atomsList')
myList.append ('protons')

setattr(stuff, 'atomsList', myList)

How do I save the stuff module now as stuff.py?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 4
    Modules aren't designed as a storage mechanism. You'll have a much cleaner experience if you use a real serialization format and separate data files. – user2357112 Oct 06 '19 at 23:50
  • you might look at the shelve module https://docs.python.org/3.6/library/shelve.html As others pointed out. modules are not intended to be modified by the python code. It could be done theoretically, but self modifying code is really not a good idea. To store keyword based data you might look at shelve if you want to 'transfer' all data existing at the moment in stuff you might write a one shot script, that loops through `stuff` and writse each item into a shelve. afterwards just use the shelve – gelonida Oct 06 '19 at 23:59
  • Consider storing the data as an instance of a class or as just a dictionary. If you make it a `class`, you can also, optionally, give it methods that operate on the data in it if you wish. See [Saving an Object (Data persistence)](https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence). – martineau Oct 07 '19 at 00:34

1 Answers1

0

The idea with modules I thought is that they are defined in a general sense and are only made specific when they are 'instantiated' in the same way as classes ( and you can't edit the source code). So unless you want to directly edit your class, you should save the instantiated class using pickle.

I think Pickle is what you're looking for...

E.g.:

import pickle
import stuff

myList = getattr(stuff, 'atomsList')
myList.append ('protons')
setattr(stuff, 'atomsList', myList)

with open("instantiated_stuff.pickle", ‘wb’) as f:
    pickle.dump(stuff, f)

Then to open the file use:

with open("instantiated_stuff.pickle", ‘rb’) as pickle_file:
    opend_stuff = pickle.load(pickle_file)
AER
  • 1,549
  • 19
  • 37