Late initialization using __getattribute__

bukzor workitharder at gmail.com
Wed Sep 3 16:55:52 EDT 2008


I want to make a MixIn class that waits to initialize its super-
classes until an attribute of the object is accessed. Not generally
useful, but desirable in my case. I've written this, and it works, but
would like to take any suggestions you guys have. I've commented out
the "delattr" call because it throws an AttributeError (although I
don't know why).



class LateInitMixIn(object):
    def __init__(self):
        print "LateInit initialization"
        self.inited = False
    def __getattribute__(self, attr):
        print "Doing __getattribute__"
        getattr = lambda attr:object.__getattribute__(self, attr)
        if not getattr("inited"):
            super(LateInitMixIn, self).__init__()
            setattr(self, "inited", True)
        #delattr(self, "__getattribute__")
        return getattr(attr)



class Base(object):
    def __init__(self):
        print "Base initialization"
        self.base = True
class LateInit(LateInitMixIn, Base): pass

def main():
    S = LateInit()
    print S
    print
    print "Should do Base init after now"
    print S.base
    print S.base

if __name__=="__main__": main()




This gives the following output:
LateInit initialization
<__main__.LateInit object at 0x2a960c1c50>

Should do Base init after now
Doing __getattribute__
Base initialization
True
Doing __getattribute__
True





More information about the Python-list mailing list