Dunder variables

Frank Millman frank at chagford.com
Tue Jan 9 09:14:27 EST 2018


"Steven D'Aprano"  wrote in message news:p32g4v$v88$2 at blaine.gmane.org...

> 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?
>

Maybe I was not clear. The Context instance is passed as an argument to many 
methods. The methods can access the attributes of the instance. The instance 
has no methods of its own.

> If you have a class with only data, and you access the attributes via the
> instance's __dict__, why not use an ordinary dict?

I don’t access them *via* the __dict__, I access them via normal object 
[dot] attribute syntax.

> Alternatively, use a SimpleNamespace:

I did play with that for a while, but AFAIK it does not allow you to define 
read-only attributes.

> > 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.
>

If you are referring to the @property methods, I think this is a bit 
pedantic.

> > 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:

I thought of that. But some of the attributes are things like database 
connections and context managers. Are they pickleable? What I do at the 
moment is make a copy of the attributes, using vars(...).copy(), delete the 
ones I do not want, and save the rest.

Frank





More information about the Python-list mailing list