[Python-ideas] Idea to support lazy loaded names.

Terry Reedy tjreedy at udel.edu
Tue Oct 7 05:51:45 CEST 2014


On 10/6/2014 11:30 PM, Steven D'Aprano wrote:

> This is a specific example of a more general technique, namely computed
> attributes. Rather than a solution to the specific example, I would
> rather have a general solution to the problem of having computed
> attributes in modules. We have half a solution already: the descriptor
> protocol, the most obvious example being property(). Well, perhaps a
> quarter of a solution.
>
> Assuming property(), or some equivalent, worked in modules, the solution
> to lazy loading is simple: have a getter that returns the attribute if
> it already exists, otherwise initialise it (importing it from elsewhere)
> then return it.
>
> The problem then becomes, how do we get descriptors to be run when
> accessing them via module attributes? The normal process is that if a
> name is found in the instance __dict__, the descriptor protocol is not
> followed:
>
> py> class Test(object):
> ...     spam = property(lambda self: 23)
> ...     def __init__(self):
> ...             self.eggs = property(lambda self: 42)
> ...
> py> x = Test()
> py> x.spam
> 23
> py> x.eggs
> <property object at 0xb7168c5c>
>
>
> This is relevant because modules are instances, and module attributes
> live in the instance __dict__.

So a 'solution' might be to make modules be instances (but with no 
__new__ or __init__) of a module metaclass, so that module dicts could 
act like class dicts with respect to descriptors.  I have no idea how 
much code this would break ;-).

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list