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: >> On Thu, Mar 1, 2018 at 1:46 PM, Rick Johnson >> <rantingrickjohn...@gmail.com> wrote: >>> On Wednesday, February 28, 2018 at 5:02:17 PM UTC-6, Chris Angelico wrote: >>> >>>> Here's one example: reference cycles. When do they get detected? >>>> Taking a really simple situation: >>>> >>>> class Foo: >>>> def __init__(self): >>>> self.self = self >>> >>> *shudders* >>> >>> Can you provide a real world example in which you need an >>> object which circularly references _itself_? This looks like >>> a highly contrived example used to (1) merely win the >>> argument, and (2) Bump fib() up one position from it's >>> current position as "the worst introductory example of how >>> to write a function in the history of programming tutorials" >> >> 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. ChrisA -- https://mail.python.org/mailman/listinfo/python-list