On Fri, Mar 2, 2018 at 4:46 PM, Ian Kelly <ian.g.ke...@gmail.com> wrote: > On Thu, Mar 1, 2018 at 10:35 PM, Chris Angelico <ros...@gmail.com> wrote: >> On Fri, Mar 2, 2018 at 4:16 PM, Ian Kelly <ian.g.ke...@gmail.com> wrote: >>> On Wed, Feb 28, 2018 at 8:00 PM, Chris Angelico <ros...@gmail.com> wrote: >>>> Not off hand, but I can provide an EXTREMELY real-world example of a >>>> fairly tight loop: exceptions. An exception has a reference to the >>>> local variables it came from, and those locals may well include the >>>> exception itself: >>>> >>>> try: >>>> 1/0 >>>> except Exception as e: >>>> print(e) >>>> >>>> The ZeroDivisionError has a reference to the locals, and 'e' in the >>>> locals refers to that very exception object. >>> >>> The problem with this example of course is that the variable 'e' is >>> scoped to the except block and automatically del'ed when it exits. >> >> Or, to be more accurate: The language design acknowledges that this >> reference cycle is a fundamental problem, and the *solution* is that >> there's an implicit "e = None; del e" at the end of the except block. >> >> You can easily defeat that protection with "except Exception as ee: e >> = ee", if you want to demonstrate the cycle. > > Yes, but how often does this happen in practice? This situation was > billed as "an EXTREMELY real-world example". In the real world, most > of the time when you have an exception, you log it or handle it, and > then you discard it.
The exception object itself is the cycle. The fact that the language has a default way of handling this doesn't change that. What happens, for instance, when you have another exception inside the except block, and they chain? Once the top-level exception is freed, there's still a definite reference cycle in the original. Or what if you have an interactive debugger that lets you inspect objects at point of crash? That's going to work by retaining a reference to the exception. So, yep, this is stuff that happens every day. Not contrived, not uncommon. ChrisA -- https://mail.python.org/mailman/listinfo/python-list