Wednesday, September 23, 2015

Loopy references

This may not come as a surprise to experienced Python programmers, but objects in Python can reference or "contain" themselves and/or their parent objects.

A trivial example, the self-containing list:

>>> a = []
>>> a.append(a)
>>> a
[[...]]

Kind of a cool repr, at least. How else could you flatly represent this infinitely nested object? What happens when you take two of these and smash them together with an equals comparator?

>>> b = []
>>> b.append(b)
>>> a == b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: maximum recursion depth exceeded in cmp


Like two mirrors pointed at one another, they compare back and forth forever, or at least for...

>>> sys.getrecursionlimit()
1000 

... loops.

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Free vehicle voucher codes open at Debenhams. Never miss a Debenhams voucher code ... Completed Debenhams vouchers - they may safeguarding work!
    By: https://www.voucherpro.co.uk/

    ReplyDelete