[Python-Dev] recursive closures - reference cycle (original) (raw)

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Dec 9 23:00:47 CET 2009


Kristján Valur Jónsson wrote:

Yes, and a number of different workarounds. That's not really the issue. The issue is that what looks like a perfectly safe idiom (calling a function recursively) happens to create a reference cycle if that function is a closure. This is a non-obvious "gotcha" that I must now educate my team about.

Documentation seems to be about the only thing that can be done about this. Recursion inherently involve self-reference, and that's going to create reference cycles somewhere, somehow.

You get a reference cycle with top-level recursion too, the only difference is that just one cycle is created when the module is imported, rather than one every time you call the function.

This is only a problem if you care about avoiding cycles, and if you do, this is just one of many subtle ways of creating them.

It's hard to tell where abouts in the docs to put information about this, however. It really relates to a certain pattern of using language features rather than to any particular feature.

Maybe there should be a section devoted to avoidance of reference cycles where all of these known pitfalls can be pointed out.

-- Greg



More information about the Python-Dev mailing list