On Wed, 28 Feb 2018 18:46:05 -0800, Rick Johnson 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"


Of course it is a contrived example: it is close to the simplest possible 
example of a reference cycle. Its not intended as an example of useful 
code.

(Useful or not, your interpreter better not crash when faced with a cycle 
like this.)

But of course there are uses for objects to hold a reference to 
themselves. If you're writing a general purpose collection (say, a list 
or dict) then you better be able to cope with the case that somebody puts 
your list in itself:

L = []
L.append(L)

either directly, as above, or indirectly.

And that's the point really: cycles don't just occur when an object holds 
a reference to itself. They occur when one object holds a reference to 
another object, which holds a reference to a third, which holds a 
reference to a fourth (and so on...), which eventually holds a reference 
to the original again.

Cycles are useful. For example, you might think of a window which holds a 
reference to a control, which in turn needs a reference to its owning 
window. Or a network which contains loops, say a network of streets, or 
networks of disease transmission (I caught the stomach bug from Bob, who 
caught it from Sally, who caught it from Georgina, who originally caught 
it from me the *first* time I had it).

It shouldn't take much imagination to think of cycles in real life which 
you may want to model in a program.

https://en.wikipedia.org/wiki/I'm_My_Own_Grandpa





-- 
Steve

-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to