On Tue, 09 Jan 2018 11:28:03 +0200, Frank Millman wrote:
> I have a class call Context containing only data, not methods. Instances
> are passed around a lot in my application, with various methods
> accessing various attributes.
That contradicts itself... your Context class has data, but no methods,
and yet it has methods accessing various attributes?
If you have a class with only data, and you access the attributes via the
instance's __dict__, why not use an ordinary dict?
Alternatively, use a SimpleNamespace:
py> from types import SimpleNamespace
py> bag = SimpleNamespace()
py> bag.spam = 1
py> bag.eggs = 2
> I wanted to allow various parts of my app to 'piggy back' on this by
> adding their own attributes at certain points, to be read back at
> various other points.
> To tidy this up, I changed it to allow other parts of the app to store
> attributes directly into Context. To protect my 'core' attributes, I
> made them read-only, using @property. This all works quite well.
Except it is no longer a class with data and no methods.
> Now I have a situation where various processes are 'long-running', and I
> need to persist the data to disk so that it can be recovered in the
> event of a crash. I want to use Json to store the data as a dictionary.
> However, I have no idea which additional attributes have been added by
> other parts of the application.
Does it have to be JSON? If this is just for your own use, pickle will
probably do what you want:
py> import pickle
py> class Foo:
py> x = Foo()
py> x.spam = 1
py> s = pickle.dumps(x)
py> y = pickle.loads(s)
(Warning: pickle is not secure if arbitrary, untrusted users have write-
access to the pickle files.)