SuperBiasedMan
SuperBiasedMan

Reputation: 9969

What's the use of a circular reference?

In Python you can append a list to itself and it will accept the assignment.

>>> l = [0,1]
>>> l.append(l)
>>> l
[0, 1, [...]]
>>> l[-1]
[0, 1, [...]]

My question is why?

Python allows this rather than throwing an error, is that because there's a potential use for it or is it just because it wasn't seen as necessary to explicitly forbid this behaviour?

Upvotes: 9

Views: 244

Answers (1)

Score_Under
Score_Under

Reputation: 1216

is that because there's a potential use for it or is it just because it wasn't seen as necessary to explicitly forbid this behaviour?

Both. Lists store references, and there is no reason to prevent them from storing certain otherwise-valid references.

As for potential uses, consider a generic top-down-shooter type video game:

  • A Level contains a reference to each Enemy, so that it can draw and update them each frame.
  • An Enemy contains a reference to its Level, so that it can (for example) query the distance to the Player or spawn a Bullet in the Level.

Upvotes: 4

Related Questions