Actually this works for all classes but classes that have a __del__
(and this is not a web2py specific problem) so for now:

Attention: do not define classes with a __del__ method in models or
controllers.

Even if you do not use web2py but use another framework, do not create
classes with __del__ methods if they may have self references, whether
or not you use exec.

Here is an example of a python program without exec that has the leak
we are talking about:

class Foo(object):
    def __del__(self):
        pass
while True:
    foo = Foo()
    foo.x = foo



On Jan 7, 6:56 pm, Massimo Di Pierro <massimo.dipie...@gmail.com>
wrote:
> Mitsuhiko on reddit brings up a good issue that I was not aware of: a
> bug in exec.
>
> code="""
> class Foo(object):
>     def __del__(self):
>         pass
> foo = Foo()
> """
> while True: exec code in {}
>
> causes a memory leak. Web2py does this. The memory leak is small in
> practice and in fact nobody noticed it. Yet it is a concern, in
> theory.
>
> So far I have the current solution
>
> code="""
> class Foo(object):
>     def __del__(self):
>         pass
> foo = Foo()
> """
> import gc
> while True:
>     exec code in {}
>     gc.collect()
>
> It works for me and I cannot reproduce the leak.
> I patched trunk with this. Give it a try and let me know what you
> think.
>
> Massimo

Reply via email to