Setting dict value to itself creates infinite copies

Viewed 89

Recently I saw a piece of code that I can't understand. Here's the example:

a = {}
a['value'] = a

print(a)
>>>> {'value': {...}}

As a result, this creates an infinite number of copies of the initial dict, someting like:

{
    'value': {
      'value': {
        'value': {
                  ...
        }
      }
    }
}

So, why is this happening? Is this some kind of recursive thing?

2 Answers

Your code does not copy anything. Python understands that your variable is recursive, that is, it references itself, and doesn't try to print the same thing forever. Instead it breaks the circular reference with writing ....

You can be sure that a["value"] is indeed not a copy of your dictionary using the is keyword:

>>> a = {}
>>> a["value"] = a
>>> a["value"] is a # they are the same object
True
>>> 

It is not really a recursion, but more just a referencing loop.

When you do

a['value'] = a

You are setting the same dictionary, the same object, as the paired value of the key which is named 'value'.

So essentially it is just referencing itself. The important part from that being that it won't crash due to infinite printing, it understands the self-reference.

You will likely run into quite a bit of confusion with python if you are coming from many other languages, since the referencing is used quite a lot. You can find some more reading in the documentation, oreilly also has a neat post about some of it here.

Related