Postpone creation of attributes until needed

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Jun 12 07:59:26 EDT 2007


En Tue, 12 Jun 2007 08:18:40 -0300, Steven D'Aprano  
<steve at REMOVE.THIS.cybersource.com.au> escribió:

> On Mon, 11 Jun 2007 22:35:46 -0700, Frank Millman wrote:
>
>> Because, as I have tried to explain elsewhere (probably not very
>> clearly), not all the information required to perform compute() is
>> available at __init__ time.
>
> I'm sorry, but this explanation doesn't make sense to me.
>
> Currently, something like this happens:
>
> (1) the caller initializes an instance
> =>  instance.x = some known value
> =>  instance.y is undefined
> (2) the caller tries to retrieve instance.y
> (3) which calls instance.__getattr__('y')
> (4) which calls instance.compute()
> =>  which forces the necessary information to be available
> =>  instance.__dict__['y'] = some value
> (5) finally returns a value for instance.y
>
> Since, as far as I can tell, there is no minimum time between creating  
> the
> instance at (1) and trying to access instance.y at (2), there is no
> minimum time between (1) and calling compute() at (4), except for the
> execution time of the steps between them. So why not just make compute()
> the very last thing that __init__ does?

As far as I understand what the OP said, (2) may never happen. And since  
(4) is expensive, it is avoided until it is actually required.

-- 
Gabriel Genellina




More information about the Python-list mailing list