Dunder variables

Frank Millman frank at chagford.com
Tue Jan 9 04:28:03 EST 2018


"Peter Otten"  wrote in message news:p31v3m$pji$1 at blaine.gmane.org...

> Frank Millman wrote:
>
> > Hi all
> >
> > I have read that one should not call dunder methods in application code.
> >
> > Does the same apply to dunder variables? I am thinking of the instance
> > attribute __dict__, which allows access to the contents of the instance.
> >
> > I only want to read from __dict__, not update it. Is this frowned upon?
>
> Why would you care whether it is "frowned upon" if it's the best way to
> achieve something useful?
>
> So the real question is /what/ you are trying to do and what your options
> are.
>

Here is a brief history of how I have got to where I am now.

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.

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.

My first attempt was to add a new attribute to Context called 'vars', which 
was an empty dictionary. Any method could add to it or read from it, but I 
would basically ignore it.

This worked, but it was awkward. My entire app revolves around passing 
passing units of data around, and my address mechanism is always two-part - 
container name, attribute name. This introduced a third element - container 
name, attribute name, key name.

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.

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.

My solution is to use __dict__ to get at the data. If there are any other 
options, I will be interested to hear them.

Thanks

Frank





More information about the Python-list mailing list