Is this pythonic?

Frank Millman frank at chagford.com
Wed Nov 23 07:27:08 EST 2016


"Frank Millman"  wrote in message news:o13meh$p2g$1 at blaine.gmane.org...

> 3. When instantiating an object, check if it would need computation -
>     if computation_required:
>         self.getval = self._getval_with_comp
>     else:
>         self.getval = self._getval
>
> 4. In _getval_with_comp, perform the computation, then add the following -
>        self.getval = self._getval
>         return self._getval()
>
> What is the verdict? -1, 0, or +1?
>

Thanks for the responses. I will reply to them all here -

@Peter
> You can also have the method replace itself ...

I like it. Thanks for the suggestion.

@Steve
> So this check only happens once, on instantiation? And you're sure that 
> once
> the instance is created, there will never be any circumstances where you
> want to re-calculate the value?

Well, the process that I call 'computation' includes setting up some 
variables that will trigger a recalculation when certain values change.

Part of my motivation was to avoid all of this if the value is never 
accessed.

> def __getval_with_comp(self):
>     value = ... # long computation
>     self._cached_value = value
>     self.getval = self._getval
>     # return value
>     return self._getval()
>     # why call the method when you already know the answer?
>
> How are subclasses supposed to override getval?
>

Two questions there, but the answer is the same.

I don't want subclasses to override the computation part of the process. I 
just want then to 'massage' the result before returning it. Therefore the 
answer to the first question is, to force the subclass to return the result, 
if it has its own _getval(). The answer to the second question is that they 
override _getval(), and therefore they will be invoked when getval() is 
called, provided getval has been set to be equal to _getval.

Hope that makes sense.

@Chris
> This strongly suggests that str(x) is the wrong way to get the
> information. You shouldn't be doing database requests inside __str__
> or __repr__.

I guess you are right, but still it is a pity. __str__ has been working for 
me beautifully for a long time now. The only change is that, previously, all 
the values had been read in or computed before calling __str__(), now I am 
delaying the computation until requested.

It is a bit like quantum theory. I have no way of telling whether the 
computation has been carried out without looking at it, but the act of 
looking at it triggers the computation. I can tell, of course, by looking at 
the underlying attribute, but not by using the public methods.

Frank





More information about the Python-list mailing list