[Tutor] Clueless

Alan Gauld alan.gauld at blueyonder.co.uk
Sun Mar 14 17:48:17 EST 2004


> I can't even give this one a good subject line, I'm so clueless.

I'm not totally sure on this one but a scan of the code shows 
up one strangeness at least:

> 
>   Logger                       object
>    /|\                        /|\  /|\
>     |                          |    |
>   Watched  --------------------     |
>    /|\                            list
>     |                              /|\
>     |                               |
>   WatchedList  ---------------------
> 
> All is cool as long as I don't implement Logger.__del__
> 

WAtched is a subnclass of Logger so inherits Loggers del method.
But...

> class Watched(object, Logger):
>     def __init__(self, log_name):
>         self.log = Logger(log_name + '.log')

INstead of initisalising the inherited file you choose to also 
have a Logger object have a reference to a logger. Thats OK of 
course but it does mean we eff4ectively have two Logger instances 
in the program each with a __del__ defined, but only one of them 
with file defined...

> class WatchedList(Watched, list):
>     def __init__(self, log_name, init_list = None):
>         Watched.__init__(self, log_name)
>         if init_list:
>             list.__init__(self, init_list)

And Watched List also drives indirectly from Logger, so instsances 
of this will also have a __del__ method, and they use the Watched 
initialiser so that they too have a loger attached, so again two 
instances of Leggoer exist...

> assets = WatchedList('assets')

So assets is a logger and references a logger...

> # >>> assets
> # []
> # >>> assets += [2,4,6]
> # >>> assets[0]
> # 2
> # >>> assets.max = max(assets)
> # >>> assets.max
> # 6
> # >>> del assets

So we now remove the reference to assets which gets GC'd, including 
it's associated logger object. The associated object has a file so 
its del works OK but assets never did have a valid file attribute 
so closing it will cause a problem....

Maybe your del should look like

def __del__(self):
    if self.file: self.file.close()

At least, I think thats the problem....
Although maybe its more to do with the design. Is Watched 
really a logger? Or does it just use one?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list